Ejemplo n.º 1
0
 public override void Init(EffectParameter _p)
 {
     base.Init(_p);
     numbericType = EffectNumbericType.Percentage;
     type = EffectType.Ice;
     coverType = EffectCoverType.Cover;
 }
Ejemplo n.º 2
0
        internal EffectConstantBuffer(string name, int size, EffectParameterDescription[] paramDescription)
            : base(size)
        {
            _device = GraphicManager.Device;

            Name = name;
            Size = size;
            _hashCode = GetHashCode(name, size, paramDescription);

            if (paramDescription != null)
            {
                Parameters = new Dictionary<string, EffectParameter>(paramDescription.Length);

                for (int i = 0; i < paramDescription.Length; i++)
                {
                    EffectParameter parameter = new EffectParameter(paramDescription[i], this);
                    Parameters.Add(parameter.Name, parameter);
                }
            }

            Clear();

            _nativeBuffer = Buffer.NewConstantBuffer(size);

            IsDirty = true;

        }
Ejemplo n.º 3
0
        /// <summary>
        /// Lazily recomputes the world inverse transpose matrix and
        /// eye position based on the current effect parameter settings.
        /// </summary>
        internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view,
                                                             EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam)
        {
            // Set the world and world inverse transpose matrices.
            if ((dirtyFlags & EffectDirtyFlags.World) != 0)
            {
                Matrix worldTranspose;
                Matrix worldInverseTranspose;

                Matrix.Invert(ref world, out worldTranspose);
                Matrix.Transpose(ref worldTranspose, out worldInverseTranspose);

                worldParam.SetValue(world);
                worldInverseTransposeParam.SetValue(worldInverseTranspose);

                dirtyFlags &= ~EffectDirtyFlags.World;
            }

            // Set the eye position.
            if ((dirtyFlags & EffectDirtyFlags.EyePosition) != 0)
            {
                Matrix viewInverse;

                Matrix.Invert(ref view, out viewInverse);

                eyePositionParam.SetValue(viewInverse.TranslationVector);

                dirtyFlags &= ~EffectDirtyFlags.EyePosition;
            }

            return dirtyFlags;
        }
Ejemplo n.º 4
0
        public ParticleSystem(GraphicsDevice device, ContentManager content)
        {
            this.device = device;

            // Create vertex buffer used to spawn new particles
            this.particleStart = Buffer.Vertex.New<ParticleVertex>(device, MAX_NEW);

            // Create vertex buffers to use for updating and drawing the particles alternatively
            var vbFlags = BufferFlags.VertexBuffer | BufferFlags.StreamOutput;
            this.particleDrawFrom = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);
            this.particleStreamTo = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);

            this.layout = VertexInputLayout.FromBuffer(0, this.particleStreamTo);
            this.effect = content.Load<Effect>("ParticleEffect");
            this.texture = content.Load<Texture2D>("Dot");

            this.viewParameter = effect.Parameters["_view"];
            this.projParameter = effect.Parameters["_proj"];
            this.lookAtMatrixParameter = effect.Parameters["_lookAtMatrix"];
            this.elapsedSecondsParameter = effect.Parameters["_elapsedSeconds"];
            this.camDirParameter = effect.Parameters["_camDir"];
            this.gravityParameter = effect.Parameters["_gravity"];
            this.textureParameter = effect.Parameters["_texture"];
            this.samplerParameter = effect.Parameters["_sampler"];
            this.updatePass = effect.Techniques["UpdateTeq"].Passes[0];
            this.renderPass = effect.Techniques["RenderTeq"].Passes[0];
        }
        protected override void Initialize()
        {
            base.Initialize();

            _pixelShaderConstantBuffer = ConstantBuffers["SamplingConstants"];
            _encodeConstantsParameter = _pixelShaderConstantBuffer.Parameters["EncodeConstants"];
        }
Ejemplo n.º 6
0
 internal EffectAnnotation(EffectParameter parameter)
 {
   this.ParameterClass = parameter.ParameterClass;
   this.ParameterType = parameter.ParameterType;
   this.Name = parameter.Name;
   this.RowCount = parameter.RowCount;
   this.ColumnCount = parameter.ColumnCount;
   this.Semantic = parameter.Semantic;
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        public PrimitiveQuad(GraphicsDevice graphicsDevice)
        {
            GraphicsDevice = graphicsDevice;
            quadEffect = ToDispose(new Effect(GraphicsDevice, effectBytecode));
            quadPass = quadEffect.CurrentTechnique.Passes[0];
            matrixParameter = quadEffect.Parameters["MatrixTransform"];
            Transform = Matrix.Identity;

            sharedData = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerDevice, "Toolkit::PrimitiveQuad::VertexBuffer", () => new SharedData(GraphicsDevice));
        }
Ejemplo n.º 8
0
        protected override void Initialize()
        {
            base.Initialize();

            _vertexShaderConstantBuffer = ConstantBuffers["VertexShaderConstants"];

            _viewMatrixParameter = _vertexShaderConstantBuffer.Parameters["ViewMatrix"];
            _projectionMatrixParameter = _vertexShaderConstantBuffer.Parameters["ProjectionMatrix"];
            _modelMatrixParameter = _vertexShaderConstantBuffer.Parameters["ModelMatrix"];
            _scaleFactorParameter = _vertexShaderConstantBuffer.Parameters["scaleFactor"];
        }
Ejemplo n.º 9
0
        public Effect(EffectData effectData)
        {
            Name = effectData.Name;

            CBufferLinks = new List<CBufferLink>();
            ConstantBuffers = new Dictionary<string, EffectConstantBuffer>();
            Parameters = new Dictionary<string, EffectParameter>();

            foreach (CBufferLinkData cb in effectData.CBuffers)
            {
                EffectConstantBuffer cBuffer = MaterialManager.ConstantBuffers[cb.CBuffer];

                ConstantBuffers.Add(cb.CBuffer, cBuffer);

                CBufferLinks.Add(new CBufferLink() { CBuffer = cBuffer, Slot = cb.Slot });

                foreach (EffectParameter parameter in cBuffer.Parameters.Values)
                {
                    Parameters.Add(parameter.Name, parameter);
                }

            }

            Techniques = new Dictionary<string, EffectTechnique>();

            foreach (TechniqueData td in effectData.Techniques)
            {
                TechniqueTags tags = new TechniqueTags(td.Tags);
                EffectTechnique technique = new EffectTechnique(td.Name, tags,this);
                
                Techniques.Add(td.Name, technique);
                SetCurrentTechnique(td.Name);

                technique.Passes = new List<EffectPass>();

                foreach (PassData pd in td.Passes)
                {

                    EffectPass pass = new EffectPass(pd.Rasterizer, pd.Blend, pd.DepthStencil,
                        pd.Shader, pd.VertexShaderEntryPoint, pd.PixelShaderEntryPoint, tags, this);
                    technique.Passes.Add(pass);

                }

            }

            WorldMatrix = Parameters["world"];
            ViewMatrix = Parameters["view"];
            ProjectionMatrix = Parameters["projection"];
            WolrdInverseTrasposeMatrix = Parameters["worldInverseTraspose"];
            EyePos = Parameters["eyePos"];

        }
Ejemplo n.º 10
0
        protected override void Initialize()
        {
            base.Initialize();

            _constantBuffer = ConstantBuffers["CB0"];

            _scaleParameter = _constantBuffer.Parameters["scale"];
            _offsetParameter = _constantBuffer.Parameters["offset"];

            _textureParameter = Parameters["tex"];

            Parameters["sam"].SetResource(GetSampler());
        }
        protected override void Initialize()
        {
            base.Initialize();

            _colorTextureParameter = Parameters["ColorTexture"];
            _colorResidencyParameter = Parameters["ColorResidency"];
            _normalTextureParameter = Parameters["NormalTexture"];
            _normalResidencyParameter = Parameters["NormalResidency"];

            Parameters["Trilinear"].SetResource(GraphicsDevice.SamplerStates.AnisotropicWrap);
            Parameters["MaxFilter"].SetResource(GraphicsDevice.SamplerStates.LinearWrap);

            _pixelShaderConstantBuffer = ConstantBuffers["PixelShaderConstants"];

            _sunPositionParameter = _pixelShaderConstantBuffer.Parameters["SunPosition"];
        }
Ejemplo n.º 12
0
        public DirectionalLight(
			EffectParameter directionParameter,
			EffectParameter diffuseColorParameter,
			EffectParameter specularColorParameter,
			DirectionalLight cloneSource
		)
        {
            this.diffuseColorParameter = diffuseColorParameter;
            this.directionParameter = directionParameter;
            this.specularColorParameter = specularColorParameter;
            if (cloneSource != null)
            {
                DiffuseColor = cloneSource.DiffuseColor;
                Direction = cloneSource.Direction;
                SpecularColor = cloneSource.SpecularColor;
                Enabled = cloneSource.Enabled;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        public PrimitiveQuad(GraphicsDevice graphicsDevice)
        {
            GraphicsDevice = graphicsDevice;
            quadEffect = ToDispose(new Effect(GraphicsDevice, effectBytecode));
            quadPass = quadEffect.CurrentTechnique.Passes[0];
            matrixParameter = quadEffect.Parameters["MatrixTransform"];

            textureCopyPass = quadEffect.CurrentTechnique.Passes[1];
            textureParameter = quadEffect.Parameters["Texture"];
            textureSamplerParameter = quadEffect.Parameters["TextureSampler"];

            // Default LinearClamp
            textureSamplerParameter.SetResource(GraphicsDevice.SamplerStates.LinearClamp);

            Transform = Matrix.Identity;

            sharedData = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerDevice, "Toolkit::PrimitiveQuad::VertexBuffer", () => new SharedData(GraphicsDevice));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Lazily recomputes the world+view+projection matrix and
        /// fog vector based on the current effect parameter settings.
        /// </summary>
        internal static EffectDirtyFlags SetWorldViewProjAndFog(EffectDirtyFlags dirtyFlags,
                                                                ref Matrix world, ref Matrix view, ref Matrix projection, ref Matrix worldView,
                                                                bool fogEnabled, float fogStart, float fogEnd,
                                                                EffectParameter worldViewProjParam, EffectParameter fogVectorParam)
        {
            // Recompute the world+view+projection matrix?
            if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != 0)
            {
                Matrix worldViewProj;
                
                Matrix.Multiply(ref world, ref view, out worldView);
                Matrix.Multiply(ref worldView, ref projection, out worldViewProj);
                
                worldViewProjParam.SetValue(worldViewProj);
                
                dirtyFlags &= ~EffectDirtyFlags.WorldViewProj;
            }

            if (fogEnabled)
            {
                // Recompute the fog vector?
                if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != 0)
                {
                    SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam);

                    dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable);
                }
            }
            else
            {
                // When fog is disabled, make sure the fog vector is reset to zero.
                if ((dirtyFlags & EffectDirtyFlags.FogEnable) != 0)
                {
                    fogVectorParam.SetValue(Vector4.Zero);

                    dirtyFlags &= ~EffectDirtyFlags.FogEnable;
                }
            }

            return dirtyFlags;
        }
        private void ApplyFrustumCorners(EffectParameter frustumCorners, Vector2 topLeftVertex, Vector2 bottomRightVertex)
        {
            float dx = _currentFrustumCorners[1].X - _currentFrustumCorners[0].X;
            float dy = _currentFrustumCorners[0].Y - _currentFrustumCorners[2].Y;

            _localFrustumCorners[0]    = _currentFrustumCorners[2];
            _localFrustumCorners[0].X += dx * (topLeftVertex.X * 0.5f + 0.5f);
            _localFrustumCorners[0].Y += dy * (bottomRightVertex.Y * 0.5f + 0.5f);

            _localFrustumCorners[1]    = _currentFrustumCorners[2];
            _localFrustumCorners[1].X += dx * (bottomRightVertex.X * 0.5f + 0.5f);
            _localFrustumCorners[1].Y += dy * (bottomRightVertex.Y * 0.5f + 0.5f);

            _localFrustumCorners[2]    = _currentFrustumCorners[2];
            _localFrustumCorners[2].X += dx * (topLeftVertex.X * 0.5f + 0.5f);
            _localFrustumCorners[2].Y += dy * (topLeftVertex.Y * 0.5f + 0.5f);

            _localFrustumCorners[3]    = _currentFrustumCorners[2];
            _localFrustumCorners[3].X += dx * (bottomRightVertex.X * 0.5f + 0.5f);
            _localFrustumCorners[3].Y += dy * (topLeftVertex.Y * 0.5f + 0.5f);

            frustumCorners.SetValue(_localFrustumCorners);
        }
Ejemplo n.º 16
0
 public GaussianBlur(Game game, int screenWidth, int screenHeight)
 {
     if (m_renderHolder != null && !m_renderHolder.IsDisposed)
     {
         m_renderHolder.Dispose();
     }
     if (m_renderHolder2 != null && !m_renderHolder2.IsDisposed)
     {
         m_renderHolder2.Dispose();
     }
     if (LevelEV.SAVE_FRAMES)
     {
         m_renderHolder  = new RenderTarget2D(game.GraphicsDevice, screenWidth / 2, screenHeight / 2);
         m_renderHolder2 = new RenderTarget2D(game.GraphicsDevice, screenWidth / 2, screenHeight / 2);
     }
     else
     {
         m_renderHolder  = new RenderTarget2D(game.GraphicsDevice, screenWidth, screenHeight);
         m_renderHolder2 = new RenderTarget2D(game.GraphicsDevice, screenWidth, screenHeight);
     }
     effect             = game.Content.Load <Effect>("Shaders\\GaussianBlurMask");
     m_offsetParameters = effect.Parameters["offsets"];
 }
Ejemplo n.º 17
0
        public void LoadContent(Game game, string diffuseTexture, Color starColor, Color haloColor)
        {
            starDiffuse = game.Content.Load <Texture2D>(@"textures\" + diffuseTexture);
            haloDiffuse = game.Content.Load <Texture2D>(@"textures\glow");

            spriteCenter = new Vector2(haloDiffuse.Width / 2, haloDiffuse.Height / 2);

            starEffect = game.Content.Load <Effect>(@"shaders\suneffect");

            starWorldMatrix      = starEffect.Parameters["World"];
            starViewMatrix       = starEffect.Parameters["View"];
            starProjectionMatrix = starEffect.Parameters["Projection"];

            starDiffuseTexture = starEffect.Parameters["DiffuseTexture"];

            starColorData = starEffect.Parameters["StarColor"];

            halo           = new SpriteBatch(game.GraphicsDevice);
            this.starColor = new Vector4((float)starColor.R / 255.0f, (float)starColor.G / 255.0f, (float)starColor.B / 255.0f, 1.0f);
            this.haloColor = haloColor;

            star.LoadContent(game);
        }
Ejemplo n.º 18
0
        public RTSFXEntity(Effect _fx)
        {
            if (_fx == null)
            {
                throw new ArgumentNullException("A Null Effect Was Used");
            }

            // Set The Effect To The First Technique
            fx = _fx;
            fx.CurrentTechnique = fx.Techniques[0];

            // Get The Passes
            fxPassBuilding = fx.CurrentTechnique.Passes[PASS_KEY_BUILDING];
            fxPassUnit     = fx.CurrentTechnique.Passes[PASS_KEY_UNIT];

            // Get The Parameters
            fxpWorld     = fx.Parameters[PARAM_KEY_WORLD];
            fxpVP        = fx.Parameters[PARAM_KEY_VP];
            fxpColP      = fx.Parameters[PARAM_KEY_COLOR_PRIMARY];
            fxpColS      = fx.Parameters[PARAM_KEY_COLOR_SECONDARY];
            fxpColT      = fx.Parameters[PARAM_KEY_COLOR_TERTIARY];
            fxpTexelSize = fx.Parameters[PARAM_KEY_TEXEL_SIZE];
        }
Ejemplo n.º 19
0
        private IArmor Finger()
        {
            IArmor armor = CreateArmor(AvalableItemPosition.Finger, 17, new Gold());

            armor.ExamineDescription  = "The gem is made of a red stone with white veins that look like a swirl frozen in time.";
            armor.LookDescription     = "The ring is made of a thick gold band with a red stone in the center.";
            armor.ShortDescription    = "Gold Ring.";
            armor.SentenceDescription = "ring";
            armor.KeyWords.Add("red");
            armor.KeyWords.Add("stone");
            armor.KeyWords.Add("gold");
            armor.KeyWords.Add("ring");

            IEnchantment enchantment = new HeartbeatBigTickEnchantment();

            enchantment.Effect = new RecoverStamina();
            IEffectParameter effectParameter = new EffectParameter();

            effectParameter.Dice  = new Dice(1, 1);
            enchantment.Parameter = effectParameter;

            return(armor);
        }
Ejemplo n.º 20
0
        public Property <Matrix[]> GetMatrixArrayParameter(string name)
        {
            IProperty result = null;

            if (!this.properties.TryGetValue(name, out result))
            {
                Property <Matrix[]> property = new Property <Matrix[]>();
                this.Add(new SetBinding <Matrix[]>(property, delegate(Matrix[] value)
                {
                    if (this.effect != null)
                    {
                        EffectParameter param = this.effect.Parameters[name];
                        if (param != null)
                        {
                            param.SetValue(value);
                        }
                    }
                }));
                this.properties[name] = property;
                result = property;
            }
            return((Property <Matrix[]>)result);
        }
Ejemplo n.º 21
0
        public override void OnCreateDevice()
        {
            effect = SpacewarGame.ContentManager.Load <Effect>(SpacewarGame.Settings.MediaPath + @"shaders\ship");

            worldParam                = effect.Parameters["world"];
            inverseWorldParam         = effect.Parameters["inverseWorld"];
            worldViewProjectionParam  = effect.Parameters["worldViewProjection"];
            viewPositionParam         = effect.Parameters["viewPosition"];
            skinTextureParam          = effect.Parameters["SkinTexture"];
            normalTextureParam        = effect.Parameters["NormalMapTexture"];
            reflectionTextureParam    = effect.Parameters["ReflectionTexture"];
            ambientParam              = effect.Parameters["Ambient"];
            directionalDirectionParam = effect.Parameters["DirectionalDirection"];
            directionalColorParam     = effect.Parameters["DirectionalColor"];
            pointPositionParam        = effect.Parameters["PointPosition"];
            pointColorParam           = effect.Parameters["PointColor"];
            pointFactorParam          = effect.Parameters["PointFactor"];
            materialParam             = effect.Parameters["Material"];

            blackTexture = SpacewarGame.ContentManager.Load <Texture2D>(SpacewarGame.Settings.MediaPath + @"Textures\Black");

            SetupEffect();
        }
Ejemplo n.º 22
0
        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="BloomFilter"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public BloomFilter(IGraphicsService graphicsService)
            : base(graphicsService)
        {
            _effect = GraphicsService.Content.Load <Effect>("DigitalRune/PostProcessing/BloomFilter");
            _viewportSizeParameter    = _effect.Parameters["ViewportSize"];
            _bloomThresholdParameter  = _effect.Parameters["BloomThreshold"];
            _bloomIntensityParameter  = _effect.Parameters["BloomIntensity"];
            _bloomSaturationParameter = _effect.Parameters["BloomSaturation"];
            _sceneTextureParameter    = _effect.Parameters["SceneTexture"];
            _bloomTextureParameter    = _effect.Parameters["BloomTexture"];
            _brightnessPass           = _effect.CurrentTechnique.Passes["Brightness"];
            _combinePass = _effect.CurrentTechnique.Passes["Combine"];

            _blur = new Blur(graphicsService);
            _blur.InitializeGaussianBlur(7, 7.0f / 3.0f, true);

            _downsampleFilter = PostProcessHelper.GetDownsampleFilter(graphicsService);

            Threshold        = 0.7f;
            Intensity        = 1.5f;
            Saturation       = 0.5f;
            DownsampleFactor = 4;
        }
Ejemplo n.º 23
0
        public WaterReflectionEffect(Effect effect)
            : base(effect)
        {
            this.CurrentTechnique = this.Techniques["WaterReflectionTechnique"];

            this.timeParam                           = this.Parameters["_time"];
            this.sparkleIntensityParam               = this.Parameters["_sparkleIntensity"];
            this.sparkleColorParam                   = this.Parameters["_sparkleColor"];
            this.screenSpaceVerticalOffsetParam      = this.Parameters["_screenSpaceVerticalOffset"];
            this.perspectiveCorrectionIntensityParam = this.Parameters["_perspectiveCorrectionIntensity"];
            this.firstDisplacementSpeedParam         = this.Parameters["_firstDisplacementSpeed"];
            this.secondDisplacementSpeedParam        = this.Parameters["_secondDisplacementSpeed"];
            this.secondDisplacementScaleParam        = this.Parameters["_secondDisplacementScale"];

            this.SparkleIntensity = 0.015f;
            this.SparkleColor     = Color.White;
            this.PerspectiveCorrectionIntensity = 0.3f;
            this.FirstDisplacementSpeed         = 0.06f;
            this.SecondDisplacementSpeed        = 0.02f;
            this.SecondDisplacementScale        = 3f;
            this.ReflectionIntensity            = 0.85f;
            this.NormalMagnitude = 0.03f;
        }
Ejemplo n.º 24
0
        public Property <RenderTarget2D> GetRenderTarget2DParameter(string name)
        {
            IProperty result = null;

            if (!this.properties.TryGetValue(name, out result))
            {
                Property <RenderTarget2D> property = new Property <RenderTarget2D>();
                this.Add(new SetBinding <RenderTarget2D>(property, delegate(RenderTarget2D value)
                {
                    if (this.effect != null)
                    {
                        EffectParameter param = this.effect.Parameters[name];
                        if (param != null && (value == null || !value.IsDisposed))
                        {
                            param.SetValue(value);
                        }
                    }
                }));
                this.properties[name] = property;
                result = property;
            }
            return((Property <RenderTarget2D>)result);
        }
Ejemplo n.º 25
0
        public void SetupOceanShaderParameters()
        {
            worldOceanParameter      = oceanEffect.Parameters["World"];
            viewOceanParameter       = oceanEffect.Parameters["View"];
            projectionOceanParameter = oceanEffect.Parameters["Projection"];

            ambientColorOceanParameter     = oceanEffect.Parameters["AmbientColor"];
            ambientIntensityOceanParameter = oceanEffect.Parameters["AmbientIntensity"];

            diffuseColorOceanParameter     = oceanEffect.Parameters["DiffuseColor"];
            diffuseIntensityOceanParameter = oceanEffect.Parameters["DiffuseIntensity"];
            lightDirectionOceanParameter   = oceanEffect.Parameters["LightDirection"];

            eyePosOceanParameter        = oceanEffect.Parameters["EyePosition"];
            specularColorOceanParameter = oceanEffect.Parameters["SpecularColor"];

            colorMapTextureOceanParameter  = oceanEffect.Parameters["ColorMap"];
            normalMapTextureOceanParameter = oceanEffect.Parameters["NormalMap"];
            totalTimeOceanParameter        = oceanEffect.Parameters["TotalTime"];

            rippleSpeedParameter  = oceanEffect.Parameters["rippleSpeed"];
            rippleHeightParameter = oceanEffect.Parameters["rippleHeight"];
        }
Ejemplo n.º 26
0
        /// <inheritdoc/>
        public EffectParameterBinding GetBinding(Effect effect, EffectParameter parameter, IDictionary <string, object> opaqueData)
        {
            if (effect is AlphaTestEffect ||
                effect is BasicEffect ||
                effect is DualTextureEffect ||
                effect is EnvironmentMapEffect ||
                effect is SkinnedEffect)
            {
                // The ShaderIndex parameter is set by effect technique bindings.
                var description = effect.GetParameterDescriptions()[parameter];
                if (description.Semantic == "XnaShaderIndex")
                {
                    return(new NullParameterBinding <int>(effect, parameter));
                }

                if (description.Semantic == "XnaFogVector")
                {
                    return(new FogVectorParameterBinding(effect, parameter));
                }
            }

            return(null);
        }
Ejemplo n.º 27
0
        private void ParameterListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ParameterListBox.SelectedIndex == -1)
            {
                return;
            }

            if (_selectedParam != null)
            {
                _selectedParam.Json         = AddonTextEditor.Text;
                _selectedParam.Lang         = LangTextEditor.Text;
                _params[_selectedParam.Key] = _selectedParam;
                AddonManager.CurrentAddon.Effect.Parameters = _params;
                AddonManager.SaveCurrentAddon();
            }

            var selectedKey = ((KeyValuePair <string, EffectParameter>)ParameterListBox.SelectedItem).Key;

            _selectedParam = _params[selectedKey];

            AddonTextEditor.Text = _selectedParam.Json;
            LangTextEditor.Text  = _selectedParam.Lang;
        }
Ejemplo n.º 28
0
        public GaussianBlurEffect() : base(Core.GraphicsDevice, EffectResource.GaussianBlurBytes)
        {
            _blurWeightsParam = Parameters["_sampleWeights"];
            _blurOffsetsParam = Parameters["_sampleOffsets"];

            // Look up how many samples our gaussian blur effect supports.
            _sampleCount = _blurWeightsParam.Elements.Count;

            // Create temporary arrays for computing our filter settings.
            _sampleWeights           = new float[_sampleCount];
            _verticalSampleOffsets   = new Vector2[_sampleCount];
            _horizontalSampleOffsets = new Vector2[_sampleCount];

            // The first sample always has a zero offset.
            _verticalSampleOffsets[0]   = Vector2.Zero;
            _horizontalSampleOffsets[0] = Vector2.Zero;

            // we can calculate the sample weights just once since they are always the same for horizontal or vertical blur
            CalculateSampleWeights();

            SetBlurEffectParameters(_horizontalBlurDelta, 0, _horizontalSampleOffsets);
            PrepareForHorizontalBlur();
        }
Ejemplo n.º 29
0
        protected override void GetParameters()
        {
            //Binding the effect parameters in to Effect File;

            // Geometry
            world          = effect.Parameters["world"];
            viewProj       = effect.Parameters["viewProjection"];
            worldForNormal = effect.Parameters["worldForNormal"];
            cameraPosition = effect.Parameters["cameraPosition"];

            // Material
            emissiveColor  = effect.Parameters["emissiveColor"];
            diffuseColor   = effect.Parameters["diffuseColor"];
            specularColor  = effect.Parameters["specularColor"];
            specularPower  = effect.Parameters["specularPower"];
            toonTexture    = effect.Parameters["toonTexture"];
            textureEnabled = effect.Parameters["TextureEnabled"];

            // Lights
            light             = effect.Parameters["light"];
            ambientLightColor = effect.Parameters["ambientLightColor"];
            numberOfLights    = effect.Parameters["numberOfLights"];
        }
Ejemplo n.º 30
0
        //--------------------------------------------------------------
        #region Properties & Events
        //--------------------------------------------------------------
        #endregion


        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="FogRenderer"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public FogRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            {
                throw new ArgumentNullException("graphicsService");
            }

            Order   = 3;
            _effect = graphicsService.Content.Load <Effect>("DigitalRune/Deferred/Fog");
            _parameterViewportSize       = _effect.Parameters["ViewportSize"];
            _parameterFrustumCorners     = _effect.Parameters["FrustumCorners"];
            _parameterFogParameters      = _effect.Parameters["FogParameters"];
            _parameterColor0             = _effect.Parameters["Color0"];
            _parameterColor1             = _effect.Parameters["Color1"];
            _parameterHeights            = _effect.Parameters["Heights"];
            _parameterLightDirection     = _effect.Parameters["LightDirection"];
            _parameterScatteringSymmetry = _effect.Parameters["ScatteringSymmetry"];
            _parameterGBuffer0           = _effect.Parameters["GBuffer0"];
            _passFog = _effect.Techniques[0].Passes["Fog"];
            _passFogWithHeightFalloff          = _effect.Techniques[0].Passes["FogWithHeightFalloff"];
            _passFogWithPhase                  = _effect.Techniques[0].Passes["FogWithPhase"];
            _passFogWithHeightFalloffWithPhase = _effect.Techniques[0].Passes["FogWithHeightFalloffWithPhase"];
        }
Ejemplo n.º 31
0
        private static MaterialParameterSetter CreateSetter(EffectParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.Semantic))
            {
                return(null);
            }

            var parameterType = new ParameterType()
            {
                Type = parameter.ParameterType, Rows = parameter.RowCount, Columns = parameter.ColumnCount
            };
            Type type;

            if (!ParameterTypeMappings.TryGetValue(parameterType, out type))
            {
#if WINDOWS
                Trace.TraceWarning("An automatic setter could not be created for the Material parameter \"{0}\", with semantic \"{1}\".", parameter.Name, parameter.Semantic);
#endif
            }

            var typeName = type.Name;

            if (parameter.Elements.Count > 0)
            {
                typeName += "[]";
            }

            Type setterType;
            if (SetterTypeMappings.TryGetValue(typeName, out setterType))
            {
                return(Activator.CreateInstance(setterType, parameter) as MaterialParameterSetter);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 32
0
        EffectParameter paramPixelSize;            // pixel size

        /// <summary>
        /// Create a new blur manager
        /// </summary>
        public BlurManager(GraphicsDevice graphicsDevice, Effect effect, int sizex, int sizey)
        {
            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("graphicsDevice");
            }

            if (effect == null)
            {
                throw new ArgumentNullException("effect");
            }

            gd         = graphicsDevice;
            blurEffect = effect; // save effect
            sizeX      = sizey;  // save horizontal buffer size
            sizeY      = sizex;  // save verical buffer size

            // get effect parameters
            paramWorldViewProjection = blurEffect.Parameters["g_WorldViewProj"];
            paramColorMap            = blurEffect.Parameters["g_ColorMap"];
            paramColor     = blurEffect.Parameters["g_Color"];
            paramPixelSize = blurEffect.Parameters["g_PixelSize"];

            pixelSize      = new Vector2(1.0f / sizeX, 1.0f / sizeY);
            viewProjection = Matrix.CreateOrthographicOffCenter(0.0f, sizeX, 0.0f, sizeY, -1.0f, 1.0f);

            // create vertex buffer
            vertexBuffer = new VertexBuffer(gd, typeof(VertexPositionTexture),
                                            6, BufferUsage.WriteOnly);

            // create vertex declaration
            vertexDeclaration =
                new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());

            // create vertex data
            SetVertexData();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Helper for loading and initializing the particle effect.
        /// </summary>
        void LoadParticleEffect()
        {
            Effect effect = content.Load <Effect>("ParticleEffect");

            // If we have several particle systems, the content manager will return
            // a single shared effect instance to them all. But we want to preconfigure
            // the effect with parameters that are specific to this particular
            // particle system. By cloning the effect, we prevent one particle system
            // from stomping over the parameter settings of another.

            particleEffect = effect.Clone();

            EffectParameterCollection parameters = particleEffect.Parameters;

            // Look up shortcuts for parameters that change every frame.
            effectViewParameter          = parameters["View"];
            effectProjectionParameter    = parameters["Projection"];
            effectViewportScaleParameter = parameters["ViewportScale"];
            effectTimeParameter          = parameters["CurrentTime"];

            // Set the values of parameters that do not change.
            parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds);
            parameters["DurationRandomness"].SetValue(settings.DurationRandomness);
            parameters["Gravity"].SetValue(settings.Gravity);
            parameters["EndVelocity"].SetValue(settings.EndVelocity);
            parameters["MinColor"].SetValue(settings.MinColor.ToVector4());
            parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4());

            parameters["RotateSpeed"].SetValue(new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed));
            parameters["StartSize"].SetValue(new Vector2(settings.MinStartSize, settings.MaxStartSize));
            parameters["EndSize"].SetValue(new Vector2(settings.MinEndSize, settings.MaxEndSize));

            // Load the particle texture, and set it onto the effect.
            Texture2D texture = content.Load <Texture2D>(settings.TextureName);

            parameters["Texture"].SetValue(texture);
        }
Ejemplo n.º 34
0
        private async void AddFloatParameter_OnClick(object sender, RoutedEventArgs e)
        {
            var id = await WindowManager.ShowInputDialog("New Float Effect Parameter", "float parameter id", "float-id");

            if (string.IsNullOrWhiteSpace(id))
            {
                return;
            }

            if (_params.ContainsKey(id))
            {
                NotificationManager.PublishErrorNotification("failed to add parameter, parameter id already exists");
                return;
            }

            var param = new EffectParameter {
                Key = id.Replace(" ", "-")
            };

            param.Json = $@"{{
    ""id"":""{id}"",
    ""type"": ""float"",
    ""initial-value"":0,
    ""uniform"": ""{param.Uniform}""
}}";
            param.Lang = $@"""{id}"": {{
    ""name"": ""{param.Uniform}"",
    ""desc"": ""{param.Uniform}""
}}";
            param.VariableDeclaration = $"uniform lowp float {param.Uniform};";

            _params.Add(id, param);
            ParameterListBox.Items.Refresh();
            ParameterListBox.SelectedIndex = _params.Count - 1;

            AddonManager.CurrentAddon.Effect.Parameters = _params;
        }
Ejemplo n.º 35
0
        public WindowsSceneEffect(ContentManager content)
        {
            _basicEffect         = content.Load <Effect>(ResourceNames.Effects.BasicEffect);
            PostProcessingEffect = content.Load <Effect>(ResourceNames.Effects.PostProcessing);

            _shadowCasterTechnique            = _basicEffect.Techniques["ShadowCaster"];
            _shadowCasterTransparentTechnique = _basicEffect.Techniques["ShadowCasterTransparent"];
            ShadowMapDebugEffect = content.Load <Effect>(ResourceNames.Effects.DebugShadowMap);

            _effectsByLightingFlags = new Dictionary <int, EffectTechnique>()
            {
                { LightTechniqueFlag.Lit | LightTechniqueFlag.ReceiveShadows, _basicEffect.Techniques["LitNoTextureShadowReceiver"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.ReceiveShadows | LightTechniqueFlag.SoftShadows, _basicEffect.Techniques["LitNoTextureShadowReceiverPCF"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture, _basicEffect.Techniques["Lit"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture | LightTechniqueFlag.ReceiveShadows, _basicEffect.Techniques["LitShadowReceiver"] },
                { LightTechniqueFlag.Lit | LightTechniqueFlag.UseTexture | LightTechniqueFlag.ReceiveShadows | LightTechniqueFlag.SoftShadows, _basicEffect.Techniques["LitShadowReceiverPCF"] },
                { 0, _basicEffect.Techniques["UnlitNoTexture"] },
                { LightTechniqueFlag.UseTexture, _basicEffect.Techniques["Unlit"] },
                { LightTechniqueFlag.UseTexture | LightTechniqueFlag.LinearTextureSampling, _basicEffect.Techniques["UnlitLinearSampled"] },
            };

            _lightViewProjection = _basicEffect.Parameters["LightViewProjection"];
            _world            = _basicEffect.Parameters["World"];
            _worldLight       = _basicEffect.Parameters["WorldLight"];
            _view             = _basicEffect.Parameters["View"];
            _projection       = _basicEffect.Parameters["Projection"];
            _lightDirection   = _basicEffect.Parameters["LightDirection"];
            _shadowMap        = _basicEffect.Parameters["ShadowMap"];
            _diffuseTexture   = _basicEffect.Parameters["DiffuseTexture"];
            _texcoordOffset   = _basicEffect.Parameters["TexcoordOffset"];
            _texcoordScale    = _basicEffect.Parameters["TexcoordScale"];
            _ambientLight     = _basicEffect.Parameters["AmbientLight"];
            _ambientIntensity = _basicEffect.Parameters["AmbientIntensity"];
            _diffuseIntensity = _basicEffect.Parameters["DiffuseIntensity"];
            _shadowScale      = _basicEffect.Parameters["ShadowScale"];
            _materialColor    = _basicEffect.Parameters["MaterialColor"];
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Draws several copies of a piece of geometry without using any
        /// special GPU instancing techniques at all. This just does a
        /// regular loop and issues several draw calls one after another.
        /// </summary>
        void DrawModelNoInstancing(Model model, Matrix[] modelBones,
                                   Matrix[] instances, Matrix view, Matrix projection)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                {
                    GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer, meshPart.VertexOffset);
                    GraphicsDevice.Indices = meshPart.IndexBuffer;

                    // Set up the rendering effect.
                    Effect effect = meshPart.Effect;

                    effect.CurrentTechnique = effect.Techniques["NoInstancing"];

                    effect.Parameters["View"].SetValue(view);
                    effect.Parameters["Projection"].SetValue(projection);

                    EffectParameter transformParameter = effect.Parameters["World"];

                    // Draw a single instance copy each time around this loop.
                    for (int i = 0; i < instances.Length; i++)
                    {
                        transformParameter.SetValue(modelBones[mesh.ParentBone.Index] * instances[i]);

                        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                        {
                            pass.Apply();

                            GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                                 meshPart.NumVertices, meshPart.StartIndex,
                                                                 meshPart.PrimitiveCount);
                        }
                    }
                }
            }
        }
Ejemplo n.º 37
0
        private void ExtractParameters()
        {
            _worldParameter               = _effect.Parameters["World"];
            _viewParameter                = _effect.Parameters["View"];
            _projectionParameter          = _effect.Parameters["Projection"];
            _worldViewParameter           = _effect.Parameters["WorldView"];
            _worldViewProjectionParameter = _effect.Parameters["WorldViewProjection"];

            _textureMatrixParameter        = _effect.Parameters["TextureMatrix"];
            _lightViewProjParameter        = _effect.Parameters["LightViewProj"];
            _farClipParameter              = _effect.Parameters["FarClip"];
            _lightBufferPixelSizeParameter = _effect.Parameters["LightBufferPixelSize"];

            _bonesParameter               = _effect.Parameters["Bones"];
            _normalBufferParameter        = _effect.Parameters["NormalBuffer"];
            _lightBufferParameter         = _effect.Parameters["LightBuffer"];
            _lightSpecularBufferParameter = _effect.Parameters["LightSpecularBuffer"];

            _depthBufferParameter = _effect.Parameters["DepthBuffer"];
            _colorBufferParameter = _effect.Parameters["ColorBuffer"];

            _ambientParameter        = _effect.Parameters["AmbientColor"];
            _ambientCubemapParameter = _effect.Parameters["AmbientCubeMap"];

            _totalTimeParameter = _effect.Parameters["TotalTime"];

            _diffuseParameter = _effect.Parameters["DiffuseMap"];
            if (_diffuseParameter == null)
            {
                _diffuseParameter = _effect.Parameters["Diffuse"];
            }

            if (_textureMatrixParameter != null)
            {
                _textureMatrixParameter.SetValue(Matrix.Identity);
            }
        }
Ejemplo n.º 38
0
    public LensFlareRenderer(IGraphicsService graphicsService)
    {
      if (graphicsService == null)
        throw new ArgumentNullException("graphicsService");

      Order = 4;

      var graphicsDevice = graphicsService.GraphicsDevice;
      _basicEffect = new BasicEffect(graphicsDevice)
      {
        FogEnabled = false,
        LightingEnabled = false,
        TextureEnabled = false,
        VertexColorEnabled = true,
      };
      _queryGeometry = new VertexPositionColor[4];

      _spriteBatch = graphicsService.GetSpriteBatch();

      if (graphicsDevice.GraphicsProfile == GraphicsProfile.HiDef)
      {
        // Use custom effect with sRGB reads in pixel shader.
        try
        {
          _effect = graphicsService.Content.Load<Effect>("DigitalRune/SpriteEffect");
          _transformParameter = _effect.Parameters["Transform"];
          _techniqueLinear = _effect.Techniques["Sprite"];
          _techniqueGamma = _effect.Techniques["SpriteWithGamma"];
        }
        catch (ContentLoadException)
        {
          // If we cannot load the HiDef effect, fall back to Reach. This happens in the Linux
          // build when it runs in Windows.
          _effect = null;
        }
      }
    }
Ejemplo n.º 39
0
        /// <summary>
        /// Example 1.3
        /// This function obtains EffectParameter objects from the Effect objects.
        /// The EffectParameters are handles to the values in the shaders and are
        /// effectively how your C# code and your shader code communicate.
        /// </summary>
        private void GetEffectParameters()
        {
            //These parameters are used by both vertexLightingEffect and
            //noLightingEffect, so we must take care to look up the correct ones.
            if (enableAdvancedEffect)
            {
                worldParameter      = vertexLightingEffect.Parameters["world"];
                viewParameter       = vertexLightingEffect.Parameters["view"];
                projectionParameter = vertexLightingEffect.Parameters["projection"];
            }
            else
            {
                worldParameter      = noLightingEffect.Parameters["world"];
                viewParameter       = noLightingEffect.Parameters["view"];
                projectionParameter = noLightingEffect.Parameters["projection"];
            }


            //These effect parameters are only used by vertexLightingEffect
            //to indicate the lights' colors and direction
            lightColorParameter     = vertexLightingEffect.Parameters["lightColor"];
            lightDirectionParameter = vertexLightingEffect.Parameters["lightDirection"];
            ambientColorParameter   = vertexLightingEffect.Parameters["ambientColor"];
        }
Ejemplo n.º 40
0
        public WaterReflectionEffect() : base()
        {
            CurrentTechnique = Techniques["WaterReflectionTechnique"];

            _timeParam                           = Parameters["_time"];
            _sparkleIntensityParam               = Parameters["_sparkleIntensity"];
            _sparkleColorParam                   = Parameters["_sparkleColor"];
            _screenSpaceVerticalOffsetParam      = Parameters["_screenSpaceVerticalOffset"];
            _perspectiveCorrectionIntensityParam = Parameters["_perspectiveCorrectionIntensity"];
            _firstDisplacementSpeedParam         = Parameters["_firstDisplacementSpeed"];
            _secondDisplacementSpeedParam        = Parameters["_secondDisplacementSpeed"];
            _secondDisplacementScaleParam        = Parameters["_secondDisplacementScale"];

            _sparkleIntensityParam.SetValue(_sparkleIntensity);
            _sparkleColorParam.SetValue(Vector3.One);
            _perspectiveCorrectionIntensityParam.SetValue(_perspectiveCorrectionIntensity);
            FirstDisplacementSpeed  = _firstDisplacementSpeed;
            SecondDisplacementSpeed = _secondDisplacementSpeed;
            _secondDisplacementScaleParam.SetValue(_secondDisplacementScale);

            // override some defaults from the ReflectionEffect
            ReflectionIntensity = _reflectionIntensity;
            NormalMagnitude     = _normalMagnitude;
        }
Ejemplo n.º 41
0
        protected override void PrepareParams()
        {
            base.PrepareParams();

            //fixed parameters
            pProjection = Parameters["Projection"];
            pTileSize   = Parameters["TileSize"];

            //change between rendering light passes
            pRoomTarget    = Parameters["RoomTarget"];
            pRoomUVRescale = Parameters["RoomUVRescale"];
            pRoomUVOff     = Parameters["RoomUVOff"];

            pLightPosition  = Parameters["LightPosition"];
            pLightColor     = Parameters["LightColor"];
            pLightSize      = Parameters["LightSize"];
            pLightPower     = Parameters["LightPower"];
            pLightIntensity = Parameters["LightIntensity"];
            pTargetRoom     = Parameters["TargetRoom"];
            pBlurMax        = Parameters["BlurMax"];
            pBlurMin        = Parameters["BlurMin"];
            pMapLayout      = Parameters["MapLayout"];
            pUVBase         = Parameters["UVBase"];

            pLightDirection = Parameters["LightDirection"];
            pLightHeight    = Parameters["LightHeight"];

            pShadowPowers = Parameters["ShadowPowers"];
            pSSAASize     = Parameters["SSAASize"];

            pIsOutdoors = Parameters["IsOutdoors"];

            proomMap        = Parameters["roomMap"];
            pshadowMap      = Parameters["shadowMap"];
            pfloorShadowMap = Parameters["floorShadowMap"];
        }
Ejemplo n.º 42
0
        public override void Initialize()
        {
            base.Initialize();

            part = GameContainer.Content.Load <Model>("Content\\Models\\Player_Part");
            tail = GameContainer.Content.Load <Model>("Content\\Models\\Player_Tail");

            tailTransforms = new Matrix[tail.Bones.Count];
            tail.CopyAbsoluteBoneTransformsTo(tailTransforms);

            velvety = GameContainer.Content.Load <Effect>("Content\\Effects\\Velvety");

            fxWorldInvertedTranspose = velvety.Parameters["WorldITXf"];
            fxWvp          = velvety.Parameters["WvpXf"];
            fxWorld        = velvety.Parameters["WorldXf"];
            fxViewInverted = velvety.Parameters["ViewIXf"];
            fxSubColor     = velvety.Parameters["SubColor"];
            fxDiffColor    = velvety.Parameters["DiffColor"];
            fxSpecColor    = velvety.Parameters["SpecColor"];

            for (int i = 0; i < part.Meshes.Count; i++)
            {
                for (int j = 0; j < part.Meshes[i].MeshParts.Count; j++)
                {
                    part.Meshes[i].MeshParts[j].Effect = velvety;
                }
            }

            for (int i = 0; i < tail.Meshes.Count; i++)
            {
                for (int j = 0; j < tail.Meshes[i].MeshParts.Count; j++)
                {
                    tail.Meshes[i].MeshParts[j].Effect = velvety;
                }
            }
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Get parameters, override to support more
 /// </summary>
 protected virtual void GetParameters()
 {
     worldViewProj = effect.Parameters["worldViewProj"];
     viewProj      = effect.Parameters["viewProj"];
     world         = effect.Parameters["world"];
     viewInverse   = effect.Parameters["viewInverse"];
     projection    = effect.Parameters["projection"];
     lightDir      = effect.Parameters["lightDir"];
     ambientColor  = effect.Parameters["ambientColor"];
     diffuseColor  = effect.Parameters["diffuseColor"];
     specularColor = effect.Parameters["specularColor"];
     specularPower = effect.Parameters["specularPower"];
     alphaFactor   = effect.Parameters["alphaFactor"];
     // Default alpha factor to 1.0f for hotels and stuff
     AlphaFactor           = 1.0f;
     scale                 = effect.Parameters["scale"];
     diffuseTexture        = effect.Parameters["diffuseTexture"];
     normalTexture         = effect.Parameters["normalTexture"];
     heightTexture         = effect.Parameters["heightTexture"];
     reflectionCubeTexture = effect.Parameters["reflectionCubeTexture"];
     detailTexture         = effect.Parameters["detailTexture"];
     parallaxAmount        = effect.Parameters["parallaxAmount"];
     carHueColorChange     = effect.Parameters["carHueColorChange"];
 }
Ejemplo n.º 44
0
        public VisionEffect(Effect effect, SamplerState samplerState = null)
        {
            GraphicsDevice = effect.GraphicsDevice;
            Effect = effect;
            Name = effect.Name;

            _epTextureSampler = effect.Parameters["TextureSampler"];
            if(_epTextureSampler!=null)
                Sampler = samplerState ?? GraphicsDevice.SamplerStates.LinearWrap;

            _epWorld = effect.Parameters["World"];
            _epWorldInverseTranspose = effect.Parameters["WorldInverseTranspose"];
            _epView = effect.Parameters["View"];
            _epProjection = effect.Parameters["Projection"];
            _epCameraPosition = effect.Parameters["CameraPosition"];
            _epClipPlane = effect.Parameters["ClipPlane"];
            _epSunlightDirection = effect.Parameters["SunlightDirection"];
            _epTexture = effect.Parameters["Texture"];
            _epDiffuseColor = effect.Parameters["DiffuseColor"];

            _epDoShadowMapping = effect.Parameters["DoShadowMapping"];
            _epShadowMap = effect.Parameters["ShadowMap"];
            _epShadowViewProjection = effect.Parameters["ShadowViewProjection"];
            _epShadowFarPlane = effect.Parameters["ShadowFarPlane"];
            _epShadowMult = effect.Parameters["ShadowMult"];

            _techStandard = effect.Techniques["TechStandard"];
            _techClipPlane = effect.Techniques["TechClipPlane"];
            _techDepthMap = effect.Techniques["TechDepthMap"];

            //Debug.Assert( _epView != null );
            //Debug.Assert(_techDepthMap != null);

            if ( _epSunlightDirection != null)
                _epSunlightDirection.SetValue(VisionContent.SunlightDirection);
        }
Ejemplo n.º 45
0
        public int effectDispel(SkillParameter skillParameter, EffectParameter effectParameter)
        {
            UnitCtl curUnit = War.scene.GetUnitForUID(effectParameter.curBuildUid);

            if (curUnit == null)
            {
                return(-1);
            }

            if (effectParameter.effect.animPathStart != "temp")
            {
                GameObject effectPrefab = WarRes.GetPrefab(effectParameter.effect.animPathStart.ToLower());
                GameObject effectAnim   = GameObject.Instantiate <GameObject>(effectPrefab);
                effectAnim.transform.position = curUnit.transform.position;
            }
            if (effectParameter.unitCtlList.Count <= 1)
            {
                Debug.Log("==============unitctllist count < 1");
                return(-1);
            }

            War.skillWarManager.StartCoroutine(effectDispelEnd(skillParameter, effectParameter));
            return(0);
        }
Ejemplo n.º 46
0
        protected override void Initialize()
        {
            textureParam = Parameters["Texture"];
            samplerParam = Parameters["TextureSampler"];
            diffuseColorParam = Parameters["DiffuseColor"];
            emissiveColorParam = Parameters["EmissiveColor"];
            specularColorParam = Parameters["SpecularColor"];
            specularPowerParam = Parameters["SpecularPower"];
            eyePositionParam = Parameters["EyePosition"];
            fogColorParam = Parameters["FogColor"];
            fogVectorParam = Parameters["FogVector"];
            worldParam = Parameters["World"];
            worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
            worldViewProjParam = Parameters["WorldViewProj"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          Parameters["DirLight0SpecularColor"], null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          Parameters["DirLight1SpecularColor"], null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          Parameters["DirLight2SpecularColor"], null);

            samplerParam.SetResource(GraphicsDevice.SamplerStates.Default);
        }
Ejemplo n.º 47
0
        protected override void Initialize()
        {
            base.Initialize();

            if (this.Parameters.Contains("blockSampler"))
                this.Parameters["blockSampler"].SetResource(this.GraphicsDevice.SamplerStates.LinearClamp);

            m_perObConstBuf = this.ConstantBuffers["PerObjectBuffer"];
            m_objectWorldMatrixParam = m_perObConstBuf.Parameters["g_chunkOffset"];

            CreateGameColorBuffer();
        }
Ejemplo n.º 48
0
 /// <summary>
 /// Looks up shortcut references to our effect parameters.
 /// </summary>
 void CacheEffectParameters()
 {
     matrixParam = Parameters["MatrixTransform"];
 }
Ejemplo n.º 49
0
 public ConstantBufferLink(EffectConstantBuffer constantBuffer, EffectParameter parameter)
 {
     ConstantBuffer = constantBuffer;
     Parameter = parameter;
     ResourceIndex = 0;
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Looks up shortcut references to our effect parameters.
 /// </summary>
 void CacheEffectParameters()
 {
     textureParam        = Parameters["Texture"];
     diffuseColorParam   = Parameters["DiffuseColor"];
     alphaTestParam      = Parameters["AlphaTest"];
     fogColorParam       = Parameters["FogColor"];
     fogVectorParam      = Parameters["FogVector"];
     worldViewProjParam  = Parameters["WorldViewProj"];
     shaderIndexParam    = Parameters["ShaderIndex"];
 }
Ejemplo n.º 51
0
 protected override void Initialize()
 {
     textureParam = Parameters["Texture"];
     diffuseColorParam = Parameters["DiffuseColor"];
     alphaTestParam = Parameters["AlphaTest"];
     fogColorParam = Parameters["FogColor"];
     fogVectorParam = Parameters["FogVector"];
     worldViewProjParam = Parameters["WorldViewProj"];
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Looks up shortcut references to our effect parameters.
        /// </summary>
        void CacheEffectParameters(EnvironmentMapEffect cloneSource)
        {
            textureParam                = Parameters["Texture"];
            environmentMapParam         = Parameters["EnvironmentMap"];
            environmentMapAmountParam   = Parameters["EnvironmentMapAmount"];
            environmentMapSpecularParam = Parameters["EnvironmentMapSpecular"];
            fresnelFactorParam          = Parameters["FresnelFactor"];
            diffuseColorParam           = Parameters["DiffuseColor"];
            emissiveColorParam          = Parameters["EmissiveColor"];
            eyePositionParam            = Parameters["EyePosition"];
            fogColorParam               = Parameters["FogColor"];
            fogVectorParam              = Parameters["FogVector"];
            worldParam                  = Parameters["World"];
            worldInverseTransposeParam  = Parameters["WorldInverseTranspose"];
            worldViewProjParam          = Parameters["WorldViewProj"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          null,
                                          (cloneSource != null) ? cloneSource.light0 : null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          null,
                                          (cloneSource != null) ? cloneSource.light1 : null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          null,
                                          (cloneSource != null) ? cloneSource.light2 : null);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Looks up shortcut references to our effect parameters.
        /// </summary>
        void CacheEffectParameters(BasicEffect cloneSource)
        {
            textureParam                = Parameters["Texture"];
            diffuseColorParam           = Parameters["DiffuseColor"];
            emissiveColorParam          = Parameters["EmissiveColor"];
            specularColorParam          = Parameters["SpecularColor"];
            specularPowerParam          = Parameters["SpecularPower"];
            eyePositionParam            = Parameters["EyePosition"];
            fogColorParam               = Parameters["FogColor"];
            fogVectorParam              = Parameters["FogVector"];
            worldParam                  = Parameters["World"];
            worldInverseTransposeParam  = Parameters["WorldInverseTranspose"];
            worldViewProjParam          = Parameters["WorldViewProj"];
            shaderIndexParam            = Parameters["ShaderIndex"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          Parameters["DirLight0SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light0 : null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          Parameters["DirLight1SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light1 : null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          Parameters["DirLight2SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light2 : null);
        }
Ejemplo n.º 54
0
 public ParameterBinding(EffectParameter parameter, int slot)
 {
     Parameter = parameter;
     Slot = slot;
 }
Ejemplo n.º 55
0
        ///// <summary>
        ///// Creates a new DualTextureEffect by cloning parameter settings from an existing instance.
        ///// </summary>
        //protected DualTextureEffect(DualTextureEffect cloneSource)
        //    : base(cloneSource)
        //{
        //    CacheEffectParameters();

        //    fogEnabled = cloneSource.fogEnabled;
        //    vertexColorEnabled = cloneSource.vertexColorEnabled;

        //    world = cloneSource.world;
        //    view = cloneSource.view;
        //    projection = cloneSource.projection;

        //    diffuseColor = cloneSource.diffuseColor;

        //    alpha = cloneSource.alpha;

        //    fogStart = cloneSource.fogStart;
        //    fogEnd = cloneSource.fogEnd;
        //}


        ///// <summary>
        ///// Creates a clone of the current DualTextureEffect instance.
        ///// </summary>
        //public override Effect Clone()
        //{
        //    return new DualTextureEffect(this);
        //}


        /// <summary>
        /// Looks up shortcut references to our effect parameters.
        /// </summary>
        void CacheEffectParameters()
        {
            textureParam = Parameters["Texture"];
            texture2Param = Parameters["Texture2"];
            diffuseColorParam = Parameters["DiffuseColor"];
            fogColorParam = Parameters["FogColor"];
            fogVectorParam = Parameters["FogVector"];
            worldViewProjParam = Parameters["WorldViewProj"];
        }
Ejemplo n.º 56
0
        protected override void Initialize()
        {
            textureParam = Parameters["Texture"];
            diffuseColorParam = Parameters["DiffuseColor"];
            emissiveColorParam = Parameters["EmissiveColor"];
            specularColorParam = Parameters["SpecularColor"];
            specularPowerParam = Parameters["SpecularPower"];
            eyePositionParam = Parameters["EyePosition"];
            fogColorParam = Parameters["FogColor"];
            fogVectorParam = Parameters["FogVector"];
            worldParam = Parameters["World"];
            worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
            worldViewProjParam = Parameters["WorldViewProj"];
            bonesParam = Parameters["Bones"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          Parameters["DirLight0SpecularColor"],
                                          null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          Parameters["DirLight1SpecularColor"],
                                          null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          Parameters["DirLight2SpecularColor"],
                                          null);
        }
Ejemplo n.º 57
0
        private void buildFx(InitInfo initInfo)
        {
            var p = Effect.Effect.Parameters;

            p["MirrorSampler"].SetResource(Effect.GraphicsDevice.SamplerStates.PointMirror);

            _mhWorldInv = p["WorldInv"];
            _mhCameraPosition = p["CameraPosition"];
            _mhWaveBumpMapOffset0 = p["WaveNMapOffset0"];
            _mhWaveBumpMapOffset1 = p["WaveNMapOffset1"];
            _mhWaveDispMapOffset0 = p["WaveDMapOffset0"];
            _mhWaveDispMapOffset1 = p["WaveDMapOffset1"];
            _reflectedView = p["ReflectedView"];
            _reflectedMap = p["ReflectedMap"];

            p["BumpMap0"].SetResource(initInfo.waveMap0);
            p["BumpMap1"].SetResource(initInfo.waveMap1);

            p["WaveDispMap0"].SetResource(initInfo.dmap0);
            p["WaveDispMap1"].SetResource(initInfo.dmap1);
            p["ScaleHeights"].SetValue(initInfo.scaleHeights);
            p["GridStepSizeL"].SetValue(new Vector2(initInfo.dx, initInfo.dz));
            p["WaveHeight"].SetValue(0.3f * 2);
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Sets a vector which can be dotted with the object space vertex position to compute fog amount.
        /// </summary>
        static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam)
        {
            if (fogStart == fogEnd)
            {
                // Degenerate case: force everything to 100% fogged if start and end are the same.
                fogVectorParam.SetValue(new Vector4(0, 0, 0, 1));
            }
            else
            {
                // We want to transform vertex positions into view space, take the resulting
                // Z value, then scale and offset according to the fog start/end distances.
                // Because we only care about the Z component, the shader can do all this
                // with a single dot product, using only the Z row of the world+view matrix.
                
                float scale = 1f / (fogStart - fogEnd);

                var fogVector = new Vector4(worldView.M13 * scale, worldView.M23 * scale, worldView.M33 * scale, (worldView.M43 + fogStart) * scale);

                fogVectorParam.SetValue(fogVector);
            }
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Initializes the stage block.
        /// </summary>
        /// <param name="stageBlock">The stage block.</param>
        /// <param name="logger">The logger.</param>
        private void InitStageBlock(StageBlock stageBlock, Logger logger)
        {
            // If null shader, then skip init
            if (stageBlock.Index < 0)
            {
                return;
            }

            stageBlock.Shader = Effect.Pool.GetOrCompileShader(stageBlock.Type, stageBlock.Index);
            var shaderRaw = Effect.Pool.EffectData.Shaders[stageBlock.Index];

            // Cache the input signature
            if (shaderRaw.Type == EffectShaderType.Vertex)
            {
                inputSignatureManager = graphicsDevice.GetOrCreateInputSignatureManager(shaderRaw.InputSignature.Bytecode, shaderRaw.InputSignature.Hashcode);
            }

            for (int i = 0; i < shaderRaw.ConstantBuffers.Count; i++)
            {
                var constantBufferRaw = shaderRaw.ConstantBuffers[i];

                // Constant buffers with a null size are skipped
                if (constantBufferRaw.Size == 0)
                    continue;

                var constantBuffer = Effect.GetOrCreateConstantBuffer(Effect.GraphicsDevice, constantBufferRaw);
                // IF constant buffer is null, it means that there is a conflict
                if (constantBuffer == null)
                {
                    logger.Error("Constant buffer [{0}] cannot have multiple size or different content declaration inside the same effect pool", constantBufferRaw.Name);
                    continue;
                }
                
                // Test if this constant buffer is not already part of the effect
                if (Effect.ConstantBuffers[constantBufferRaw.Name] == null)
                {
                    // Add the declared constant buffer to the effect shader.
                    Effect.ConstantBuffers.Add(constantBuffer);

                    // Declare all parameter from constant buffer at the effect level.
                    foreach (var parameter in constantBuffer.Parameters)
                    {
                        var previousParameter = Effect.Parameters[parameter.Name];
                        if (previousParameter == null)
                        {
                            // Add an effect parameter linked to the approriate constant buffer at the effect level.
                            Effect.Parameters.Add(new EffectParameter((EffectData.ValueTypeParameter) parameter.ParameterDescription, constantBuffer));
                        }
                        else if (parameter.ParameterDescription != previousParameter.ParameterDescription || parameter.buffer != previousParameter.buffer)
                        {
                            // If registered parameters is different
                            logger.Error("Parameter [{0}] defined in Constant buffer [{0}] is already defined by another constant buffer with the definition [{2}]", parameter, constantBuffer.Name, previousParameter);
                        }
                    }
                }
            }

            var constantBufferLinks = new List<ConstantBufferLink>();

            // Declare all resource parameters at the effect level.
            foreach (var parameterRaw in shaderRaw.ResourceParameters)
            {
                EffectParameter parameter;
                var previousParameter = Effect.Parameters[parameterRaw.Name];

                // Skip enmpty constant buffers.
                if (parameterRaw.Type == EffectParameterType.ConstantBuffer && Effect.ConstantBuffers[parameterRaw.Name] == null)
                {
                    continue;
                }

                int resourceIndex = Effect.ResourceLinker.Count;

                if (previousParameter == null)
                {
                    parameter = new EffectParameter(parameterRaw, EffectResourceTypeHelper.ConvertFromParameterType(parameterRaw.Type), Effect.ResourceLinker.Count, Effect.ResourceLinker);
                    Effect.Parameters.Add(parameter);

                    Effect.ResourceLinker.Count += parameterRaw.Count;
                }
                else
                {
                    resourceIndex = ((EffectData.ResourceParameter) previousParameter.ParameterDescription).Slot;

                    if (CompareResourceParameter(parameterRaw, (EffectData.ResourceParameter) previousParameter.ParameterDescription))
                    {
                        // If registered parameters is different
                        logger.Error("Resource Parameter [{0}] is already defined with a different definition [{1}]", parameterRaw, previousParameter.ParameterDescription);
                    }
                    parameter = previousParameter;
                }

                // For constant buffers, we need to store explicit link
                if (parameter.ResourceType == EffectResourceType.ConstantBuffer)
                {
                    constantBufferLinks.Add(new ConstantBufferLink(Effect.ConstantBuffers[parameter.Name], parameter));
                }

                if (stageBlock.Parameters == null)
                {
                     stageBlock.Parameters = new List<EffectParameter>();
                }

                stageBlock.Parameters.Add(parameter);
            }

            stageBlock.ConstantBufferLinks = constantBufferLinks.ToArray();
        }
Ejemplo n.º 60
0
 /// <summary>
 /// Sets the diffuse/emissive/alpha material color parameters.
 /// </summary>
 internal static void SetMaterialColor(bool lightingEnabled, float alpha,
                                       ref Vector4 diffuseColor, ref Vector3 emissiveColor, ref Vector3 ambientLightColor,
                                       EffectParameter diffuseColorParam, EffectParameter emissiveColorParam)
 {
     // Desired lighting model:
     //
     //     ((AmbientLightColor + sum(diffuse directional light)) * DiffuseColor) + EmissiveColor
     //
     // When lighting is disabled, ambient and directional lights are ignored, leaving:
     //
     //     DiffuseColor + EmissiveColor
     //
     // For the lighting disabled case, we can save one shader instruction by precomputing
     // diffuse+emissive on the CPU, after which the shader can use DiffuseColor directly,
     // ignoring its emissive parameter.
     //
     // When lighting is enabled, we can merge the ambient and emissive settings. If we
     // set our emissive parameter to emissive+(ambient*diffuse), the shader no longer
     // needs to bother adding the ambient contribution, simplifying its computation to:
     //
     //     (sum(diffuse directional light) * DiffuseColor) + EmissiveColor
     //
     // For further optimization goodness, we merge material alpha with the diffuse
     // color parameter, and premultiply all color values by this alpha.
     
     if (lightingEnabled)
     {
         var diffuse = new Vector4(diffuseColor.X * alpha, diffuseColor.Y * alpha, diffuseColor.Z * alpha, alpha);
         var emissive = new Vector3(
                                (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha,
                                (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha,
                                (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha
                            );
         diffuseColorParam.SetValue(diffuse);
         emissiveColorParam.SetValue(emissive);
     }
     else
     {
         var diffuse = new Vector4((diffuseColor.X + emissiveColor.X) * alpha, (diffuseColor.Y + emissiveColor.Y) * alpha, (diffuseColor.Z + emissiveColor.Z) * alpha, alpha);
         diffuseColorParam.SetValue(diffuse);
     }
 }