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);
        }
 /// <summary>
 /// Получить эффект
 /// </summary>
 /// <param name="FileName"></param>
 /// <param name="inputElement"></param>
 /// <returns></returns>
 public static EffectContainer LoadEffect(string FileName, InputElement[] inputElement)
 {
     string Origin = FileName;
     if (Effects.ContainsKey(Origin) && Effects[Origin].IsAlive)
     {
         //Уже есть
         EffectContainer t = (EffectContainer)Effects[Origin].Target;
         return t;
     }
     else
     {
         //нужно загрузить
         if (File.Exists(FileName + ".fx"))
         {
             FileName += ".fx";
         }
         else if (File.Exists(FileName + ".ees"))
         {
             FileName += ".ees";
         }
         EffectContainer t = new EffectContainer(ModelViewer.Program.device, FileName, inputElement);
         t.Name = Origin;
         WeakReference wr = new WeakReference(t, false);
         Effects.Add(Origin, wr);
         return t;
         //TODO проверка на валидность загрузки
     }
 }
示例#3
0
        private void InitScene()
        {
            D3D11.InputElement[] inputElements = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0)
            };

            using (CompilationResult vsResult = ShaderBytecode.CompileFromFile("vs.hlsl", "main", "vs_4_0", ShaderFlags.Debug))
            {
                vs         = new D3D11.VertexShader(device, vsResult.Bytecode.Data);
                vertLayout = new D3D11.InputLayout(device, vsResult.Bytecode, inputElements);
            }

            using (CompilationResult psResult = ShaderBytecode.CompileFromFile("ps.hlsl", "main", "ps_4_0", ShaderFlags.Debug))
                ps = new D3D11.PixelShader(device, psResult.Bytecode.Data);

            deviceContext.VertexShader.Set(vs);
            deviceContext.PixelShader.Set(ps);

            verts = new RawVector3[] {
                new RawVector3(0.0f, 0.5f, 0.5f),
                new RawVector3(0.5f, -0.5f, 0.5f),
                new RawVector3(-0.5f, -0.5f, 0.5f)
            };
            vertBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.VertexBuffer, verts);
            deviceContext.InputAssembler.SetVertexBuffers(0,
                                                          new D3D11.VertexBufferBinding(vertBuffer, Utilities.SizeOf <RawVector3>(), 0));

            deviceContext.InputAssembler.InputLayout       = vertLayout;
            deviceContext.InputAssembler.PrimitiveTopology = D3D.PrimitiveTopology.TriangleList;
        }
        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);
        }
 public EffectSignatureLayout(InputElement[] inputElements, byte[] signature)
 {
     InputElements = inputElements;
     ShaderSignature = signature;
     inputElementsHashCode = InputElements.Aggregate(InputElements.Length, (current, inputElement) => (current * 397) ^ inputElement.GetHashCode());
     inputElementsHashCode = (inputElementsHashCode * 397) ^ ShaderSignature.GetHashCode();
 }
示例#6
0
 public static InputLayout GetInputLayout(Device device, CompilationResult vertexShaderByteCode)
 {
     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 = LightShader.Vertex.AppendAlignedElement1,
             Classification = InputClassification.PerVertexData,
             InstanceDataStepRate = 0
         }
     };
     return new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
 }
示例#7
0
        /// <summary>
        /// Function to convert this input layout into a Direct3D input layout.
        /// </summary>
        /// <param name="device">Direct 3D device object.</param>
        /// <returns>The Direct 3D 11 input layout.</returns>
        internal D3D.InputLayout Convert(D3D.Device device)
        {
            if (D3DLayout != null)
            {
                return(D3DLayout);
            }

            // If the shader that's linked to this layout is gone, then don't bother with a new layout object.
            if (Shader.D3DByteCode == null)
            {
                return(null);
            }

            var elements = new D3D.InputElement[_elements.Length];

            for (int i = 0; i < elements.Length; i++)
            {
                elements[i] = _elements[i].Convert();
            }

            D3DLayout = new D3D.InputLayout(device, Shader.D3DByteCode, elements)
            {
                DebugName = "Gorgon Input Layout '" + Name + "'"
            };

            return(D3DLayout);
        }
        public override void InitShaders(ref Device device)
        {
            ShaderBytecode vertexShaderByteCode =
                ShaderBytecode.CompileFromFile(@"Shader/basicShaders.hlsl", "VShader", "vs_4_0");

            ShaderBytecode pixelShaderByteCode =
                ShaderBytecode.CompileFromFile(@"Shader/basicShaders.hlsl", "PShader", "ps_4_0");

            _deviceContext = device.ImmediateContext;
            _deviceContext.VertexShader.Set(new VertexShader(device, vertexShaderByteCode));
            _deviceContext.PixelShader.Set(new PixelShader(device, pixelShaderByteCode));

            //----

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR"   , 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 16, 0),
            };

            _deviceContext.InputAssembler.InputLayout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), elements);

            Vertex[] vertices = new Vertex[]
            {
                new Vertex(0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f),
                new Vertex(0.5f, -.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f),
                new Vertex(-.5f, -.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f),
            };

            BufferDescription description = new BufferDescription(32 * 3, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            _vertexBuffer = Buffer.Create(device, vertices, description);
        }
示例#9
0
        public IShader LoadVS(string path, Type constantsType = null)
        {
            using (var cr = ShaderBytecode.CompileFromFile(path, "main", "vs_5_0", DEBUG_FLAG)) {
                if (cr.Bytecode == null)
                {
                    throw new Exception(cr.Message);
                }

                var gpuShader = new D3D11.VertexShader(Graphics.Device, cr);

                var inputElements = new D3D11.InputElement[] {
                    new D3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new D3D11.InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                };

                var inputSignature = ShaderSignature.GetInputSignature(cr);
                var inputLayout    = new D3D11.InputLayout(Graphics.Device, inputSignature, inputElements);

                var shader = new SharpDXShader(Graphics, gpuShader, inputLayout, constantsType);

                m_Shaders.Add(shader);

                return(shader);
            }
        }
示例#10
0
        public VertexElement(string semantic, int index, int components, DataType dataType = DataType.Float, bool normalized = false, int slot = 0, bool instanceData = false)
        {
            mDescription = new InputElement
            {
                AlignedByteOffset = InputElement.AppendAligned,
                Classification = instanceData ? InputClassification.PerInstanceData : InputClassification.PerVertexData,
                InstanceDataStepRate = instanceData ? 1 : 0,
                SemanticIndex = index,
                SemanticName = semantic,
                Slot = slot
            };

            if(dataType == DataType.Byte)
            {
                switch(components)
                {
                    case 1:
                        mDescription.Format = normalized ? Format.R8_UNorm : Format.R8_UInt;
                        break;

                    case 2:
                        mDescription.Format = normalized ? Format.R8G8_UNorm : Format.R8G8_UInt;
                        break;

                    case 4:
                        mDescription.Format = normalized ? Format.R8G8B8A8_UNorm : Format.R8G8B8A8_UInt;
                        break;

                    default:
                        throw new ArgumentException("Invalid combination of data type and component count");
                }
            }
            else
            {
                switch(components)
                {
                    case 1:
                        mDescription.Format = Format.R32_Float;
                        break;

                    case 2:
                        mDescription.Format = Format.R32G32_Float;
                        break;

                    case 3:
                        mDescription.Format = Format.R32G32B32_Float;
                        break;

                    case 4:
                        mDescription.Format = Format.R32G32B32A32_Float;
                        break;

                    default:
                        throw new ArgumentException("Invalid combination of data type and component count");
                }
            }
        }
示例#11
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.InputLayout" /> object to describe the
 ///   input-buffer data for the input-assembler stage.
 /// </summary>
 /// <unmanaged>ID3D11Device::CreateInputLayout</unmanaged>
 /// <param name = "device">The device used to create the layout.</param>
 /// <param name = "elements">An array of input elements describing the layout of the input data.</param>
 /// <param name = "shaderBytecode">The compiled shader used to validate the input elements.</param>
 public InputLayout(Device device, byte[] shaderBytecode, InputElement[] elements)
     : base(IntPtr.Zero)
 {
     unsafe
     {
         fixed (void* pBuffer = shaderBytecode)
             device.CreateInputLayout(elements, elements.Length, (IntPtr)pBuffer, shaderBytecode.Length,  this);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="VertexArrayLayout"/> class.
        /// </summary>
        /// <param name="inputElements">The input elements.</param>
        /// <exception cref="System.ArgumentNullException">inputElements</exception>
        public VertexArrayLayout(InputElement[] inputElements)
        {
            if (inputElements == null) throw new ArgumentNullException("inputElements");

            this.InputElements = inputElements;
            hashCode = inputElements.Length;
            for (int i = 0; i < inputElements.Length; i++)
            {
                hashCode = (hashCode * 397) ^ inputElements[i].GetHashCode();
            }
        }
示例#13
0
        public Style(String vertexShaderFilename, String pixelShaderFilename, InputElement[] layoutElements, int floatsPerVertex, DeviceManager deviceManager)
        {
            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            // Read pre-compiled shader byte code relative to current directory
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\" + vertexShaderFilename);
            this.pixelShader = new PixelShader(deviceManager.DeviceDirect3D, NativeFile.ReadAllBytes(path + "\\" + pixelShaderFilename));
            this.vertexShader = new VertexShader(deviceManager.DeviceDirect3D, vertexShaderByteCode);

            // Specify the input layout for the new style
            this.layout = new InputLayout(deviceManager.DeviceDirect3D, vertexShaderByteCode, layoutElements);
            this.floatsPerVertex = floatsPerVertex;
        }
        /// <summary>
        /// Function to convert this input layout into a Direct3D input layout.
        /// </summary>
        private void BuildD3DLayout()
        {
            // ReSharper disable once InconsistentNaming
            var d3dElements = new D3D11.InputElement[_elements.Length];

            for (int i = 0; i < _elements.Length; ++i)
            {
                d3dElements[i] = _elements[i].D3DInputElement;
            }

            _d3DInputLayout = new D3D11.InputLayout(Graphics.D3DDevice, Shader.D3DByteCode.Data, d3dElements)
            {
                DebugName = $"{Name} Direct 3D 11 Input Layout"
            };
        }
示例#15
0
        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);
        }
示例#16
0
 public SimpleShader GetNewOrCachedShader(
     Device device,
     DeviceContext context,
     string filename,
     string vsEntryPoint,
     string psEntryPoint,
     InputElement[] inputElements)
 {
     SimpleShader shader;
     if (!shaders.TryGetValue(filename, out shader))
     {
         shader = new SimpleShader(device, context, filename, vsEntryPoint, psEntryPoint, inputElements);
         shaders.Add(filename, shader);
     }
     return shader;
 }
示例#17
0
        public static InputLayout GetLayout(GxContext context, InputElement[] elements, Mesh mesh, ShaderProgram program)
        {
            Dictionary<ShaderProgram, InputLayout> meshEntry;
            InputLayout layout;

            if (Layouts.TryGetValue(mesh, out meshEntry))
            {
                if (meshEntry.TryGetValue(program, out layout))
                    return layout;

                layout = new InputLayout(context.Device, program.VertexShaderCode.Data, elements);
                meshEntry.Add(program, layout);
                return layout;
            }

            bool hasInstance = false, hasVertex = false;

            for(var i = 0; i < elements.Length; ++i)
            {
                if (hasInstance && hasVertex)
                    break;

                if(elements[i].Classification == InputClassification.PerInstanceData && hasInstance == false)
                {
                    elements[i].AlignedByteOffset = 0;
                    hasInstance = true;
                    continue;
                }

                if(elements[i].Classification == InputClassification.PerVertexData && hasVertex == false)
                {
                    elements[i].AlignedByteOffset = 0;
                    hasVertex = true;
                }
            }

            layout = new InputLayout(context.Device, program.VertexShaderCode.Data, elements);
            meshEntry = new Dictionary<ShaderProgram, InputLayout>()
            {
                {program, layout}
            };

            Layouts.Add(mesh, meshEntry);
            return layout;
        }
示例#18
0
        public Shader(Device device, string shaderFile, string vertexTarget, string pixelTraget, InputElement[] layouts)
        {
            var shaderString = ShaderBytecode.PreprocessFromFile(shaderFile);

            using (var bytecode = ShaderBytecode.Compile(shaderString, vertexTarget, "vs_4_0"))
            {
                layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), layouts);
                vertShader = new VertexShader(device, bytecode);
            }

            using (var bytecode = ShaderBytecode.Compile(shaderString, pixelTraget, "ps_4_0"))
            {
                pixShader = new PixelShader(device, bytecode);
            }

            OnCleanup += vertShader.Dispose;
            OnCleanup += pixShader.Dispose;
            OnCleanup += layout.Dispose;
        }
        private VertexArrayObject(GraphicsDevice graphicsDevice, EffectInputSignature shaderSignature, IndexBufferBinding indexBufferBinding, VertexBufferBinding[] vertexBufferBindings)
            : base(graphicsDevice)
        {
            this.vertexBufferBindings = vertexBufferBindings;
            this.indexBufferBinding = indexBufferBinding;
            this.EffectInputSignature = shaderSignature;

            // Calculate Direct3D11 InputElement
            int inputElementCount = vertexBufferBindings.Sum(t => t.Declaration.VertexElements.Length);
            var inputElements = new InputElement[inputElementCount];

            int j = 0;
            for (int i = 0; i < vertexBufferBindings.Length; i++)
            {
                var declaration = vertexBufferBindings[i].Declaration;
                vertexBufferBindings[i].Buffer.AddReferenceInternal();
                foreach (var vertexElementWithOffset in declaration.EnumerateWithOffsets())
                {
                    var vertexElement = vertexElementWithOffset.VertexElement;
                    inputElements[j++] = new InputElement
                        {
                            Slot = i,
                            SemanticName = vertexElement.SemanticName,
                            SemanticIndex = vertexElement.SemanticIndex,
                            AlignedByteOffset = vertexElementWithOffset.Offset,
                            Format = (SharpDX.DXGI.Format)vertexElement.Format,
                        };
                }
            }

            Layout = VertexArrayLayout.GetOrCreateLayout(new VertexArrayLayout(inputElements));

            if (indexBufferBinding != null)
            {
                indexBufferBinding.Buffer.AddReferenceInternal();
                indexBufferOffset = indexBufferBinding.Offset;
                indexFormat = (indexBufferBinding.Is32Bit ? SharpDX.DXGI.Format.R32_UInt : SharpDX.DXGI.Format.R16_UInt);
            }

            CreateResources();
        }
        public PhysicsDebugDraw(SharpDX11Graphics graphics)
        {
            device = graphics.Device;
            inputAssembler = device.ImmediateContext.InputAssembler;

            InputElement[] elements = new InputElement[]
            {
                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>
        /// Function to normalize the offsets in the element list.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is used to rebuild the offsets for the elements assigned to this layout. Ensure that this input layout is not bound to the pipeline before normalizing. Otherwise, an invalid binding will
        /// occur.
        /// </para>
        /// <para>
        /// This will use the order of the elements as they appear in the list passed to this object to determine the offsets.
        /// </para>
        /// </remarks>
        public void NormalizeOffsets()
        {
            int lastOffset = 0;

            var elements = new D3D11.InputElement[_elements.Length];

            for (int i = 0; i < _elements.Length - 1; i++)
            {
                GorgonInputElement oldElement = _elements[i];
                _elements[i] = new GorgonInputElement(oldElement.Context,
                                                      oldElement.Format,
                                                      lastOffset,
                                                      oldElement.Index,
                                                      oldElement.Slot,
                                                      oldElement.Instanced,
                                                      oldElement.InstanceCount);
                lastOffset += oldElement.SizeInBytes;
                elements[i] = _elements[i].D3DInputElement;
            }

            BuildD3DLayout();
        }
示例#22
0
		private void CreateVertexDeclaration()
		{
			int elementIndex = 0;
			var vertexElements = new InputElement[Format.Elements.Length];
			foreach (var vertexElement in Format.Elements)
				if (vertexElement.ElementType == VertexElementType.Position3D)
					vertexElements[elementIndex++] = GetVertexPosition3D(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.Position2D)
					vertexElements[elementIndex++] = GetVertexPosition2D(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.Color)
					vertexElements[elementIndex++] = GetVertexColor(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.TextureUV)
					vertexElements[elementIndex++] = GetVertexTextureCoordinate(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.LightMapUV)
					vertexElements[elementIndex++] = GetVertexLightMapUV(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.Normal)
					vertexElements[elementIndex++] = GetVertexNormal3D(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.SkinIndices)
					vertexElements[elementIndex++] = GetVertexSkinIndices(vertexElement.Offset);
				else if (vertexElement.ElementType == VertexElementType.SkinWeights)
					vertexElements[elementIndex++] = GetVertexSkinWeights(vertexElement.Offset);
			inputLayout = new InputLayout(nativeDevice, vertexShaderBytecode, vertexElements);
		}
示例#23
0
        private void PlatformConstruct(
            VertexAttributeDescription[] attributeDescriptions,
            VertexLayoutDescription[] layoutDescriptions)
        {
            DeviceInputElements = new D3D11.InputElement[attributeDescriptions.Length];
            for (var i = 0; i < attributeDescriptions.Length; i++)
            {
                var attributeDescription = attributeDescriptions[i];
                var layoutDescription    = layoutDescriptions[attributeDescription.BufferIndex];

                DeviceInputElements[i] = new D3D11.InputElement
                {
                    AlignedByteOffset    = attributeDescription.Offset,
                    Classification       = layoutDescription.Classification.ToInputClassification(),
                    Format               = attributeDescription.Format.ToDxgiFormat(),
                    InstanceDataStepRate = (layoutDescription.Classification == InputClassification.PerInstanceData) ? 1 : 0,
                    SemanticIndex        = attributeDescription.SemanticIndex,
                    SemanticName         = attributeDescription.SemanticName,
                    Slot = attributeDescription.BufferIndex
                };
            }

            _layoutDescriptions = layoutDescriptions;
        }
示例#24
0
 private static InputLayout BuildLayout(Effect effect, Device device, string techniqueName, InputElement[] elements)
 {
     EffectTechnique technique = effect.GetTechniqueByName(techniqueName);
     var passDescription = technique.GetPassByIndex(0).Description;
     return new InputLayout(device, passDescription.Signature, elements);
 }
        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
        }
        private static List<InputElement> InputElementsFromSpec(IEnumerable<ShaderInputElementSpec> specs, Dictionary<ShaderInputElementPurpose, int> typeCount, bool isInstanceData)
        {
            var list = new List<InputElement>();
            var slot = isInstanceData ? 1 : 0;
            var stepRate = isInstanceData ? 1 : 0;
            var offset = 0;
            var classification = isInstanceData ? InputClassification.PerInstanceData : InputClassification.PerVertexData;

            foreach(var spec in specs)
            {
                var semantic = _semantics[spec.Purpose];
                var format = _formats[spec.Format];
                var elementSize = _elementSizes[spec.Format];
                int elementCount;
                if(!_elementCountsByFormat.TryGetValue(spec.Format, out elementCount))
                    elementCount = 1;
                int n;
                typeCount.TryGetValue(spec.Purpose, out n);

                for(var i = 0; i < elementCount; i++)
                {
                    var element = new InputElement(semantic, i + n, format, offset, slot, classification, stepRate);
                    // Debug.WriteLine("new InputElement(\"{0}\", {1}, {2}, {3}, {4}, {5}, {6})", semantic, i + n, format, offset, slot, classification, stepRate);
                    list.Add(element);
                    offset += elementSize;
                }

                typeCount[spec.Purpose] = n + elementCount;
            }

            return list;
        }
示例#27
0
        static void Main(string[] args)
        {
            //Это быстро написанный код. Тут все переменные для DX11.
            RenderForm renderForm = new RenderForm();

            SharpDX.Direct3D11.Device device;
            SwapChain            swapChain;
            SwapChainDescription swapChainDescription;

            SharpDX.Viewport viewport;
            DeviceContext    deviceContext;
            ModeDescription  modeDescription;
            Texture2D        texture2D;
            RenderTargetView renderTargetView;



            //Устанавливаем параметры в переменные.
            renderForm.Width     = 640;
            renderForm.Height    = 480;
            modeDescription      = new ModeDescription(640, 480, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                ModeDescription   = modeDescription,
                IsWindowed        = true,
                OutputHandle      = renderForm.Handle
            };
            SharpDX.Direct3D11.Device.CreateWithSwapChain(
                DriverType.Hardware,
                SharpDX.Direct3D11.DeviceCreationFlags.None,
                swapChainDescription,
                out device,
                out swapChain);
            viewport      = new SharpDX.Viewport(0, 0, 640, 480);
            deviceContext = device.ImmediateContext;
            deviceContext.Rasterizer.SetViewport(viewport);
            texture2D        = swapChain.GetBackBuffer <Texture2D>(0);
            renderTargetView = new RenderTargetView(device, texture2D);



            //Шейдеры.
            ShaderSignature inputSignature;
            VertexShader    vertexShader;
            PixelShader     pixelShader;
            InputLayout     inputLayout;

            Vector3[] vertices;
            SharpDX.Direct3D11.Buffer buffer;
            ShaderBytecode            vertexShaderByteCode;
            ShaderBytecode            pixelShaderByteCode;

            SharpDX.Direct3D11.InputElement[] inputElements;


            inputElements = new SharpDX.Direct3D11.InputElement[]
            {
                new SharpDX.Direct3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
                new SharpDX.Direct3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0)
            };
            vertices = new Vector3[]
            {
                new Vector3(0, 0, 0),
                new Vector3(0, 240, 0),
                new Vector3(320, 120, 0)
            };
            buffer = SharpDX.Direct3D11.Buffer.Create(device, SharpDX.Direct3D11.BindFlags.VertexBuffer, vertices);

            VertexPositionColor[] vrt = new VertexPositionColor[]
            {
                new VertexPositionColor(new Vector3(-0.5f, 0.5f, 0.0f), SharpDX.Color.Red),
                new VertexPositionColor(new Vector3(0.5f, 0.5f, 0.0f), SharpDX.Color.Green),
                new VertexPositionColor(new Vector3(0.0f, -0.5f, 0.0f), SharpDX.Color.Blue)
            };

            vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug);
            inputSignature       = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            vertexShader         = new SharpDX.Direct3D11.VertexShader(device, vertexShaderByteCode);



            pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug);
            pixelShader         = new SharpDX.Direct3D11.PixelShader(device, pixelShaderByteCode);



            deviceContext.VertexShader.Set(vertexShader);
            deviceContext.PixelShader.Set(pixelShader);
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            inputLayout = new SharpDX.Direct3D11.InputLayout(device, inputSignature, inputElements);
            deviceContext.InputAssembler.InputLayout = inputLayout;



            //Используем.
            deviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            deviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178));
            deviceContext.Draw(0, 0);
            swapChain.Present(1, PresentFlags.None);
            renderForm.Show();



            //Очистка всего.
            renderTargetView.Dispose();
            texture2D.Dispose();
            deviceContext.Dispose();
            swapChain.Dispose();
            device.Dispose();
            renderForm.Dispose();
        }
示例#28
0
 /// <summary>
 /// Determines whether the specified <see cref="InputElement"/> is equal to this instance.
 /// </summary>
 /// <param name="other">The <see cref="InputElement"/> to compare with this instance.</param>
 /// <returns>
 ///   <c>true</c> if the specified <see cref="InputElement"/> is equal to this instance; otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(InputElement other)
 {
     return Equals(other.SemanticName, SemanticName) && other.SemanticIndex == SemanticIndex && Equals(other.Format, Format) && other.Slot == Slot && other.AlignedByteOffset == AlignedByteOffset && Equals(other.Classification, Classification) && other.InstanceDataStepRate == InstanceDataStepRate;
 }
示例#29
0
        public MeshFactory(Demo demo)
        {
            this.demo = demo;
            this.device = demo.Device;
            this.inputAssembler = device.ImmediateContext.InputAssembler;

            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, demo.GetEffectPass().Description.Signature, elements);
        }
示例#30
0
        public void Init(Form form)
        {
            ViewportSize  = new Size2F(form.Width, form.Height);
            hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f);

            ModeDescription      backBufferDesc = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDesc  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
            };

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext;

            d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height);
            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default();
            blendStateDesc.AlphaToCoverageEnable                 = false;
            blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.One;         //
            blendStateDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.SourceAlpha; //Zero
            blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha;
            blendStateDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendState = new D3D11.BlendState(d3dDevice, blendStateDesc);

            Fonts = new Detail.FontCache(this);

            var layout2d = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0),
                new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0),
            };

            var layout3d = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0),
            };

            var vertexShaderOutput2d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode2d, "main", "vs_4_0", ShaderFlags.Debug);
            var vertexShaderOutput3d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode3d, "main", "vs_4_0", ShaderFlags.Debug);
            var pixelShaderOutput    = ShaderBytecode.Compile(Detail.Shaders.pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug);

            Detail.Shaders.VertexShader2D = new D3D11.VertexShader(Device, vertexShaderOutput2d);
            Detail.Shaders.VertexShader3D = new D3D11.VertexShader(Device, vertexShaderOutput3d);
            Detail.Shaders.PixelShader    = new D3D11.PixelShader(Device, pixelShaderOutput);

            Detail.Shaders.InputLayout2D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput2d), layout2d);
            Detail.Shaders.InputLayout3D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput3d), layout3d);

            IntPtr data  = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4);
            var    white = BitConverter.GetBytes(1f);

            for (int i = 0; i < 4 * 4; i++)
            {
                for (int j = 0; j < white.Length; j++)
                {
                    System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]);
                }
            }

            White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription
            {
                Width             = 4,
                Height            = 4,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Dynamic,
                CpuAccessFlags    = D3D11.CpuAccessFlags.Write,
                Format            = Format.R32G32B32A32_Float,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new DXGI.SampleDescription(1, 0),
            }, new DataBox[] { new DataBox(data, 4 * 2, 4) });

            System.Runtime.InteropServices.Marshal.FreeHGlobal(data);

            WhiteView = new D3D11.ShaderResourceView(Device, White);

            samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                Filter             = D3D11.Filter.MinMagMipLinear,
                AddressU           = D3D11.TextureAddressMode.Clamp,
                AddressV           = D3D11.TextureAddressMode.Clamp,
                AddressW           = D3D11.TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(1f, 0f, 1f, 1f),
                ComparisonFunction = D3D11.Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = 0,
                MaximumLod         = 16
            });

            transfBuffer = new SharpDX.Direct3D11.Buffer(Device,
                                                         new D3D11.BufferDescription(sizeof(float) * 4, D3D11.ResourceUsage.Dynamic, D3D11.BindFlags.ConstantBuffer,
                                                                                     D3D11.CpuAccessFlags.Write, D3D11.ResourceOptionFlags.None, sizeof(float)));

            DataStream stream;

            DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);

            stream.Write(hViewportSize.Width);
            stream.Write(hViewportSize.Height);

            DeviceContext.UnmapSubresource(transfBuffer, 0);

            DeviceContext.VertexShader.SetShader(vertexShader, null, 0);
            DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer);
            DeviceContext.PixelShader.SetShader(pixelShader, null, 0);
            DeviceContext.PixelShader.SetSampler(0, samplerState);
            DeviceContext.InputAssembler.InputLayout = inputLayout;
            DeviceContext.OutputMerger.BlendState    = blendState;

            cam = new Camera(this);
        }
示例#31
0
        public TextureShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "TexturePixelShader", "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 = "TEXCOORD",
                    SemanticIndex = 0,
                    Format = Format.R32G32_Float,
                    Slot = 0,
                    AlignedByteOffset = TextureShader.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<TextureShader.MatrixBuffer>(), // Contains three matrices
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                StructureByteStride = 0
            };
            ConstantMatrixBuffer = new SharpDX.Direct3D11.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.
            SamplerState = new SamplerState(device, samplerDesc);
        }
示例#32
0
 /// <summary>
 /// Gets a more helpful message for the SharpDX invalid arg error.
 /// </summary>
 /// <param name="inputElements">The input elements.</param>
 /// <returns>The exception message.</returns>
 private static string GetInvalidArgMessage(InputElement[] inputElements)
 {
     var elements = string.Join(", ", inputElements.Select(x => x.SemanticName + x.SemanticIndex));
     return "An error occurred while preparing to draw. "
            + "This is probably because the current vertex declaration does not include all the elements "
            + "required by the current vertex shader. The current vertex declaration includes these elements: "
            + elements + ".";
 }
示例#33
0
        public static InputLayout CreateInputLayout(Device dxDevice, ShaderSignature signature,
            LayoutElementType[] elementTypes)
        {
            InputElement[] elements = new InputElement[elementTypes.Length];

            int offset = 0;
            for(int i = 0; i < elements.Length; ++i)
            {
                var type = elementTypes[i];
                int size;
                var element = CreateInputElement(type, out size);
                element.AlignedByteOffset = offset;
                elements[i] = element;
                offset += size;
            }

            return new InputLayout(dxDevice, signature, elements);
        }
示例#34
0
        public static InputElement CreateInputElement(LayoutElementType type, out int elemSize)
        {
            InputElement element = new InputElement();
            switch(type & LayoutElementType.TypeMask)
            {
                case LayoutElementType.Position3:
                    element.SemanticName = "POSITION";
                    element.Format = SharpDX.DXGI.Format.R32G32B32_Float;
                    elemSize = 12;
                    break;
                case LayoutElementType.Position4:
                    element.SemanticName = "POSITION";
                    element.Format = SharpDX.DXGI.Format.R32G32B32A32_Float;
                    elemSize = 16;
                    break;
                case LayoutElementType.Normal3:
                    element.SemanticName = "NORMAL";
                    element.Format = SharpDX.DXGI.Format.R32G32B32_Float;
                    elemSize = 12;
                    break;
                case LayoutElementType.Normal4:
                    element.SemanticName = "NORMAL";
                    element.Format = SharpDX.DXGI.Format.R32G32B32A32_Float;
                    elemSize = 16;
                    break;
                case LayoutElementType.Color4:
                    element.SemanticName = "COLOR";
                    element.Format = SharpDX.DXGI.Format.R32G32B32A32_Float;
                    elemSize = 16;
                    break;
                case LayoutElementType.TexCoords2:
                    element.SemanticName = "TEXCOORD";
                    element.Format = SharpDX.DXGI.Format.R32G32_Float;
                    elemSize = 8;
                    break;
                default:
                    element.SemanticName = "POSITION";
                    element.Format = SharpDX.DXGI.Format.R32G32B32_Float;
                    elemSize = 12;
                    break;
            }

            switch(type & LayoutElementType.SlotMask)
            {
                case LayoutElementType.Slot0:
                    element.SemanticName += "0";
                    element.Slot = 0;
                    break;
                case LayoutElementType.Slot1:
                    element.SemanticName += "1";
                    element.Slot = 1;
                    break;
                case LayoutElementType.Slot2:
                    element.SemanticName += "2";
                    element.Slot = 2;
                    break;
                case LayoutElementType.Slot3:
                    element.SemanticName += "3";
                    element.Slot = 3;
                    break;
                default:
                    element.Slot = 0;
                    break;
            }

            return element;
        }
示例#35
0
        public static InputLayout CreateInputLayoutFromXml(Device dxDevice, ShaderSignature signature, XmlNode layoutNode)
        {
            InputElement[] elements = new InputElement[layoutNode.ChildNodes.Count];

            int offset = 0;
            XmlNode elemNode = layoutNode.FirstChild;
            for(int i = 0; i < elements.Length; ++i)
            {
                var type = ParseTypeFromXml(elemNode);
                int size;
                var element = CreateInputElement(type, out size);
                element.AlignedByteOffset = offset;
                elements[i] = element;
                offset += size;
                elemNode = elemNode.NextSibling;
            }

            return new InputLayout(dxDevice, signature, elements);
        }
示例#36
0
        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;
            };
        }
示例#37
0
        //Create meshes and add vertex and index buffers
        private void AddVertexData(Model model, Scene scene, Node node, Device device, ref Matrix transform)
        {
            Matrix previousTransform = transform;
            transform = Matrix.Multiply(previousTransform, FromMatrix(node.Transform));

            //also calculate inverse transpose matrix for normal/tangent/bitagent transformation
            Matrix invTranspose = transform;
            invTranspose.Invert();
            invTranspose.Transpose();

            if (node.HasMeshes)
            {
                foreach (int index in node.MeshIndices)
                {
                    //get a mesh from the scene
                    Assimp.Mesh mesh = scene.Meshes[index];

                    //create new mesh to add to model
                    ModelMesh modelMesh = new ModelMesh();
                    model.AddMesh(ref modelMesh);

                    //if mesh has a material extract the diffuse texture, if present
                    Material material = scene.Materials[mesh.MaterialIndex];
                    if (material != null && material.GetMaterialTextureCount(TextureType.Diffuse) > 0)
                    {
                        TextureSlot texture;
                        material.GetMaterialTexture(TextureType.Diffuse, 0, out texture);
                        //create new texture for mesh
                        modelMesh.AddTextureDiffuse(device, m_modelPath + "\\" + texture.FilePath);
                    }

                    //determine the elements in the vertex
                    bool hasTexCoords = mesh.HasTextureCoords(0);
                    bool hasColors = mesh.HasVertexColors(0);
                    bool hasNormals = mesh.HasNormals;
                    bool hasTangents = mesh.Tangents != null;
                    bool hasBitangents = mesh.BiTangents != null;

                    //create vertex element list 
                    InputElement[] vertexElements = new InputElement[GetNoofInputElements(mesh)];
                    uint elementIndex = 0;
                    vertexElements[elementIndex++] = new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0);
                    short vertexSize = (short)Utilities.SizeOf<Vector3>();

                    if (hasColors)
                    {
                        vertexElements[elementIndex++] = new InputElement("COLOR", 0, Format.R8G8B8A8_UInt, vertexSize, 0);
                        vertexSize += (short)Utilities.SizeOf<Color>();
                    }
                    if (hasNormals)
                    {
                        vertexElements[elementIndex++] = new InputElement("NORMAL", 0, Format.R32G32B32_Float, vertexSize, 0);
                        vertexSize += (short)Utilities.SizeOf<Vector3>();
                    }
                    if (hasTangents)
                    {
                        vertexElements[elementIndex++] = new InputElement("TANGENT", 0, Format.R32G32B32_Float, vertexSize, 0);
                        vertexSize += (short)Utilities.SizeOf<Vector3>();
                    }
                    if (hasBitangents)
                    {
                        vertexElements[elementIndex++] = new InputElement("BITANGENT", 0, Format.R32G32B32_Float, vertexSize, 0);
                        vertexSize += (short)Utilities.SizeOf<Vector3>();
                    }
                    if (hasTexCoords)
                    {
                        vertexElements[elementIndex++] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, vertexSize, 0);
                        vertexSize += (short)Utilities.SizeOf<Vector2>();
                    }

                    //set the vertex elements and size
                    modelMesh.InputElements = vertexElements;
                    modelMesh.VertexSize = vertexSize;

                    //get pointers to vertex data
                    Vector3D[] positions = mesh.Vertices.ToArray();
                    Vector3D[] texCoords = mesh.TextureCoordinateChannels[0].ToArray();
                    Vector3D[] normals = mesh.Normals.ToArray();
                    Vector3D[] tangents = mesh.Tangents.ToArray();
                    Vector3D[] biTangents = mesh.BiTangents.ToArray();
                    Color4D[] colours = mesh.VertexColorChannels[0].ToArray();

                    //also determine primitive type
                    switch (mesh.PrimitiveType)
                    {
                        case Assimp.PrimitiveType.Point:
                            modelMesh.PrimitiveTopology = PrimitiveTopology.PointList;
                            break;
                        case Assimp.PrimitiveType.Line:
                            modelMesh.PrimitiveTopology = PrimitiveTopology.LineList;
                            break;
                        case Assimp.PrimitiveType.Triangle:
                            modelMesh.PrimitiveTopology = PrimitiveTopology.TriangleList;
                            break;
                        default:
                            throw new Exception("ModelLoader::AddVertexData(): Unknown primitive type");
                    }

                    //create data stream for vertices
                    DataStream vertexStream = new DataStream(mesh.VertexCount * vertexSize, true, true);

                    for (int i = 0; i < mesh.VertexCount; i++)
                    {
                        //add position, after transforming it with accumulated node transform
                        {
                            Vector4 result;
                            Vector3 pos = FromVector(positions[i]);
                            Vector3.Transform(ref pos, ref transform, out result);
                            vertexStream.Write<Vector3>(new Vector3(result.X, result.Y, result.Z));
                        }

                        if (hasColors)
                        {
                            Color vertColor = FromColor(mesh.VertexColorChannels[0].ToArray()[i]);
                            vertexStream.Write<Color>(vertColor);
                        }
                        if (hasNormals)
                        {
                            Vector4 result;
                            Vector3 normal = FromVector(normals[i]);
                            Vector3.Transform(ref normal, ref invTranspose, out result);
                            vertexStream.Write<Vector3>(new Vector3(result.X, result.Y, result.Z));
                        }
                        if (hasTangents)
                        {
                            Vector4 result;
                            Vector3 tangent = FromVector(tangents[i]);
                            Vector3.Transform(ref tangent, ref invTranspose, out result);
                            vertexStream.Write<Vector3>(new Vector3(result.X, result.Y, result.Z));
                        }
                        if (hasBitangents)
                        {
                            Vector4 result;
                            Vector3 biTangent = FromVector(biTangents[i]);
                            Vector3.Transform(ref biTangent, ref invTranspose, out result);
                            vertexStream.Write<Vector3>(new Vector3(result.X, result.Y, result.Z));
                        }
                        if (hasTexCoords)
                        {
                            vertexStream.Write<Vector2>(new Vector2(texCoords[i].X, 1 - texCoords[i].Y));
                        }
                    }

                    vertexStream.Position = 0;

                    //create new vertex buffer
                    var vertexBuffer = new Buffer(device,
                                                    vertexStream,
                                                    new BufferDescription()
                                                    {
                                                        BindFlags = BindFlags.VertexBuffer,
                                                        CpuAccessFlags = CpuAccessFlags.None,
                                                        OptionFlags = ResourceOptionFlags.None,
                                                        SizeInBytes = mesh.VertexCount * vertexSize,
                                                        Usage = ResourceUsage.Default
                                                    }
                                                 );

                    //add it to the mesh
                    modelMesh.VertexBuffer = vertexBuffer;
                    modelMesh.VertexCount = mesh.VertexCount;
                    modelMesh.PrimitiveCount = mesh.FaceCount;

                    //get pointer to indices data
                    uint[] indices = mesh.GetUnsignedIndices();

                    //create data stream for indices
                    DataStream indexStream = new DataStream(indices.GetLength(0) * sizeof(uint), true, true);

                    for (int i = 0; i < indices.GetLength(0); i++)
                    {
                        indexStream.Write<uint>(indices[i]);
                    }

                    indexStream.Position = 0;

                    //create new index buffer
                    var indexBuffer = new Buffer(device,
                                                    indexStream,
                                                    new BufferDescription()
                                                    {
                                                        BindFlags = BindFlags.IndexBuffer,
                                                        CpuAccessFlags = CpuAccessFlags.None,
                                                        OptionFlags = ResourceOptionFlags.None,
                                                        SizeInBytes = indices.GetLength(0) * sizeof(uint),
                                                        Usage = ResourceUsage.Default
                                                    }
                                                 );

                    //add it to the mesh
                    modelMesh.IndexBuffer = indexBuffer;
                    modelMesh.IndexCount = indices.GetLength(0);
                }
            }

            //if node has more children process them as well
            for (int i = 0; i < node.ChildCount; i++)
            {
                AddVertexData(model, scene, node.Children[i], device, ref transform);
            }

            transform = previousTransform;
        }
示例#38
0
        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;
            };
        }
示例#39
0
        static void Main()
        {
            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //render form
            RenderForm form = new RenderForm();
            form.Text = "Tutorial 18: Skin Animation";
            SharpFPS fpsCounter = new SharpFPS();

            //number of cube
            int count = 1000;

            using (SharpDevice device = new SharpDevice(form))
            {
                SharpBatch font = new SharpBatch(device, "textfont.dds");

                //Input layout for Skinning Mesh
                InputElement[] description = new InputElement[]
                {
                    new InputElement("POSITION",0,SharpDX.DXGI.Format.R32G32B32_Float,0,0),
                    new InputElement("NORMAL",0,SharpDX.DXGI.Format.R32G32B32_Float,12,0),
                    new InputElement("TEXCOORD",0,SharpDX.DXGI.Format.R32G32_Float,24,0),
                    new InputElement("BINORMAL",0,SharpDX.DXGI.Format.R32G32B32_Float,32,0),
                    new InputElement("TANGENT",0,SharpDX.DXGI.Format.R32G32B32_Float,44,0),
                    new InputElement("JOINT",0,SharpDX.DXGI.Format.R32G32B32A32_Float,56,0),
                    new InputElement("WEIGHT",0,SharpDX.DXGI.Format.R32G32B32A32_Float,72,0),
                };

                SharpShader staticShader = new SharpShader(device, "../../Basic.hlsl",
                    new SharpShaderDescription()
                    {
                        VertexShaderFunction = "VSMain",
                        PixelShaderFunction = "PSMain"
                    }, description);

                SharpShader skinShader = new SharpShader(device, "../../BasicSkin.hlsl",
                    new SharpShaderDescription()
                    {
                        VertexShaderFunction = "VSMain",
                        PixelShaderFunction = "PSMain"
                    }, description);

                Buffer11 lightBuffer = skinShader.CreateBuffer<Vector4>();

                string path = @"../../../Models/Troll/";

                SharpModel model = new SharpModel(device,
                    ColladaImporter.Import(path + "troll.dae"));

                foreach (Geometry g in model.Geometries)
                {
                    if (g.IsAnimated)
                        g.Shader = skinShader;
                    else
                        g.Shader = staticShader;
                    g.Material.DiffuseTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.DiffuseTextureName);

                    g.Material.NormalTextureName = Path.GetFileNameWithoutExtension(g.Material.DiffuseTextureName) + "N.dds";

                    g.Material.NormalTexture = ShaderResourceView.FromFile(device.Device, path + g.Material.NormalTextureName);
                }

                fpsCounter.Reset();

                form.KeyDown += (sender, e) =>
                {
                    switch (e.KeyCode)
                    {
                        case Keys.Up:
                            if (count < 1000)
                                count++;
                            break;
                        case Keys.Down:
                            if (count > 0)
                                count--;
                            break;
                    }
                };

                int lastTick = Environment.TickCount;

                //main loop
                RenderLoop.Run(form, () =>
                {
                    //Resizing
                    if (device.MustResize)
                    {
                        device.Resize();
                        font.Resize();
                    }

                    //apply state
                    device.UpdateAllStates();

                    //clear color
                    device.Clear(Color.CornflowerBlue);

                    //set transformation matrix
                    float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 10000);
                    Matrix view = Matrix.LookAtLH(new Vector3(0, -100, 50), new Vector3(0, 0, 50), Vector3.UnitZ);
                    Matrix world = Matrix.Identity;

                    float angle = 0.2F;
                    Vector3 light = new Vector3((float)Math.Sin(angle), (float)Math.Cos(angle), 0);
                    light.Normalize();
                    device.UpdateData<Vector4>(lightBuffer, new Vector4(light, 1));
                    device.DeviceContext.VertexShader.SetConstantBuffer(2, lightBuffer);

                    float animationTime = (Environment.TickCount - lastTick) / 1000.0F;

                    if (animationTime >= model.Animations.First().Duration)
                    {
                        lastTick = Environment.TickCount;
                        animationTime = 0;
                    }

                    model.SetTime(animationTime);

                    model.Draw(device, new SkinShaderInformation()
                        {
                            Trasform = world * view * projection,
                            World = world
                        });

                    font.Begin();

                    //draw string
                    fpsCounter.Update();
                    font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White);
                    font.DrawString("Skinning Animation With Collada", 0, 30, Color.White);

                    //flush text to view
                    font.End();
                    //present
                    device.Present();

                });

                //release resource
                font.Dispose();
            }
        }