Exemplo n.º 1
0
        public ShapesDemo(IntPtr hInstance)
            : base(hInstance) {
            _vb = null;
            _ib = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _wireframeRS = null;
            _theta = 1.5f * MathF.PI;
            _phi = 0.1f * MathF.PI;
            _radius = 15.0f;

            MainWindowCaption = "Shapes Demo";

            _lastMousePos = new Point(0, 0);

            _gridWorld = Matrix.Identity;
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _boxWorld = Matrix.Scaling(2.0f, 1.0f, 2.0f) * Matrix.Translation(0, 0.5f, 0);
            _centerSphere = Matrix.Scaling(2.0f, 2.0f, 2.0f) * Matrix.Translation(0, 2, 0);

            for (int i = 0; i < 5; ++i) {
                _cylWorld[i * 2] = Matrix.Translation(-5.0f, 1.5f, -10.0f + i * 5.0f);
                _cylWorld[i * 2 + 1] = Matrix.Translation(5.0f, 1.5f, -10.0f + i * 5.0f);

                _sphereWorld[i * 2] = Matrix.Translation(-5.0f, 3.5f, -10.0f + i * 5.0f);
                _sphereWorld[i * 2 + 1] = Matrix.Translation(5.0f, 3.5f, -10.0f + i * 5.0f);
            }

        }
Exemplo n.º 2
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("RenderParticles");
				m_ParticlePass_Add = m_Technique.GetPassByName("Add");

				m_Layout = new InputLayout(GameEnvironment.Device, m_ParticlePass_Add.Description.Signature, new[] {
					new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
					new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0),				
					new InputElement("INST_POSITION", 0, Format.R32G32B32_Float, 0, 1, InputClassification.PerInstanceData, 1),
					new InputElement("INST_COLOR", 0, Format.R32G32B32A32_Float, 12, 1, InputClassification.PerInstanceData, 1), 					
				});

				m_WorldViewProj = m_Effect.GetVariableByName("worldViewProj").AsMatrix();
				m_ParticleTexture = m_Effect.GetVariableByName("particle_texture").AsResource();
				m_AmpScale = m_Effect.GetVariableByName("ampScale").AsScalar();
				m_PartScaleX = m_Effect.GetVariableByName("partScaleX").AsScalar();
				m_PartScaleY = m_Effect.GetVariableByName("partScaleY").AsScalar(); 
				m_MaxDistance = m_Effect.GetVariableByName("maxDistance").AsScalar();
				m_MinDistance = m_Effect.GetVariableByName("minDistance").AsScalar();
				m_ScaleDistance = m_Effect.GetVariableByName("scaleDistance").AsScalar();

				m_Disposed = false;
			}
		}
Exemplo n.º 3
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_TextFont.LoadResources();

				//SlimDX.D3DCompiler.ShaderBytecode blob = SlimDX.D3DCompiler.ShaderBytecode.CompileFromFile(Helper.ResolvePath(m_ShaderLocation), "fx_4_0", SlimDX.D3DCompiler.ShaderFlags.EnableStrictness, SlimDX.D3DCompiler.EffectFlags.None);

				m_Effect = new Effect(GameEnvironment.Device, Bytecode);

				m_Technique = m_Effect.GetTechniqueByName("LinesAndBoxes");
				m_Pass_BoxesAndText = m_Technique.GetPassByName("BoxesAndText");
				m_Pass_Lines = m_Technique.GetPassByName("Lines");
				
				m_Layout = new InputLayout(GameEnvironment.Device, m_Pass_Lines.Description.Signature, new[] {
					new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
					new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0),
					new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 20, 0),				
				});

				m_UiElementsTexture = m_Effect.GetVariableByName("UiElementsTexture").AsResource();
				m_UiElementsTexture.SetResource(m_TextFont.TexureView); 

				m_Disposed = false;
			}
		}
Exemplo n.º 4
0
        protected VisualEffect(IServiceProvider services, string effectAsset,
            int effectLayerCount, IEnumerable<RenderTargetLayerType> requiredRenderTargets)
        {
            if (services == null)
                throw new ArgumentNullException("services");
            if (effectAsset == null)
                throw new ArgumentNullException("effectAsset");
            if (requiredRenderTargets == null)
                throw new ArgumentNullException("requiredRenderTargets");
            if (effectLayerCount < 0)
                throw new ArgumentOutOfRangeException("affectedLayers", "Parameter should have non-negative value.");

            renderer = (Renderer)services.GetService(typeof(Renderer));
            resourceManager = (ResourceManager)services.GetService(typeof(ResourceManager));

            this.requiredRenderTargets = requiredRenderTargets;
            this.effectLayerCount = effectLayerCount > 0 ? effectLayerCount : renderer.KBufferManager.Configuration.LayerCount;

            effect = resourceManager.Load<Effect>(effectAsset);
            effectTechnique = effect.GetTechniqueByName(VisualEffectTechniqueName);
            if (!effectTechnique.IsValid)
                throw new ArgumentException(
                    string.Format("Given effect asset '{0}' does not contain technique {1}.", effectAsset, VisualEffectTechniqueName),
                    "effectAsset");
        }
Exemplo n.º 5
0
        public FowardLightingEffect(Device device, string filename)
            : base(device, filename) {

            Ambient = FX.GetTechniqueByName("Ambient");
            DepthPrePass = FX.GetTechniqueByName("DepthPrePass");
            Directional = FX.GetTechniqueByName("Directional");
            PointLight = FX.GetTechniqueByName("Point");

            _worldViewProj = FX.GetVariableByName("WorldViewProjection").AsMatrix();
            _world = FX.GetVariableByName("World").AsMatrix();
            _worldInvTranspose = FX.GetVariableByName("gWorldInvTranspose").AsMatrix();

            _ambientDown = FX.GetVariableByName("AmbientDown").AsVector();
            _ambientRange = FX.GetVariableByName("AmbientRange").AsVector();

            _dirToLight = FX.GetVariableByName("DirToLight").AsVector();
            _dirLightColor = FX.GetVariableByName("DirLightColor").AsVector();

            _eyePosition = FX.GetVariableByName("EyePosition").AsVector();
            _specularExponent = FX.GetVariableByName("specExp").AsScalar();
            _specularIntensity = FX.GetVariableByName("specIntensity").AsScalar();

            _pointLightPosition = FX.GetVariableByName("PointLightPosition").AsVector();
            _pointLightRangeRcp = FX.GetVariableByName("PointLightRangeRcp").AsScalar();
            _pointLightColor = FX.GetVariableByName("PointLightColor").AsVector();

            _diffuseMap = FX.GetVariableByName("DiffuseTexture").AsResource();
        }
        public override void Attach(IRenderHost host)
        {
            /// --- attach
            this.renderTechnique = Techniques.RenderCubeMap;
            base.Attach(host);

            /// --- get variables               
            this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique);
            this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name);
            this.effectTransforms = new EffectTransformVariables(this.effect);

            /// -- attach cube map 
            if (this.Filename != null)
            {
                /// -- attach texture
                using (var texture = Texture2D.FromFile<Texture2D>(this.Device, this.Filename))
                {
                    this.texCubeMapView = new ShaderResourceView(this.Device, texture);
                }
                this.texCubeMap = effect.GetVariableByName("texCubeMap").AsShaderResource();
                this.texCubeMap.SetResource(this.texCubeMapView);
                this.bHasCubeMap = effect.GetVariableByName("bHasCubeMap").AsScalar();
                this.bHasCubeMap.Set(true);

                /// --- set up geometry
                var sphere = new MeshBuilder(false,true,false);
                sphere.AddSphere(new Vector3(0, 0, 0));
                this.geometry = sphere.ToMeshGeometry3D();

                /// --- set up vertex buffer
                this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, CubeVertex.SizeInBytes, this.geometry.Positions.Select((x, ii) => new CubeVertex() { Position = new Vector4(x, 1f) }).ToArray());

                /// --- set up index buffer
                this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array);

                /// --- set up rasterizer states
                var rasterStateDesc = new RasterizerStateDescription()
                {
                    FillMode = FillMode.Solid,
                    CullMode = CullMode.Back,
                    IsMultisampleEnabled = true,
                    IsAntialiasedLineEnabled = true,
                    IsFrontCounterClockwise = false,
                };
                this.rasterState = new RasterizerState(this.Device, rasterStateDesc);

                /// --- set up depth stencil state
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All,
                    IsDepthEnabled = true,
                };
                this.depthStencilState = new DepthStencilState(this.Device, depthStencilDesc);
            }

            /// --- flush
            this.Device.ImmediateContext.Flush();
        }
Exemplo n.º 7
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);
            }
        }
Exemplo n.º 8
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("Imposter");

				m_Pass_NoBlend = m_Technique.GetPassByName("NoBlend");
				m_Pass_OverlayAdd = m_Technique.GetPassByName("OverlayAdd");
				m_Pass_OverlaySubtract = m_Technique.GetPassByName("OverlaySubtract");
				m_Pass_OverlayInvert = m_Technique.GetPassByName("OverlayInvert");
				m_Pass_OverlayAlpha = m_Technique.GetPassByName("OverlayAlpha");

				m_Technique_BrightPass = m_Effect.GetTechniqueByName("Imposter_BrightPass");

				m_Pass_NoBlend_BrightPass = m_Technique_BrightPass.GetPassByName("NoBlend");
				m_Pass_OverlayAdd_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAdd");
				m_Pass_OverlaySubtract_BrightPass = m_Technique_BrightPass.GetPassByName("OverlaySubtract");
				m_Pass_OverlayAlpha_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAlpha");

				m_ImposterTextureResource = m_Effect.GetVariableByName("imposter").AsResource();

				m_BrightPassThreshold = m_Effect.GetVariableByName("brightPassThreshold").AsScalar();

				m_Layout = new InputLayout(GameEnvironment.Device, m_Pass_NoBlend.Description.Signature, new[] {
					new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
					new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0)		
				});

				float minX = -1f, miny = -1f, maxX = 1f, maxY = 1f;

				using (DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(Vertex2D)), true, true))
				{
					stream.WriteRange(new Vertex2D[] {					
						new Vertex2D() { Position = new Vector2(maxX, miny), TextureCoords =  new Vector2(1.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(minX, miny), TextureCoords =  new Vector2(0.0f, 1.0f) }, 
						new Vertex2D() { Position = new Vector2(maxX, maxY), TextureCoords = new Vector2(1.0f, 0.0f) },  
						new Vertex2D() { Position = new Vector2(minX, maxY), TextureCoords =  new Vector2(0.0f, 0.0f) } 
					});
					stream.Position = 0;

					m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
						Usage = ResourceUsage.Default
					});
				}

				m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0);

				m_Disposed = false;
			}
		}
Exemplo n.º 9
0
        public SsaoNormalDepthEffect(Device device, string filename) : base(device, filename) {
            NormalDepthTech = FX.GetTechniqueByName("NormalDepth");
            NormalDepthAlphaClipTech = FX.GetTechniqueByName("NormalDepthAlphaClip");

            _worldView = FX.GetVariableByName("gWorldView").AsMatrix();
            _worldInvTransposeView = FX.GetVariableByName("gWorldInvTransposeView").AsMatrix();
            _worldViewProj = FX.GetVariableByName("gWorldViewProj").AsMatrix();
            _texTransform = FX.GetVariableByName("gTexTransform").AsMatrix();
            _diffuseMap = FX.GetVariableByName("gDiffuseMap").AsResource();
        }
Exemplo n.º 10
0
        public DebugTexEffect(Device device, string filename) : base(device, filename) {
            ViewArgbTech = FX.GetTechniqueByName("ViewArgbTech");
            ViewRedTech = FX.GetTechniqueByName("ViewRedTech");
            ViewGreenTech = FX.GetTechniqueByName("ViewGreenTech");
            ViewBlueTech = FX.GetTechniqueByName("ViewBlueTech");
            ViewAlphaTech = FX.GetTechniqueByName("ViewAlphaTech");

            _texture = FX.GetVariableByName("gTexture").AsResource();
            _wvp = FX.GetVariableByName("gWorldViewProj").AsMatrix();
        }
Exemplo n.º 11
0
        public SsaoBlurEffect(Device device, string filename) : base(device, filename) {
            HorzBlurTech = FX.GetTechniqueByName("HorzBlur");
            VertBlurTech = FX.GetTechniqueByName("VertBlur");

            _texelWidth = FX.GetVariableByName("gTexelWidth").AsScalar();
            _texelHeight = FX.GetVariableByName("gTexelHeight").AsScalar();

            _normalDepthMap = FX.GetVariableByName("gNormalDepthMap").AsResource();
            _inputImage = FX.GetVariableByName("gInputImage").AsResource();
        }
Exemplo n.º 12
0
        public InstancedNormalMapEffect(Device device, string filename) : base(device, filename) {
            Light1Tech = FX.GetTechniqueByName("Light1");
            Light3TexTech = FX.GetTechniqueByName("Light3Tex");

            _viewProj = FX.GetVariableByName("gViewProj").AsMatrix();
            _texTransform = FX.GetVariableByName("gTexTransform").AsMatrix();
            _eyePosW = FX.GetVariableByName("gEyePosW").AsVector();

            _dirLights = FX.GetVariableByName("gDirLights");
            _mat = FX.GetVariableByName("gMaterial");
            _diffuseMap = FX.GetVariableByName("gDiffuseMap").AsResource();
            _normalMap = FX.GetVariableByName("gNormalMap").AsResource();
        }
Exemplo n.º 13
0
        } // GetParameters

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                pointLightStencilTechnique     = Resource.Techniques["PointLightStencil"];
                pointLightTechnique            = Resource.Techniques["PointLight"];
                pointLightWithShadowsTechnique = Resource.Techniques["PointLightWithShadows"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
Exemplo n.º 14
0
        protected Blender(IServiceProvider services, string effectAsset)
        {
            if (services == null)
                throw new ArgumentNullException("services");
            if (effectAsset == null)
                throw new ArgumentNullException("effectAsset");

            resourceManager = (ResourceManager) services.GetService(typeof (ResourceManager));
            renderer = (Renderer) services.GetService(typeof (Renderer));

            effect = resourceManager.Load<Effect>(effectAsset);
            effectTechnique = effect.GetTechniqueByName(BlenderTechniqueName);
        }
Exemplo n.º 15
0
        }         // GetParametersHandles

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                blinnPhongSkinnedTechnique       = Resource.Techniques["BlinnPhongSkinned"];
                blinnPhongSimpleTechnique        = Resource.Techniques["BlinnPhongSimple"];
                blinnPhongWithParrallaxTechnique = Resource.Techniques["BlinnPhongWithParrallax"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
Exemplo n.º 16
0
        /// <inheritdoc/>
        public override EffectTechniqueDescription GetDescription(Effect effect, EffectTechnique technique)
        {
            if (effect is AlphaTestEffect ||
                effect is BasicEffect ||
                effect is DualTextureEffect ||
                effect is EnvironmentMapEffect ||
                effect is SkinnedEffect)
            {
                return(new EffectTechniqueDescription(effect, technique));
            }

            return(null);
        }
Exemplo n.º 17
0
        public ForwardLightingEffect(Device device, string filename)
            : base(device, filename) {

            Ambient = FX.GetTechniqueByName("Ambient");

            _worldViewProj = FX.GetVariableByName("WorldViewProjection").AsMatrix();
            _world = FX.GetVariableByName("World").AsMatrix();
            _worldInvTranspose = FX.GetVariableByName("gWorldInvTranspose").AsMatrix();

            _ambientDown = FX.GetVariableByName("AmbientDown").AsVector();
            _ambientRange = FX.GetVariableByName("AmbientRange").AsVector();

            _diffuseMap = FX.GetVariableByName("DiffuseTexture").AsResource();
        }
Exemplo n.º 18
0
 public override void Draw(EffectTechnique technique)
 {
     if (Height > 0)
     {
         RendererAssetPool.UniversalEffect.CurrentTechnique =
             RendererAssetPool.UniversalEffect.Techniques.TexturedWrap;
     }
     else
     {
         RendererAssetPool.UniversalEffect.CurrentTechnique =
             RendererAssetPool.UniversalEffect.Techniques.TexturedClamp;
     }
     base.Draw(technique);
 }
Exemplo n.º 19
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("BlurBilinear");

				m_Pass_Gaussian = m_Technique.GetPassByName("Gaussian");

				m_SourceTex = m_Effect.GetVariableByName("g_SourceTex").AsResource();
				m_GWeights = m_Effect.GetVariableByName("g_GWeights").AsScalar();

				//m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES;
				m_DataStride = Marshal.SizeOf(typeof(Vector2)) * (1 + GAUSSIAN_MAX_SAMPLES);

				InputElement[] IADesc = new InputElement[1 + (GAUSSIAN_MAX_SAMPLES / 2)];

				IADesc[0] = new InputElement()
				{
					SemanticName = "POSITION",
					SemanticIndex = 0,
					AlignedByteOffset = 0,
					Slot = 0,
					Classification = InputClassification.PerVertexData,
					Format = Format.R32G32_Float
				};


				for (int i = 1; i < 1 + (GAUSSIAN_MAX_SAMPLES / 2); i++)
				{
					IADesc[i] = new InputElement()
					{
						SemanticName = "TEXCOORD",
						SemanticIndex = i - 1,
						AlignedByteOffset = 8 + (i - 1) * 16,
						Slot = 0,
						Classification = InputClassification.PerVertexData,
						Format = Format.R32G32B32A32_Float
					};
				}

				// Real number of "sematinc based" elements
				//m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES / 2;

				EffectPassDescription PassDesc = m_Pass_Gaussian.Description;
				m_Layout = new InputLayout(GameEnvironment.Device, PassDesc.Signature, IADesc);

				m_Disposed = false;
			}
		}
Exemplo n.º 20
0
        /// <summary>
        /// Called when the shader parameters are to be configured before rendering.
        /// </summary>
        /// <param name="renderSystem">Instance of the <see cref="DeferredRenderSystem"/> we are using to render</param>
        /// <param name="technique">Technique to use (can be null)</param>
        protected override void ConfigureShader(DeferredRenderSystem renderSystem, EffectTechnique technique)
        {
            if (!technique.Name.Equals("ApplyFlagsToOptionsMap"))
            {
                throw new ArgumentException("You dun goofed.");
            }

            base.ConfigureShader(renderSystem, technique);

            this.ShaderAsset.Parameters["viewProjection"].SetValue(renderSystem.GameCamera.GetViewProjectionMatrix(renderSystem));
            this.ShaderAsset.Parameters["cameraPosition"].SetValue(renderSystem.GameCamera.PixelPosition);
            this.ShaderAsset.Parameters["pixelOptions"].SetValue((float)SpriteRenderOptions.None);
            this.ShaderAsset.Parameters["specularReflectivity"].SetValue(0.5f);
        }
Exemplo n.º 21
0
        public EffectDescription(string filename)
        {
            this.filename = filename;
            instanceParameters = new SortedList<string, InstanceParameter>();
            staticParameters = new SortedList<string, SharedParameter>();
            dynamicParameters = new SortedList<string, SharedParameter>();

            effect = EffectManager.LoadEffect(Global.FXPath + filename);

            if (effect == null)
                Application.Exit();
            else
                technique = effect.GetTechniqueByIndex(0);
        }
Exemplo n.º 22
0
        } // GetParameters

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                ambientLightSphericalHarmonicsTechnique = Resource.Techniques["AmbientLightSphericalHarmonics"];
                ambientLightSphericalHarmonicsAmbientOcclusionTechnique = Resource.Techniques["AmbientLightSphericalHarmonicsAmbientOcclusion"];
                ambientLightTechnique = Resource.Techniques["AmbientLight"];
                ambientLightAmbientOcclusionTechnique = Resource.Techniques["AmbientLightAmbientOcclusion"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
Exemplo n.º 23
0
        /// <summary>
        /// This Init function also doubles as an update function
        /// in case the position or size of the billboard changes.
        /// </summary>
        public void InitDeviceResources(GraphicsDevice device)
        {
            // Init the vertex buffer.
            if (vbuf == null)
            {
                vbuf = new VertexBuffer(device, typeof(Vertex), 4, BufferUsage.WriteOnly);

                // Create local vertices.
                Vertex[] localVerts = new Vertex[4];
                {
                    localVerts[0] = new Vertex(new Vector3(-size.X / 2.0f, size.Y / 2.0f, 0.0f), new Vector2(0, 0));
                    localVerts[1] = new Vertex(new Vector3(size.X / 2.0f, size.Y / 2.0f, 0.0f), new Vector2(1, 0));
                    localVerts[2] = new Vertex(new Vector3(size.X / 2.0f, -size.Y / 2.0f, 0.0f), new Vector2(1, 1));
                    localVerts[3] = new Vertex(new Vector3(-size.X / 2.0f, -size.Y / 2.0f, 0.0f), new Vector2(0, 1));
                }

                // Copy to vertex buffer.
                vbuf.SetData <Vertex>(localVerts);
            }

            // Init the effect.
            if (effect == null)
            {
                effect = BokuGame.Load <Effect>(BokuGame.Settings.MediaPath + @"Shaders\Billboard");
                ShaderGlobals.RegisterEffect("Billboard", effect);
                effectCache.Load(effect);
                technique = premultipliedAlpha
                    ? effect.Techniques["PremultipliedAlphaColorPass"]
                    : effect.Techniques["NormalAlphaColorPass"];
            }

            // Load the texture.
            if (textureFilename != null)
            {
                // First try and load it as a programming tile.
                texture = CardSpace.Cards.CardFaceTexture(textureFilename);

                // If that didn't work, treat it as an asset name.
                if (texture == null)
                {
                    texture = BokuGame.Load <Texture2D>(BokuGame.Settings.MediaPath + textureFilename);
                }
            }
            if (texture != null && size == Vector2.Zero)
            {
                UiCamera c = new UiCamera();
                size.X = texture.Width / c.Dpi;  // 96 DPI
                size.Y = texture.Height / c.Dpi;
            }
        }   // end of InitDeviceResources()
Exemplo n.º 24
0
 private void TryCloneEffect(Effect sharedEffect)
 {
     this.effect = sharedEffect.Clone();
     using (IEnumerator <EffectTechnique> enumerator = this.effect.Techniques.GetEnumerator())
     {
         if (!enumerator.MoveNext())
         {
             return;
         }
         EffectTechnique current = enumerator.Current;
         this.currentTechnique = current;
         this.currentPass      = current.Passes[0];
     }
 }
Exemplo n.º 25
0
        public TreeSpriteEffect(Device device, string filename) : base(device, filename) {
            Light3Tech = FX.GetTechniqueByName("Light3");
            Light3TexAlphaClipTech = FX.GetTechniqueByName("Light3TexAlphaClip");
            Light3TexAlphaClipFogTech = FX.GetTechniqueByName("Light3TexAlphaClipFog");

            _viewProj = FX.GetVariableByName("gViewProj").AsMatrix();
            _eyePosW = FX.GetVariableByName("gEyePosW").AsVector();
            _fogColor = FX.GetVariableByName("gFogColor").AsVector();
            _fogStart = FX.GetVariableByName("gFogStart").AsScalar();
            _fogRange = FX.GetVariableByName("gFogRange").AsScalar();
            _dirLights = FX.GetVariableByName("gDirLights");
            _mat = FX.GetVariableByName("gMaterial");
            _treeTextureMapArray = FX.GetVariableByName("gTreeMapArray").AsResource();
        }
        } // GetParameters

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                generateLightDepthBufferSkinnedTechnique     = Resource.Techniques["GenerateLightDepthBufferSkinned"];
                generateLightDepthBufferTechnique            = Resource.Techniques["GenerateLightDepthBuffer"];
                generateCubeLightDepthBufferSkinnedTechnique = Resource.Techniques["GenerateCubeLightDepthBufferSkinned"];
                generateCubeLightDepthBufferTechnique        = Resource.Techniques["GenerateCubeLightDepthBuffer"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
        public InstancedNormalMapEffect(Device device, string filename) : base(device, filename)
        {
            Light1Tech    = FX.GetTechniqueByName("Light1");
            Light3TexTech = FX.GetTechniqueByName("Light3Tex");

            _viewProj     = FX.GetVariableByName("gViewProj").AsMatrix();
            _texTransform = FX.GetVariableByName("gTexTransform").AsMatrix();
            _eyePosW      = FX.GetVariableByName("gEyePosW").AsVector();

            _dirLights  = FX.GetVariableByName("gDirLights");
            _mat        = FX.GetVariableByName("gMaterial");
            _diffuseMap = FX.GetVariableByName("gDiffuseMap").AsResource();
            _normalMap  = FX.GetVariableByName("gNormalMap").AsResource();
        }
Exemplo n.º 28
0
        public SsaoEffect(Device device, string filename) : base(device, filename) {
            SsaoTech = FX.GetTechniqueByName("Ssao");

            _viewToTexSpace = FX.GetVariableByName("gViewToTexSpace").AsMatrix();
            _offsetVectors = FX.GetVariableByName("gOffsetVectors").AsVector();
            _frustumCorners = FX.GetVariableByName("gFrustumCorners").AsVector();
            _occlusionRadius = FX.GetVariableByName("gOcclusionRadius").AsScalar();
            _occlusionFadeStart = FX.GetVariableByName("gOcclusionFadeStart").AsScalar();
            _occlusionFadeEnd = FX.GetVariableByName("gOcclusionFadeEnd").AsScalar();
            _surfaceEpsilon = FX.GetVariableByName("gSurfaceEpsilon").AsScalar();

            _normalDepthMap = FX.GetVariableByName("gNormalDepthMap").AsResource();
            _randomVecMap = FX.GetVariableByName("gRandomVecMap").AsResource();
        }
Exemplo n.º 29
0
        public ForwardLightingEffect(Device device, string filename)
            : base(device, filename)
        {
            Ambient = FX.GetTechniqueByName("Ambient");

            _worldViewProj     = FX.GetVariableByName("WorldViewProjection").AsMatrix();
            _world             = FX.GetVariableByName("World").AsMatrix();
            _worldInvTranspose = FX.GetVariableByName("gWorldInvTranspose").AsMatrix();

            _ambientDown  = FX.GetVariableByName("AmbientDown").AsVector();
            _ambientRange = FX.GetVariableByName("AmbientRange").AsVector();

            _diffuseMap = FX.GetVariableByName("DiffuseTexture").AsResource();
        }
Exemplo n.º 30
0
        public void Draw(ref EffectTechnique technique)
        {
            for (int p = 0; p < technique.Description.PassCount; p++)
            {
                Renderer.SetInputLayout("Textured");
                Renderer.context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                Renderer.context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, VertexTex.Stride, 0));
                Renderer.context.InputAssembler.SetIndexBuffer(IndexBuffer, Format.R32_UInt, 0);
                Renderer.SetTexture(texture);

                technique.GetPassByIndex(p).Apply(Renderer.context);
                Renderer.context.DrawIndexed(36, 0, 0);
            }
        }
Exemplo n.º 31
0
        public static void RenderMesh2(Model m, Vector3 position, string effectName, string technique, Matrix mWorld, int stride)
        {
            if (m == null || m.MeshObj == null)
            {
                return;
            }
            Shader e     = WorldData.GetObject(effectName) as Shader;
            Matrix world = Matrix.Identity + Matrix.Translation(position);

            if (mWorld != null)
            {
                world = mWorld;
            }
            ShaderHelper.UpdateCommonEffectVars(e, world);

            EffectTechnique t = e.EffectObj.GetTechniqueByName(technique);

            D3D10.Buffer indexBuffer   = m.MeshObj.GetDeviceIndexBuffer();
            D3D10.Buffer vertextBuffer = m.MeshObj.GetDeviceVertexBuffer(0);

            Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);
            Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertextBuffer, stride, 0));

            for (int p = 0; p < t.Description.PassCount; p++)
            {
                EffectPass  pass = t.GetPassByIndex(p);
                InputLayout l    = ShaderHelper.ConstructInputLayout(m.Mesh3d.inputElements, pass.Description.Signature);
                Game.Device.InputAssembler.SetInputLayout(l);

                for (int subset = 0; subset < m.Mesh3d.NumAttributes; subset++)
                {
                    EffectResourceVariable diffTex = e.GetVar(ShaderHelper.DiffTex).AsResource();
                    if (diffTex != null)
                    {
                        diffTex.SetResource(m.Mesh3d.textureViews[subset]);
                    }
                    pass.Apply();
                    MeshAttributeRange r = m.Mesh3d.attrTable[subset];
                    // * 2 cause adj data is twice as much data
                    //Game.Device.DrawIndexed((r.FaceCount * 3) * 2, (r.FaceStart * 3) * 2, 0);

                    Game.Device.DrawIndexed((r.FaceCount * 3), (r.FaceStart * 3), 0);
                }
            }

            indexBuffer.Dispose();
            vertextBuffer.Dispose();
        }
Exemplo n.º 32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        public override void Attach(IRenderHost host)
        {
            renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Points];
            base.Attach(host);

            if (this.Geometry == null ||
                this.Geometry.Positions == null || this.Geometry.Positions.Count == 0)
            {
                return;
            }

            if (renderHost.RenderTechnique == renderHost.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.Deferred) ||
                renderHost.RenderTechnique == renderHost.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.GBuffer))
            {
                return;
            }

            // --- get device
            vertexLayout    = renderHost.EffectsManager.GetLayout(renderTechnique);
            effectTechnique = effect.GetTechniqueByName(renderTechnique.Name);

            effectTransforms = new EffectTransformVariables(effect);

            // --- get geometry
            var geometry = Geometry as PointGeometry3D;

            // -- set geometry if given
            if (geometry != null)
            {
                /// --- set up buffers
                vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, VertexSizeInBytes, CreateVertexArray());
            }

            /// --- set up const variables
            vViewport = effect.GetVariableByName("vViewport").AsVector();
            //this.vFrustum = effect.GetVariableByName("vFrustum").AsVector();
            vPointParams = effect.GetVariableByName("vPointParams").AsVector();

            /// --- set effect per object const vars
            var pointParams = new Vector4((float)Size.Width, (float)Size.Height, (float)Figure, (float)FigureRatio);

            vPointParams.Set(pointParams);

            /// --- create raster state
            OnRasterStateChanged();

            /// --- flush
            Device.ImmediateContext.Flush();
        }
Exemplo n.º 33
0
        private static void DrawClouds(bool renderReflection)
        {
            if (skyBoxCloudsMesh == null || skyBoxCloudsMesh.MeshObj == null)
            {
                return;
            }
            Shader          scatterEffect = WorldData.GetObject("scatter.fx") as Shader;
            EffectTechnique tech          = scatterEffect.EffectObj.GetTechniqueByName("RenderClouds");

            if (renderReflection)
            {
                tech = scatterEffect.EffectObj.GetTechniqueByName("RenderCloudsReflection");
            }

            D3D10.Buffer iBuffer = skyBoxCloudsMesh.MeshObj.GetDeviceIndexBuffer();
            D3D10.Buffer vBuffer = skyBoxCloudsMesh.MeshObj.GetDeviceVertexBuffer(0);

            Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            Game.Device.InputAssembler.SetIndexBuffer(iBuffer, Format.R16_UInt, 0);
            Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vBuffer, 56, 0));
            EffectPass  p1     = tech.GetPassByIndex(0);
            InputLayout layout = ShaderHelper.ConstructInputLayout(MeshInputElements10.NormalMesh, p1.Description.Signature);

            Game.Device.InputAssembler.SetInputLayout(layout);

            Matrix mWorld = Matrix.Translation(Camera.Position);

            if (renderReflection)
            {
                mWorld = Matrix.Scaling(1, -1, 1) * Matrix.Translation(Camera.Position);
            }
            scatterEffect.GetVar("WorldViewProj").AsMatrix().SetMatrix(mWorld * Camera.ViewMatrix * Camera.ProjectionMatrix);
            if (settings != null && settings.SkySettings != null)
            {
                scatterEffect.GetVar("cloud1Tile").AsScalar().Set(settings.SkySettings.CloudTile.X);
                scatterEffect.GetVar("cloud2Tile").AsScalar().Set(settings.SkySettings.CloudTile.Y);
                scatterEffect.GetVar("cloudCover").AsScalar().Set(settings.SkySettings.CloudCover);
            }
            scatterEffect.GetVar("scroll").AsVector().Set(t);
            scatterEffect.GetVar("clouds1Tex").AsResource().SetResource(skyClouds1);
            scatterEffect.GetVar("clouds2Tex").AsResource().SetResource(skyClouds2);
            scatterEffect.GetVar("SunColor").AsVector().Set(SunColor);

            p1.Apply();
            Game.Device.DrawIndexed((skyBoxCloudsMesh.Mesh3d.attrTable[0].FaceCount * 3), 0, 0);

            iBuffer.Dispose();
            vBuffer.Dispose();
        }
Exemplo n.º 34
0
        public void Render(Device device, ShaderResourceView textureView)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (device == null)
            {
                return;
            }

            if (!object.ReferenceEquals(device, _cachedDevice))
            {
                throw new InvalidOperationException(string.Format("Argument {0} and member {1} do not match!", nameof(device), nameof(_cachedDevice)));
            }

            device.InputAssembler.InputLayout       = _vertexLayout;
            device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertices, 24, 0));


            EffectTechnique technique                   = null;
            EffectPass      pass                        = null;
            EffectVariable  shaderResourceObj           = null;
            EffectShaderResourceVariable shaderResource = null;

            try
            {
                technique         = _effect.GetTechniqueByIndex(0);
                pass              = technique.GetPassByIndex(0);
                shaderResourceObj = _effect.GetVariableByName("ShaderTexture");
                shaderResource    = shaderResourceObj.AsShaderResource();
                shaderResource.SetResource(textureView);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply();
                    device.Draw(6, 0);
                }
            }
            finally
            {
                Disposer.RemoveAndDispose(ref shaderResource);
                Disposer.RemoveAndDispose(ref shaderResourceObj);
                Disposer.RemoveAndDispose(ref pass);
                Disposer.RemoveAndDispose(ref technique);
            }
        }
Exemplo n.º 35
0
        private void LoadShader(string p_filepath, string p_VS_name, string p_PS_name, InputElement[] p_elements)
        {
            var vshader = ShaderBytecode.CompileFromFile(p_filepath, p_VS_name, "vs_4_0", ShaderFlags.None,
                                                         EffectFlags.None);
            var pshader = ShaderBytecode.CompileFromFile(p_filepath, p_PS_name, "fx_5_0", ShaderFlags.None,
                                                         EffectFlags.None);
            var sig = ShaderSignature.GetInputSignature(vshader);

            ShaderEffect = new Effect(GraphicsRenderer.Device, pshader);
            EffectTechnique technique = ShaderEffect.GetTechniqueByIndex(0);

            ShaderPass = technique.GetPassByIndex(0);

            Layout = new InputLayout(GraphicsRenderer.Device, sig, p_elements);
        }
Exemplo n.º 36
0
        } // GetParameters

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                renderShadowMap2x2PCFTechnique    = Resource.Techniques["RenderShadowMap2x2PCF"];
                renderShadowMap3x3PCFTechnique    = Resource.Techniques["RenderShadowMap3x3PCF"];
                renderShadowMap5x5PCFTechnique    = Resource.Techniques["RenderShadowMap5x5PCF"];
                renderShadowMap7x7PCFTechnique    = Resource.Techniques["RenderShadowMap7x7PCF"];
                renderShadowMapPoisonPCFTechnique = Resource.Techniques["RenderShadowMapPoisonPCF"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
Exemplo n.º 37
0
        } // GetParameters

        #endregion

        #region Get Techniques Handles

        /// <summary>
        /// Get the handles of the techniques from the shader.
        /// </summary>
        /// <remarks>
        /// Creating and assigning a EffectParameter instance for each technique in your Effect is significantly faster than using the Parameters indexed property on Effect.
        /// </remarks>
        protected override void GetTechniquesHandles()
        {
            try
            {
                gBufferSimpleTechnique      = Resource.Techniques["GBufferSimple"];
                gBufferWithNormalMap        = Resource.Techniques["GBufferWithNormalMap"];
                gBufferWithParallax         = Resource.Techniques["GBufferWithParallax"];
                gBufferSkinnedSimple        = Resource.Techniques["GBufferSkinnedSimple"];
                gBufferSkinnedWithNormalMap = Resource.Techniques["GBufferSkinnedWithNormalMap"];
            }
            catch
            {
                throw new InvalidOperationException("The technique's handles from the " + Name + " shader could not be retrieved.");
            }
        } // GetTechniquesHandles
        /// <summary>
        /// Interprets the specified effect technique and adds an
        /// <see cref="EffectTechniqueDescription"/> to the collection.
        /// </summary>
        /// <param name="effect">The effect.</param>
        /// <param name="technique">The technique.</param>
        /// <param name="interpreters">The effect interpreters.</param>
        private void InterpretTechnique(Effect effect, EffectTechnique technique, EffectInterpreterCollection interpreters)
        {
            foreach (var interpreter in interpreters)
            {
                var description = interpreter.GetDescription(effect, technique);
                if (description != null)
                {
                    Add(description);
                    return;
                }
            }

            // No description found. Set default description.
            Add(new EffectTechniqueDescription(effect, technique));
        }
Exemplo n.º 39
0
        } // Render(passName, renderDelegate)

        public void SetTechnique(string techniqueName)
        {
            if (currentTechnique == techniqueName)
            {
                return;
            }
            EffectTechnique technique = GetTechnique(techniqueName);

            if (technique == null)
            {
                throw new InvalidOperationException("Given technique does not exists!");
            }
            effect.CurrentTechnique = technique;
            currentTechnique        = techniqueName;
        }
Exemplo n.º 40
0
        public SsaoEffect(Device device, string filename) : base(device, filename)
        {
            SsaoTech = FX.GetTechniqueByName("Ssao");

            _viewToTexSpace     = FX.GetVariableByName("gViewToTexSpace").AsMatrix();
            _offsetVectors      = FX.GetVariableByName("gOffsetVectors").AsVector();
            _frustumCorners     = FX.GetVariableByName("gFrustumCorners").AsVector();
            _occlusionRadius    = FX.GetVariableByName("gOcclusionRadius").AsScalar();
            _occlusionFadeStart = FX.GetVariableByName("gOcclusionFadeStart").AsScalar();
            _occlusionFadeEnd   = FX.GetVariableByName("gOcclusionFadeEnd").AsScalar();
            _surfaceEpsilon     = FX.GetVariableByName("gSurfaceEpsilon").AsScalar();

            _normalDepthMap = FX.GetVariableByName("gNormalDepthMap").AsResource();
            _randomVecMap   = FX.GetVariableByName("gRandomVecMap").AsResource();
        }
Exemplo n.º 41
0
        public void LoadContent(GraphicsDevice g, ContentManager cm)
        {
            e = cm.Load <Effect>(@"shaders/bloom");
            luminosityExtractTechnique = e.Techniques["LuminosityExtract"];
            gaussianBlurTechnique      = e.Techniques["Blur"];
            compositeTechnique         = e.Techniques["Composite"];

            PresentationParameters pp = g.PresentationParameters;

            rTarget1 = new RenderTarget2D(g, pp.BackBufferWidth, pp.BackBufferHeight, 1, g.DisplayMode.Format);
            rTarget2 = new RenderTarget2D(g, pp.BackBufferWidth, pp.BackBufferHeight, 1, g.DisplayMode.Format);

            // calculate the blur parameters
            SetBlur(8);
        }
Exemplo n.º 42
0
        public ParticleEffect(Device device, string filename) : base(device, filename) {
            StreamOutTech = FX.GetTechniqueByName("StreamOutTech");
            DrawTech = FX.GetTechniqueByName("DrawTech");

            _viewProj = FX.GetVariableByName("gViewProj").AsMatrix();
            _gameTime = FX.GetVariableByName("gGameTime").AsScalar();
            _timeStep = FX.GetVariableByName("gTimeStep").AsScalar();

            _eyePosW = FX.GetVariableByName("gEyePosW").AsVector();
            _emitPosW = FX.GetVariableByName("gEmitPosW").AsVector();
            _emitDirW = FX.GetVariableByName("gEmitDirW").AsVector();

            _texArray = FX.GetVariableByName("gTexArray").AsResource();
            _randomTex = FX.GetVariableByName("gRandomTex").AsResource();
        }
Exemplo n.º 43
0
 public Effect GetSuitableDepthShader(EffectTechnique e)
 {
     if (e.Name.Contains("constantsinstancing"))
     {
         return(depthConstantsInstancingEffect);
     }
     else if (e.Name.Contains("hardwareinstancing"))
     {
         return(depthHardwareInstancingEffect);
     }
     else
     {
         return(depthEffect);
     }
 }
Exemplo n.º 44
0
        private void LoadEffect(string shaderFileName = @"Assets\light.fx")
        {
            _effect     = Effect.FromFile(_dxDevice, shaderFileName, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
            _technique  = _effect.GetTechniqueByName("Render"); //C++ Comparaison// technique = effect->GetTechniqueByName( "Render" );
            _effectPass = _technique.GetPassByIndex(0);

            ShaderSignature signature = _effectPass.Description.Signature;

            _inputLayout = new InputLayout(_dxDevice, signature,
                                           new[] {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 32, 0)
            });
        }
        public override void SetUp()
        {
            View           = Collection["View"];
            Projection     = Collection["Projection"];
            ViewProjection = Collection["ViewProjection"];
            World          = Collection["World"];
            Rotation       = Collection["Rotation"];
            CameraPosition = Collection["CameraPosition"];
            Time           = Collection["Time"];

            ShadowTechnique  = FindTechnique("Shadow");
            ForwardTechnique = FindTechnique("Forward");

            base.SetUp();
        }
Exemplo n.º 46
0
        public void Draw(EffectTechnique technique, int pass, Matrix objectTransform)
        {
            if (_visible)
            {
                Renderer.SetWVP(_transformation * objectTransform);
                Renderer.SetInputLayout("Textured");
                Renderer.context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                Renderer.context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertexBuffer, VertexTex.Stride, 0));
                Renderer.context.InputAssembler.SetIndexBuffer(_indexBuffer, Format.R32_UInt, 0);
                _parentBox.ParentModel.SetActiveTexture(TextureName);

                technique.GetPassByIndex(pass).Apply(Renderer.context);
                Renderer.context.DrawIndexed(36, 0, 0);
            }
        }
Exemplo n.º 47
0
        public EffectTechniqueDescription GetDescription(Effect effect, EffectTechnique technique)
        {
            foreach (var pass in technique.Passes)
            {
                foreach (var annotation in pass.Annotations)
                {
                    if (annotation.Name == "RepeatParameter")
                    {
                        return(new RepeatTechniqueDescription(effect, technique));
                    }
                }
            }

            return(null);
        }
Exemplo n.º 48
0
        public TreeSpriteEffect(Device device, string filename) : base(device, filename)
        {
            Light3Tech                = FX.GetTechniqueByName("Light3");
            Light3TexAlphaClipTech    = FX.GetTechniqueByName("Light3TexAlphaClip");
            Light3TexAlphaClipFogTech = FX.GetTechniqueByName("Light3TexAlphaClipFog");

            _viewProj            = FX.GetVariableByName("gViewProj").AsMatrix();
            _eyePosW             = FX.GetVariableByName("gEyePosW").AsVector();
            _fogColor            = FX.GetVariableByName("gFogColor").AsVector();
            _fogStart            = FX.GetVariableByName("gFogStart").AsScalar();
            _fogRange            = FX.GetVariableByName("gFogRange").AsScalar();
            _dirLights           = FX.GetVariableByName("gDirLights");
            _mat                 = FX.GetVariableByName("gMaterial");
            _treeTextureMapArray = FX.GetVariableByName("gTreeMapArray").AsResource();
        }
Exemplo n.º 49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        public override void Attach(IRenderHost host)
        {
            renderTechnique = Techniques.RenderPoints;
            base.Attach(host);

            if (Geometry == null)
            {
                return;
            }

#if DEFERRED
            if (renderHost.RenderTechnique == Techniques.RenderDeferred || renderHost.RenderTechnique == Techniques.RenderGBuffer)
            {
                return;
            }
#endif

            // --- get device
            vertexLayout    = EffectsManager.Instance.GetLayout(renderTechnique);
            effectTechnique = effect.GetTechniqueByName(renderTechnique.Name);

            effectTransforms = new EffectTransformVariables(effect);

            // --- get geometry
            var geometry = Geometry as PointGeometry3D;

            // -- set geometry if given
            if (geometry != null)
            {
                /// --- set up buffers
                vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, Geometry3D.PointsVertex.SizeInBytes, CreatePointVertexArray());
            }

            /// --- set up const variables
            vViewport = effect.GetVariableByName("vViewport").AsVector();
            //this.vFrustum = effect.GetVariableByName("vFrustum").AsVector();
            vPointParams = effect.GetVariableByName("vPointParams").AsVector();

            /// --- set effect per object const vars
            var pointParams = new Vector4((float)Size.Width, (float)Size.Height, (float)Figure, (float)FigureRatio);
            vPointParams.Set(pointParams);

            /// --- create raster state
            OnRasterStateChanged(DepthBias);

            /// --- flush
            Device.ImmediateContext.Flush();
        }
Exemplo n.º 50
0
    public BoxApp(IntPtr hInstance) : base(hInstance) {
        _boxIB = null;
        _boxVB = null;
        _fx = null;
        _tech = null;
        _fxWVP = null;
        _inputLayout = null;
        _theta = 1.5f * MathF.PI;
        _phi = 0.25f * MathF.PI;
        _radius = 5.0f;

        MainWindowCaption = "Box Demo";
        _lastMousePos = new Point(0, 0);
        _world = Matrix.Identity;
        _view = Matrix.Identity;
        _proj = Matrix.Identity;
    }
 public UserInterfaceRenderCommand(Renderer renderer, Hud hud, RenderableNode rNode)
     : base(renderer, new UIMaterial(),
         new RenderableCollection(UIMaterial.ItemsDescription, new [] {rNode}))
 {
     CommandType = CommandType.UserInterfaceRenderCommand;
     CommandAttributes |= Graphics.CommandAttributes.MonoRendering;
     this.hud = hud;
     textMaterial = new TextMaterial();
     this.rNode = rNode;
     this.rNode.RenderableObject.Material = Material;
     tNode = (TransformNode)rNode.Parent;
     UpdateSprites(hud.SpriteControls);
     textTechnique = textMaterial.EffectDescription.Technique;
     textPass = textTechnique.GetPassByIndex(textMaterial.EffectDescription.Pass);
     textLayout = new InputLayout(Game.Context.Device, textPass.Description.Signature,
         TextItems.Description.InputElements);
 }
Exemplo n.º 52
0
        public InstancedBasicEffect(Device device, string filename)
            : base(device, filename)
        {
            Light1Tech = FX.GetTechniqueByName("Light1");
            Light2Tech = FX.GetTechniqueByName("Light2");
            Light3Tech = FX.GetTechniqueByName("Light3");

            Light0TexTech = FX.GetTechniqueByName("Light0Tex");
            Light1TexTech = FX.GetTechniqueByName("Light1Tex");
            Light2TexTech = FX.GetTechniqueByName("Light2Tex");
            Light3TexTech = FX.GetTechniqueByName("Light3Tex");

            Light0TexAlphaClipTech = FX.GetTechniqueByName("Light0TexAlphaClip");
            Light1TexAlphaClipTech = FX.GetTechniqueByName("Light1TexAlphaClip");
            Light2TexAlphaClipTech = FX.GetTechniqueByName("Light2TexAlphaClip");
            Light3TexAlphaClipTech = FX.GetTechniqueByName("Light3TexAlphaClip");

            Light1FogTech = FX.GetTechniqueByName("Light1Fog");
            Light2FogTech = FX.GetTechniqueByName("Light2Fog");
            Light3FogTech = FX.GetTechniqueByName("Light3Fog");

            Light0TexFogTech = FX.GetTechniqueByName("Light0TexFog");
            Light1TexFogTech = FX.GetTechniqueByName("Light1TexFog");
            Light2TexFogTech = FX.GetTechniqueByName("Light2TexFog");
            Light3TexFogTech = FX.GetTechniqueByName("Light3TexFog");

            Light0TexAlphaClipFogTech = FX.GetTechniqueByName("Light0TexAlphaClipFog");
            Light1TexAlphaClipFogTech = FX.GetTechniqueByName("Light1TexAlphaClipFog");
            Light2TexAlphaClipFogTech = FX.GetTechniqueByName("Light2TexAlphaClipFog");
            Light3TexAlphaClipFogTech = FX.GetTechniqueByName("Light3TexAlphaClipFog");

            _viewProj = FX.GetVariableByName("gViewProj").AsMatrix();
            _texTransform = FX.GetVariableByName("gTexTransform").AsMatrix();
            _eyePosW = FX.GetVariableByName("gEyePosW").AsVector();

            _fogColor = FX.GetVariableByName("gFogColor").AsVector();
            _fogStart = FX.GetVariableByName("gFogStart").AsScalar();
            _fogRange = FX.GetVariableByName("gFogRange").AsScalar();

            _dirLights = FX.GetVariableByName("gDirLights");
            _mat = FX.GetVariableByName("gMaterial");
            _diffuseMap = FX.GetVariableByName("gDiffuseMap").AsResource();
        }
Exemplo n.º 53
0
        public BoxApp(IntPtr hInstance)
            : base(hInstance) {
            _ib = null;
            _vb = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _theta = 1.5f * MathF.PI;
            _phi = 0.1f * MathF.PI;
            _radius = 200.0f;

            MainWindowCaption = "Hills Demo";
            _lastMousePos = new Point(0, 0);
            _world = Matrix.Identity;
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _gridIndexCount = 0;
        }
Exemplo n.º 54
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.Debug | ShaderFlags.EnableStrictness, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("Render");
				m_Pass0 = m_Technique.GetPassByName("P0");

				/*m_Layout = new InputLayout(GameEnvironment.Device, m_Pass0.Description.Signature, new[] {
					new InputElement( "POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
					new InputElement( "NORMAL", 0, Format.R32G32B32_Float, 0, 12, InputClassification.PerVertexData, 0),
					new InputElement( "TEXCOORD", 0, Format.R32G32_Float, 0, 24, InputClassification.PerVertexData, 0),
				});*/

				m_Layout = new InputLayout(GameEnvironment.Device, m_Pass0.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)
				});

				//texColorMap
				//texNormalMap
				//texDiffuseMap
				//texSpecularMap

				//m_DiffuseVariable = m_Effect.GetVariableByName("g_txDiffuse").AsResource();
				m_DiffuseVariable = m_Effect.GetVariableByName("texColorMap").AsResource();
				m_NormalMapVariable = m_Effect.GetVariableByName("texNormalMap").AsResource();
				m_WorldVariable = m_Effect.GetVariableByName("World").AsMatrix();
				m_ViewVariable = m_Effect.GetVariableByName("View").AsMatrix();
				m_InvViewVariable = m_Effect.GetVariableByName("InvView").AsMatrix();
				m_ProjectionVariable = m_Effect.GetVariableByName("Projection").AsMatrix();
				//m_SpecularMapVariable = m_Effect.GetVariableByName("g_txEnvMap").AsResource();
				m_SpecularMapVariable = m_Effect.GetVariableByName("texSpecularMap").AsResource();
				m_DiffuseMapVariable = m_Effect.GetVariableByName("texDiffuseMap").AsResource();
				m_EyeVariable = m_Effect.GetVariableByName("Eye").AsVector();

				m_Disposed = false;
			}
		}
Exemplo n.º 55
0
        public BuildShadowMapEffect(Device device, string filename) : base(device, filename) {
            BuildShadowMapTech = FX.GetTechniqueByName("BuildShadowMapTech");
            BuildShadowMapAlphaClipTech = FX.GetTechniqueByName("BuildShadowMapAlphaClipTech");
            TessBuildShadowMapTech = FX.GetTechniqueByName("TessBuildShadowMapTech"); 
            TessBuildShadowMapAlphaClipTech = FX.GetTechniqueByName("TessBuildShadowMapAlphaClipTech");

            _heightScale = FX.GetVariableByName("gHeightScale").AsScalar();
            _maxTessDistance = FX.GetVariableByName("gMaxTessDistance").AsScalar();
            _minTessDistance = FX.GetVariableByName("gMinTessDistance").AsScalar();
            _minTessFactor = FX.GetVariableByName("gMinTessFactor").AsScalar();
            _maxTessFactor = FX.GetVariableByName("gMaxTessFactor").AsScalar();
            _viewProj = FX.GetVariableByName("gViewProj").AsMatrix();

            _normalMap = FX.GetVariableByName("gNormalMap").AsResource();
            _diffuseMap = FX.GetVariableByName("gDiffuseMap").AsResource();

            _worldViewProj = FX.GetVariableByName("gWorldViewProj").AsMatrix();
            _world = FX.GetVariableByName("gWorld").AsMatrix();
            _worldInvTranspose = FX.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _texTransform = FX.GetVariableByName("gTexTransform").AsMatrix();
            _eyePosW = FX.GetVariableByName("gEyePosW").AsVector();
        }
Exemplo n.º 56
0
        /// <summary>
        /// Create our test RenderEffect.
        /// </summary>
        /// <param name="Device"></param>
        public TestEffect(Device Device)
        {
            this.Device = Device;
            ImmediateContext = Device.ImmediateContext;

            // Compile our shader...
            string compileErrors;
            var compiledShader = SlimDX.D3DCompiler.ShaderBytecode.CompileFromFile
            (
                "../../Effects/TestEffect/TestEffect.fx",
                null,
                "fx_5_0",
                SlimDX.D3DCompiler.ShaderFlags.None,
                SlimDX.D3DCompiler.EffectFlags.None,
                null,
                null,
                out compileErrors
            );

            if (compileErrors != null && compileErrors != "")
            {
                throw new EffectBuildException(compileErrors);
            }

            Effect = new Effect(Device, compiledShader);
            EffectTechnique = Effect.GetTechniqueByName("TestTechnique");

            var vertexDesc = new[]
            {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("COLOR", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 12, 0, InputClassification.PerVertexData, 0)
            };

            WorldViewProj = SlimDX.Matrix.Identity;
            CPO_WorldViewProj = Effect.GetVariableByName("gWorldViewProj").AsMatrix();
            InputLayout = new InputLayout(Device, EffectTechnique.GetPassByIndex(0).Description.Signature, vertexDesc);

            Util.ReleaseCom(ref compiledShader);
        }
Exemplo n.º 57
0
        public SkullDemo(IntPtr hInstance) : base(hInstance) {
            _vb = null;
            _ib = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _wireframeRS = null;
            _skullIndexCount = 0;
            _theta = 1.5f*MathF.PI;
            _phi = 0.1f*MathF.PI;
            _radius = 20.0f;

            MainWindowCaption = "Skull Demo";

            _lastMousePos = new Point(0,0);

            _view = Matrix.Identity;
            _proj = Matrix.Identity;
            _skullWorld = Matrix.Translation(0.0f, -2.0f, 0.0f);

        }
Exemplo n.º 58
0
		public void Initialize(Device device) {
			_b = EffectUtils.Load("DeferredGObject");
			E = new Effect(device, _b);

			TechStandardDeferred = E.GetTechniqueByName("StandardDeferred");
			TechStandardForward = E.GetTechniqueByName("StandardForward");
			TechAmbientShadowDeferred = E.GetTechniqueByName("AmbientShadowDeferred");
			TechTransparentDeferred = E.GetTechniqueByName("TransparentDeferred");
			TechTransparentForward = E.GetTechniqueByName("TransparentForward");
			TechTransparentMask = E.GetTechniqueByName("TransparentMask");

			for (var i = 0; i < TechStandardDeferred.Description.PassCount && InputSignaturePNTG == null; i++) {
				InputSignaturePNTG = TechStandardDeferred.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePNTG == null) throw new System.Exception("input signature (DeferredGObject, PNTG, StandardDeferred) == null");
			LayoutPNTG = new InputLayout(device, InputSignaturePNTG, InputLayouts.VerticePNTG.InputElementsValue);
			for (var i = 0; i < TechAmbientShadowDeferred.Description.PassCount && InputSignaturePT == null; i++) {
				InputSignaturePT = TechAmbientShadowDeferred.GetPassByIndex(i).Description.Signature;
			}
			if (InputSignaturePT == null) throw new System.Exception("input signature (DeferredGObject, PT, AmbientShadowDeferred) == null");
			LayoutPT = new InputLayout(device, InputSignaturePT, InputLayouts.VerticePT.InputElementsValue);

			FxWorld = E.GetVariableByName("gWorld").AsMatrix();
			FxWorldInvTranspose = E.GetVariableByName("gWorldInvTranspose").AsMatrix();
			FxWorldViewProj = E.GetVariableByName("gWorldViewProj").AsMatrix();
			FxDiffuseMap = E.GetVariableByName("gDiffuseMap").AsResource();
			FxNormalMap = E.GetVariableByName("gNormalMap").AsResource();
			FxMapsMap = E.GetVariableByName("gMapsMap").AsResource();
			FxDetailsMap = E.GetVariableByName("gDetailsMap").AsResource();
			FxDetailsNormalMap = E.GetVariableByName("gDetailsNormalMap").AsResource();
			FxReflectionCubemap = E.GetVariableByName("gReflectionCubemap").AsResource();
			FxEyePosW = E.GetVariableByName("gEyePosW").AsVector();
			FxAmbientDown = E.GetVariableByName("gAmbientDown").AsVector();
			FxAmbientRange = E.GetVariableByName("gAmbientRange").AsVector();
			FxLightColor = E.GetVariableByName("gLightColor").AsVector();
			FxDirectionalLightDirection = E.GetVariableByName("gDirectionalLightDirection").AsVector();
			FxMaterial = E.GetVariableByName("gMaterial");
		}
Exemplo n.º 59
0
        private void CompileShader(Device device, string fullPath)
        {
            _File = fullPath;

            _CompiledEffect = ShaderBytecode.CompileFromFile(_File, "SpriteTech", "fx_5_0");

            if (_CompiledEffect.HasErrors) {
                Log.Write("Shader compilation failed with status code: {0} - {1} | Path: {2}", _CompiledEffect.ResultCode.Code, _CompiledEffect.Message, _File);
                return;
            }

            _Effect = new Effect(device, _CompiledEffect);
            _EffectTechnique = _Effect.GetTechniqueByName("SpriteTech");
            _SpriteMap = _Effect.GetVariableByName("SpriteTex").AsShaderResource();
            var _EffectPass = _EffectTechnique.GetPassByIndex(0).Description.Signature;

            InputElement[] _LayoutDescription = {
                new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
                new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0)
            };

            _InputLayout = new InputLayout(device, _EffectPass, _LayoutDescription);
        }
        public void Blit(Effect effect, EffectTechnique technique, params RenderTargetView[] targets)
        {
            view.Device10.OutputMerger.SetTargets(targets);
            /*foreach(var target in targets)
                view.Device10.ClearRenderTargetView(target, Color.Black);*/
            view.Device10.Rasterizer.SetViewports(new SlimDX.Direct3D10.Viewport
            {
                Width = ((Texture2D)targets[0].Resource).Description.Width,
                Height = ((Texture2D)targets[0].Resource).Description.Height,
                MaxZ = 1
            });

            var sp = view.Content.Acquire<Content.Mesh10>(screenPlane);

            sp.Setup(view.Device10, view.Content.Acquire<InputLayout>(new Graphics.Content.VertexStreamLayoutFromEffect
            {
                Signature10 = technique.GetPassByIndex(0).Description.Signature,
                Layout = sp.VertexStreamLayout
            }));

            technique.GetPassByIndex(0).Apply();
            sp.Draw(view.Device10);
            view.Device10.OutputMerger.SetTargets((RenderTargetView)null);
        }