Пример #1
0
        public D3D10Renderer(Device1 device3D)
        {
            Contract.Requires(device3D != null);

            _Device3D = device3D;

            string shader = GetShaderText(Properties.Resources.RenderingEffects);

            using(var byteCode = ShaderBytecode.Compile(
                    shader, "fx_4_0", ShaderFlags.None, EffectFlags.None))
            {
                _Effect = new Effect(_Device3D, byteCode);
            }

            _EffectTechnique = _Effect.GetTechniqueByName("WithTexture");

            Contract.Assert(_EffectTechnique != null);

            _EffectPass = _EffectTechnique.GetPassByIndex(0);

            Contract.Assert(_EffectPass != null);

            _InputLayout = new InputLayout(
                _Device3D, _EffectPass.Description.Signature, _InputLayoutData);

            const int byteSize = _Stride * _VertexCount;

            using(DataStream stream = new DataStream(byteSize, true, true))
            {
                for(int i = 0; i < _QuadPrimitiveData.Length; i += 2)
                {
                    float fx = (2.0f * _QuadPrimitiveData[i + 0].X) - 1.0f;
                    float fy = (2.0f * _QuadPrimitiveData[i + 0].Y) - 1.0f;

                    stream.Write(new Vector3(fx, -fy, 0.5f));
                    stream.Write(_QuadPrimitiveData[i + 1]);
                }

                stream.Seek(0, SeekOrigin.Begin);

                BufferDescription description = new BufferDescription
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    Usage = ResourceUsage.Immutable,
                    SizeInBytes = byteSize
                };

                description.SizeInBytes = byteSize;

                _VertexBuffer = new Buffer(_Device3D, stream, description);

                _VertexBufferBinding = new VertexBufferBinding(
                    _VertexBuffer, _Stride, _Offset);
            }
        }
Пример #2
0
        public static Effect GetEffect(Game game, string name)
        {
            Effect effect;

            if (!effects.TryGetValue(name, out effect))
            {
                var effectByteCode = ShaderBytecode.CompileFromFile(string.Format("Contents/Effects/{0}.fx", name), "fx_4_0");
                effect = new Effect(game.Device, effectByteCode);
            }

            return effect;
        }
Пример #3
0
        public void Create(Device1 device)
        {
            //Create effect
            var shaderSource   = File.ReadAllText("Resources/Effects/PosColNorm3DSkinned.fx");
            var shaderByteCode = ShaderBytecode.Compile(shaderSource, "fx_4_0", ShaderFlags.None, EffectFlags.None);

            Effect    = new SharpDX.Direct3D10.Effect(device, shaderByteCode);
            Technique = Effect.GetTechniqueByIndex(0);

            //Create inputLayout
            var pass = Technique.GetPassByIndex(0);

            InputLayout = new InputLayout(device, pass.Description.Signature, InputLayouts.SkinnedVertex);
        }
        public void Initialize(Device1 device)
        {
            //Load Effect
            var shaderSource = File.ReadAllText("Resources\\PosColNorm3D.fx");
            var shaderByteCode = ShaderBytecode.Compile(shaderSource, "fx_4_0", ShaderFlags.None, EffectFlags.None);
            Effect = new Effect(device, shaderByteCode);
            Technique = Effect.GetTechniqueByIndex(0);

            //InputLayout
            var pass = Technique.GetPassByIndex(0);
            InputLayout = new InputLayout(device, pass.Description.Signature, InputLayouts.PosNormCol);

            _IsInitialized = true;
        }
Пример #5
0
        public void SetTexture(string path, Device1 device)
        {
            //Texture2D r = Resource.FromFile<Texture2D>(device, path);
            Texture2D fileTexture;

            fileTexture = Texture2D.FromFile <Texture2D>(device, path);



            ShaderResourceView srv = new ShaderResourceView1(device, fileTexture);

            //fileTexture.FilterTexture();

            Effect?.GetVariableByName("gDiffuseMap").AsShaderResource().SetResource(srv);
        }
Пример #6
0
        public void Create(Device1 device)
        {
            var filepath = System.AppDomain.CurrentDomain.BaseDirectory;

            filepath += "\\Resources\\Shaders\\PosNormTex3D.fx";
            var shaderBytecode = ShaderBytecode.CompileFromFile(filepath, "fx_4_0", shaderFlags: ShaderFlags.None);

            Effect = new Effect(device, shaderBytecode);

            Technique = Effect.GetTechniqueByIndex(0);

            var pass = Technique.GetPassByIndex(0);

            // InputLayout = new InputLayout(device, pass.Description.Signature, InputLayouts.PosNormTex);
            InputLayout = new InputLayout(device, pass.Description.Signature, InputLayouts.PosNormColTex);
        }
Пример #7
0
        void IScene.Attach(ISceneHost host)
        {
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
            this.SimpleEffect = new Effect(device, shaderBytes);

            EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); ;
            EffectPass pass = technique.GetPassByIndex(0);

            this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) 
            });

            this.VertexStream = new DataStream(3 * 32, true, true);
            this.VertexStream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            this.VertexStream.Position = 0;

            this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = 3 * 32,
                    Usage = ResourceUsage.Default
                }
            );

            device.Flush();
        }
Пример #8
0
 /// <summary>
 /// Inicializálja a szükséges effectet az EffectManager segítségével
 /// </summary>
 protected virtual void InitializeEffect()
 {
     // a BasicStaticVertexBufferEffect csak a forma világkoordinátáit kéri, ami statikus minden ojjektum esetében
     // a transzlációt és orientációt pedig az Effect paraméteriben frissítgetjük
     // az EffectManager arra kellett, hogy ne szemeteljük tele a memóriát azonos ShaderByteCode-okkal
     effect = EffectManager.GetEffect(this.Game, "BasicStaticVertexBufferEffect");
     vertexDeclareation = new InputLayout(Game.Device, effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, VertexPosition.InputElements);
 }
Пример #9
0
        public void Attach(ISceneHost host)
        {
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Particle.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.ParticleEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Shape.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.ShapeEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Line.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.LineEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            EffectTechnique technique = this.ParticleEffect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);

            this.ParticleLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new InputElement("POSITION", 1, Format.R32G32_Float, 8, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            this.ShapeLayout = new InputLayout(device, this.ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
            });

            this.LineLayout = new InputLayout(device, this.LineEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0)
            });

            ParticleProjection = ParticleEffect.GetVariableByName("Projection").AsVector();
            ParticleCamera = ParticleEffect.GetVariableByName("Camera").AsVector();

            ShapeCamera = ShapeEffect.GetVariableByName("Camera").AsVector();
            ShapeProjection = ShapeEffect.GetVariableByName("Projection").AsVector();
            ShapeColor = ShapeEffect.GetVariableByName("Color").AsVector();
            ShapePosition = ShapeEffect.GetVariableByName("Position").AsVector();

            ParticlePass = ParticleEffect.GetTechniqueByIndex(0).GetPassByIndex(0);
            ShapePass = ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0);

            DataStream lines = new DataStream(linesCount * 8, true, true);
            for (int i = 0; i < linesCount; i++)
                lines.Write(new Vector2(-1.0f + (float)i / (float)linesCount * 2.0f, 0));

            lines.Position = 0;

            Disposer.RemoveAndDispose(ref this.LineBuffer);

            this.LineBuffer = new Buffer(device, lines, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = linesCount * 8,
                Usage = ResourceUsage.Default
            });

            Disposer.RemoveAndDispose(ref lines);

            device.Flush();

            Initialized = true;
        }
Пример #10
0
		public void Attach(Device hostDevice, PointD2D hostSize)
		{
			if (hostDevice == null)
				throw new ArgumentNullException(nameof(hostDevice));

			_hostDevice = hostDevice;
			_hostSize = hostSize;

			Device device = _hostDevice;

			using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Altaxo.CompiledShaders.Effects.Lighting.cso"))
			{
				if (null == stream)
					throw new InvalidOperationException(string.Format("Compiled shader resource not found: {0}", "Altaxo.CompiledShaders.Effects.Lighting.cso"));

				using (var shaderBytes = ShaderBytecode.FromStream(stream))
				{
					_lightingEffect = new Effect(device, shaderBytes);
				}
			}

			int i;

			for (i = 0; i < _layoutNames.Length; ++i)
			{
				string techniqueName = "Shade_" + _layoutNames[i];
				_renderLayouts[i].technique = this._lightingEffect.GetTechniqueByName(techniqueName);
				_renderLayouts[i].pass = _renderLayouts[i].technique.GetPassByIndex(0);

				if (null == _renderLayouts[i].technique || !_renderLayouts[i].technique.IsValid)
					throw new InvalidProgramException(string.Format("Technique {0} was not found or is invalid", techniqueName));
				if (null == _renderLayouts[i].pass || !_renderLayouts[i].pass.IsValid)
					throw new InvalidProgramException(string.Format("Pass[0] of technique {0} was not found or is invalid", techniqueName));
			}

			i = 0;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
																								});

			i = 1;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
																								});

			i = 2;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
																								});

			i = 3;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0)
																								});

			i = 4;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
																																new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0)
																								});

			i = 5;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0)
																								});

			i = 6;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
																								});

			// Create Constant Buffers
			//_constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
			//_constantBufferForColor = new Buffer(device, Utilities.SizeOf<Vector4>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
			//_constantBufferForSixPlanes = new Buffer(device, Utilities.SizeOf<Vector4>() * 6, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

			// View transformation variables
			_cbViewTransformation = this._lightingEffect.GetConstantBufferByName("cbViewTransformation");
			_evWorldViewProj = _cbViewTransformation.GetMemberByName("WorldViewProj").AsMatrix();
			_evEyePosition = _cbViewTransformation.GetMemberByName("EyePosition").AsVector();

			_cbMaterial = this._lightingEffect.GetConstantBufferByName("cbMaterial");
			_evMaterialDiffuseColor = _cbMaterial.GetMemberByName("MaterialDiffuseColor").AsVector();
			_evMaterialSpecularExponent = _cbMaterial.GetMemberByName("MaterialSpecularExponent").AsScalar();
			_evMaterialSpecularExponent.Set(4.0f);
			_evMaterialSpecularIntensity = _cbMaterial.GetMemberByName("MaterialSpecularIntensity").AsScalar();
			_evMaterialSpecularIntensity.Set(1.0f);
			_evMaterialDiffuseIntensity = _cbMaterial.GetMemberByName("MaterialDiffuseIntensity").AsScalar();
			_evMaterialMetalnessValue = _cbMaterial.GetMemberByName("MaterialMetalnessValue").AsScalar();
			_evMaterialMetalnessValue.Set(0.75f);

			// Color providers
			BindTextureFor1DColorProviders();

			// Clip plane variables
			_cbClipPlanes = this._lightingEffect.GetConstantBufferByName("cbClipPlanes");
			for (i = 0; i < 6; ++i)
			{
				_evClipPlanes[i] = _cbClipPlanes.GetMemberByName("ClipPlane" + i.ToString(System.Globalization.CultureInfo.InvariantCulture)).AsVector();
			}

			// Lighting variables

			_lighting.Initialize(_lightingEffect);
			_lighting.SetDefaultLighting();

			// --------------------
			if (_drawing != null)
			{
				BringDrawingIntoBuffers(_drawing);
			}

			if (null != _markerGeometry)
			{
				BringMarkerGeometryIntoDeviceBuffers(_markerGeometry);
			}

			if (null != _overlayGeometry)
			{
				BringOverlayGeometryIntoDeviceBuffers(_overlayGeometry);
			}
		}
Пример #11
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample");

            Configuration.EnableObjectTracking = true;

            // SwapChain description
            var desc = new SwapChainDescription()
                           {
                               BufferCount = 1,
                               ModeDescription =
                                   new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                       new Rational(60, 1), Format.R8G8B8A8_UNorm),
                               IsWindowed = true,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1, 0),
                               SwapEffect = SwapEffect.Discard,
                               Usage = Usage.RenderTargetOutput
                           };

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, effectByteCode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;
            var layout = new InputLayout(device, passSignature, new[]
                                                                                 {
                                                                                     new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                                                                                     new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                                                                                 });

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
                                  });

            // Prepare All the stages
            device.InputAssembler.InputLayout = layout;
            device.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));
            device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.OutputMerger.SetTargets(renderView);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          device.ClearRenderTargetView(renderView, Color.Black);
                                          for (int i = 0; i < technique.Description.PassCount; ++i)
                                          {
                                              pass.Apply();
                                              device.Draw(3, 0);
                                          }
                                          swapChain.Present(0, PresentFlags.None);
                                      });

            // Release all resources
            passSignature.Dispose();
            effect.Dispose();
            effectByteCode.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.ClearState();
            device.Flush();
            device.Dispose();
            swapChain.Dispose();
            factory.Dispose();           
        }
Пример #12
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                _width = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;

                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width = 1024;
            _height = 768;
            _nearPlane = 1.0f;

            ambient = new Color4(Color.Gray.ToArgb());

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 10 device.");
                return;
            }

            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            shadowGenPass = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);
            debugDrawPass = technique.GetPassByName("debug");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            _device.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);

            // grender.fx

            shaderByteCode = LoadShader("grender.fx", shaderFlags);

            effect2 = new Effect(_device, shaderByteCode);
            technique = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass = technique.GetPassByIndex(0);
            gBufferOverlayPass = technique.GetPassByIndex(1);

            Buffer quad = DemoFramework.SharpDX.MeshFactory.CreateScreenQuad(_device);
            quadBinding = new VertexBufferBinding(quad, 20, 0);
            Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f);
            effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection);

            InputElement[] elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            };
            quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements);

            info = new InfoText(_device);
            _meshFactory = new MeshFactory(this);
            MeshFactory = _meshFactory;

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
Пример #13
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                _width = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width = 1024;
            _height = 768;
            _nearPlane = 1.0f;

            ambient = new Color4(Color.Gray.ToArgb());

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 10 device.");
                return;
            }

            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            shadowGenPass = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);
            debugDrawPass = technique.GetPassByName("debug");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            _device.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);

            // grender.fx

            shaderByteCode = LoadShader("grender.fx", shaderFlags);

            effect2 = new Effect(_device, shaderByteCode);
            technique = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass = technique.GetPassByIndex(0);
            gBufferOverlayPass = technique.GetPassByIndex(1);

            info = new InfoText(_device);
            _meshFactory = new MeshFactory(this);
            MeshFactory = _meshFactory;

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
Пример #14
0
 public void SetWorldViewProjection(Matrix wvp)
 {
     Effect?.GetVariableBySemantic("WORLDVIEWPROJECTION").AsMatrix().SetMatrix(wvp);
 }
Пример #15
0
        void Initialize()
        {
            // shader.fx

            ShaderFlags shaderFlags = ShaderFlags.None;
            //ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\shader.fx", "fx_4_0", shaderFlags, EffectFlags.None);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            shadowGenPass = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            _device.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);

            // grender.fx

            shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\grender.fx", "fx_4_0", shaderFlags, EffectFlags.None);

            effect2 = new Effect(_device, shaderByteCode);
            technique = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass = technique.GetPassByIndex(0);

            Buffer quad = MeshFactory.CreateScreenQuad(_device);
            quadBinding = new VertexBufferBinding(quad, 20, 0);
            Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f);
            effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection);

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            };
            quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements);

            Info = new InfoText(_device);
            meshFactory = new MeshFactory(this);

            OnInitialize();
            CreateBuffers();
            SetSceneConstants();
        }
Пример #16
0
 public void SetWorld(Matrix world)
 {
     Effect?.GetVariableBySemantic("WORLD").AsMatrix().SetMatrix(world);
 }
Пример #17
0
        void IScene.Attach(ISceneHost host)
        {
            
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            Uri executablePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            String shaderPath = System.IO.Path.GetDirectoryName(executablePath.LocalPath) + "\\Shaders\\";

            if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P)
            {
                shaderPath += "YUVtoRGB.fx";
            }
            else
            {
                shaderPath += "Simple.fx";
            }

            try
            {            
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile(shaderPath, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);             
                this.SimpleEffect = new Effect(device, shaderBytes);             
            }
            catch (Exception e)
            {              
                System.Diagnostics.Debug.Print(e.Message);
                throw new Exception("Error compiling: " + shaderPath);
            }

            EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); 
            EffectPass pass = technique.GetPassByIndex(0);

            this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),  
                new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
                //new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)  
               
            });

            int bytesPerVertexInfo = 4 * 8;          
            nrVertices = 4;

            this.VertexStream = new DataStream(bytesPerVertexInfo * nrVertices, true, true);
            this.VertexStream.WriteRange(new[] 
                {
                    new Vector4(-1.0f, 1.0f, 0.5f, 1.0f),
                    new Vector4(0.0f, 0.0f, 0.0f, 0.0f),

                    new Vector4(1.0f, -1.0f, 0.5f, 1.0f),
                    new Vector4(1.0f, 1.0f, 0.0f, 0.0f),

                    new Vector4(-1.0f, -1.0f, 0.5f, 1.0f),
                    new Vector4(0.0f, 1.0f, 0.0f, 0.0f),

                    new Vector4(1.0f, 1.0f, 0.5f, 1.0f),
                    new Vector4(1.0f, 0.0f, 0.0f, 0.0f)
                }
            );
            
            this.VertexStream.Position = 0;

            this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = bytesPerVertexInfo * nrVertices,
                    Usage = ResourceUsage.Default
                }
            );

            nrIndices = 4;
            int indicesSizeBytes = nrIndices * sizeof(Int32);

            IndexStream = new DataStream(indicesSizeBytes, true, true);
            IndexStream.WriteRange<int>(new[] 
                {
                    3,1,0,2
                }
            );

            this.IndexStream.Position = 0;

            this.Indices = new Buffer(device, this.IndexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.IndexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = indicesSizeBytes,
                    Usage = ResourceUsage.Default
                }
            );
  
            device.Flush();         
        }
Пример #18
0
			public void Initialize(Effect effect)
			{
				_singleLights = new SingleLight[4];

				_cbLighting = effect.GetConstantBufferByName("cbLights");
				HemisphericLightColorBelow = _cbLighting.GetMemberByName("HemisphericLightColorBelow").AsVector();
				HemisphericLightColorAbove = _cbLighting.GetMemberByName("HemisphericLightColorAbove").AsVector();
				HemisphericLightBelowToAboveVector = _cbLighting.GetMemberByName("HemisphericLightBelowToAboveVector").AsVector();

				LightPosX = _cbLighting.GetMemberByName("LightPosX").AsVector();
				LightPosY = _cbLighting.GetMemberByName("LightPosY").AsVector();
				LightPosZ = _cbLighting.GetMemberByName("LightPosZ").AsVector();

				LightDirX = _cbLighting.GetMemberByName("LightDirX").AsVector();
				LightDirY = _cbLighting.GetMemberByName("LightDirY").AsVector();
				LightDirZ = _cbLighting.GetMemberByName("LightDirZ").AsVector();

				LightColorR = _cbLighting.GetMemberByName("LightColorR").AsVector();
				LightColorG = _cbLighting.GetMemberByName("LightColorG").AsVector();
				LightColorB = _cbLighting.GetMemberByName("LightColorB").AsVector();

				LightRangeRcp = _cbLighting.GetMemberByName("LightRangeRcp").AsVector();
				CapsuleLen = _cbLighting.GetMemberByName("CapsuleLen").AsVector();
				SpotCosOuterCone = _cbLighting.GetMemberByName("SpotCosOuterCone").AsVector();
				SpotCosInnerConeRcp = _cbLighting.GetMemberByName("SpotCosInnerConeRcp").AsVector();
			}
Пример #19
0
        private void LoadRenderShader()
        {
            var shaderBytes = ShaderBytecode.Compile(Properties.Resources.FillShader, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
            fillEffect = new Effect(device, shaderBytes);

            EffectTechnique technique = fillEffect.GetTechniqueByIndex(0); ;
            fillPass = technique.GetPassByIndex(0);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.Compile(Properties.Resources.FillShader, "vs_main", "vs_4_0");
            vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.Compile(Properties.Resources.FillShader, "ps_main", "ps_4_0");
            pixelShader = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                    });

            // Instantiate Vertex buiffer from vertex data
            vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      new RenderVertex(){pos = new Vector4(1.0f, -1.0f, 0.0f, 1.0f), tex = new Vector2(1,1)},
                                      new RenderVertex(){pos = new Vector4(-1.0f, -1.0f, 0.0f, 1.0f), tex = new Vector2(0,1)},
                                      new RenderVertex(){pos = new Vector4(-1.0f, 1.0f, 0.0f, 1.0f), tex = new Vector2(0,0)},
                                      new RenderVertex(){pos = new Vector4(1.0f, 1.0f, 0.0f, 1.0f), tex = new Vector2(1,0)},
                                  });
            vertices_binding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vector2>() + Utilities.SizeOf<Vector4>(), 0);

            indices = Buffer.Create(device, BindFlags.IndexBuffer, new short[] { 0, 1, 2, 2, 3, 0 });

            // Create Constant Buffer
            //constants = new Buffer(device, Utilities.SizeOf<Vector2>() + Utilities.SizeOf<Vector4>(), ResourceUsage.Dynamic, BindFlags.ShaderResource, CpuAccessFlags.Write, ResourceOptionFlags.None);

            device.Rasterizer.SetViewports(new Viewport(0, 0, Width, Height, 0.0f, 1.0f));

            RasterizerStateDescription rsd = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
            };
            RasterizerState rsdState = new RasterizerState(device, rsd);
            device.Rasterizer.State = rsdState;

            options.halfPixel = new Vector2(0.5f / (float)Width,0.5f / (float)Height);
            options.color = new Vector4(1, 0, 1, 1);
        }