Example #1
0
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="EdgeFilter"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public EdgeFilter(IGraphicsService graphicsService)
            : base(graphicsService)
        {
            _effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/EdgeFilter");
              _parameterViewportSize = _effect.Parameters["ViewportSize"];
              _parameterHalfEdgeWidth = _effect.Parameters["HalfEdgeWidth"];
              _parameterDepthThreshold = _effect.Parameters["DepthThreshold"];
              _parameterDepthSensitivity = _effect.Parameters["DepthSensitivity"];
              _parameterNormalThreshold = _effect.Parameters["NormalThreshold"];
              _parameterNormalSensitivity = _effect.Parameters["NormalSensitivity"];
              _parameterCameraBackward = _effect.Parameters["CameraBackward"];
              _parameterSourceTexture = _effect.Parameters["SourceTexture"];
              _parameterSilhouetteColor = _effect.Parameters["SilhouetteColor"];
              _parameterCreaseColor = _effect.Parameters["CreaseColor"];
              _parameterGBuffer0 = _effect.Parameters["GBuffer0"];
              _parameterGBuffer1 = _effect.Parameters["GBuffer1"];
              _passEdge = _effect.Techniques[0].Passes["Edge"];
              _passOnePixelEdge = _effect.Techniques[0].Passes["OnePixelEdge"];

              EdgeWidth = 2.0f;
              DepthThreshold = 0.001f;  // = minDistance / farPlaneDistance
              DepthSensitivity = 1000;  // = farPlaneDistance / (maxDistance - minDistance)
              NormalThreshold = 0.1f;
              NormalSensitivity = 2f;
              SilhouetteColor = new Vector4F(0, 0, 0, 1);
              CreaseColor = new Vector4F(0, 0, 0, 1);
        }
        public InstancedModelDrawer(Game game)
            : base(game)
        {
#if WINDOWS
            var resourceContentManager = new ResourceContentManager(game.Services, Indiefreaks.Xna.BEPU.Resources.WindowsPhysicsResources.ResourceManager);
#elif XBOX360
            var resourceContentManager = new ResourceContentManager(game.Services, Indiefreaks.Xna.BEPU.Resources.Xbox360PhysicsResources.ResourceManager);
#else
            ResourceContentManager resourceContentManager = null;
#endif
            instancingEffect = resourceContentManager.Load<Effect>("InstancedEffect");

            worldTransformsParameter = instancingEffect.Parameters["WorldTransforms"];
            textureIndicesParameter = instancingEffect.Parameters["TextureIndices"];
            viewParameter = instancingEffect.Parameters["View"];
            projectionParameter = instancingEffect.Parameters["Projection"];

            instancingEffect.Parameters["LightDirection1"].SetValue(Vector3.Normalize(new Vector3(.8f, -1.5f, -1.2f)));
            instancingEffect.Parameters["DiffuseColor1"].SetValue(new Vector3(.66f, .66f, .66f));
            instancingEffect.Parameters["LightDirection2"].SetValue(Vector3.Normalize(new Vector3(-.8f, 1.5f, 1.2f)));
            instancingEffect.Parameters["DiffuseColor2"].SetValue(new Vector3(.3f, .3f, .5f));
            instancingEffect.Parameters["AmbientAmount"].SetValue(.5f);

            instancingEffect.Parameters["Texture0"].SetValue(textures[0]);
            instancingEffect.Parameters["Texture1"].SetValue(textures[1]);
            instancingEffect.Parameters["Texture2"].SetValue(textures[2]);
            instancingEffect.Parameters["Texture3"].SetValue(textures[3]);
            instancingEffect.Parameters["Texture4"].SetValue(textures[4]);
            instancingEffect.Parameters["Texture5"].SetValue(textures[5]);
            instancingEffect.Parameters["Texture6"].SetValue(textures[6]);
            instancingEffect.Parameters["Texture7"].SetValue(textures[7]);

            //This vertex declaration could be compressed or made more efficient, but such optimizations weren't critical.
            instancingVertexDeclaration = new VertexDeclaration(new[] {new VertexElement(0, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1)});
        }
        public InstancedModelDrawer(Game game)
            : base(game)
        {
            var resourceContentManager = new ResourceContentManager(game.Services, DrawerResource.ResourceManager);
#if WINDOWS
            instancingEffect = resourceContentManager.Load<Effect>("InstancedEffect");
#else
            instancingEffect = resourceContentManager.Load<Effect>("InstancedEffectXbox");
#endif
            //instancingEffect = game.Content.Load<Effect>("InstancedEffect");

            worldTransformsParameter = instancingEffect.Parameters["WorldTransforms"];
            textureIndicesParameter = instancingEffect.Parameters["TextureIndices"];
            viewParameter = instancingEffect.Parameters["View"];
            projectionParameter = instancingEffect.Parameters["Projection"];

            instancingEffect.Parameters["LightDirection1"].SetValue(Vector3.Normalize(new Vector3(.8f, -1.5f, -1.2f)));
            instancingEffect.Parameters["DiffuseColor1"].SetValue(new Vector3(.66f, .66f, .66f));
            instancingEffect.Parameters["LightDirection2"].SetValue(Vector3.Normalize(new Vector3(-.8f, 1.5f, 1.2f)));
            instancingEffect.Parameters["DiffuseColor2"].SetValue(new Vector3(.3f, .3f, .5f));
            instancingEffect.Parameters["AmbientAmount"].SetValue(.5f);

            instancingEffect.Parameters["Colors"].SetValue(colors);

        }
Example #4
0
        protected override void OnInit()
        {
            base.OnInit();

            depthParam = effect.Parameters["Depth"];
            centerParam = effect.Parameters["Center"];
        }
        public ScatteringSkyRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              if (graphicsService.GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach)
            throw new NotSupportedException("The ScatteringSkyRenderer does not support the Reach profile.");

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Sky/ScatteringSky");
              _parameterView = _effect.Parameters["View"];
              _parameterProjection = _effect.Parameters["Projection"];
              _parameterSunDirection = _effect.Parameters["SunDirection"];
              _parameterRadii = _effect.Parameters["Radii"];
              _parameterNumberOfSamples = _effect.Parameters["NumberOfSamples"];
              _parameterBetaRayleigh = _effect.Parameters["BetaRayleigh"];
              _parameterBetaMie = _effect.Parameters["BetaMie"];
              _parameterGMie = _effect.Parameters["GMie"];
              _parameterSunIntensity = _effect.Parameters["SunIntensity"];
              _parameterTransmittance = _effect.Parameters["Transmittance"];
              _parameterBaseHorizonColor = _effect.Parameters["BaseHorizonColor"];
              _parameterBaseZenithColor = _effect.Parameters["BaseZenithColor"];
              _passLinear = _effect.Techniques[0].Passes["Linear"];
              _passGamma = _effect.Techniques[0].Passes["Gamma"];
              _passLinearWithBaseColor = _effect.Techniques[0].Passes["LinearWithBaseColor"];
              _passGammaWithBaseColor = _effect.Techniques[0].Passes["GammaWithBaseColor"];

              _submesh = MeshHelper.GetBox(graphicsService);
        }
        public Lighting(World world)
        {
            this.world = world;

            pSunColor = Shaders.Common.Parameters["vSunColor"];
            pSunVector = Shaders.Common.Parameters["vSunVector"];
            pAmbientColor = Shaders.Common.Parameters["vAmbientColor"];
            pAmbientLight = Shaders.Common.Parameters["fAmbient"];
            pNumberOfLights = Shaders.Common.Parameters["iNumLights"];
            pSunIntensity = Shaders.Common.Parameters["fSunIntensity"];
            pFogColor = Shaders.Common.Parameters["vFogColor"];

            //Shaders.Common.Parameters["tCloudShadowMap"].SetValue(world.Game.Content.Load<Texture2D>(@"textures\sky\clouds"));

            Random r = new Random();
            if (lights[0] == null)
            {
                for (int i = 0; i < lights.Length; i++)
                {
                    Vector3 color = new Vector3(r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f);
                    lights[i] = new PointLight(Vector3.Zero, color, Shaders.Common.Parameters["lights"].Elements[i]);
                }
            }

            // setup the shadowmap render target
            GraphicsDevice g = world.GraphicsDevice;
            PresentationParameters pp = world.GraphicsDevice.PresentationParameters;
            int shadowWidth = pp.BackBufferWidth;
            int shadowHeight = pp.BackBufferHeight;

            smapTarget = new RenderTarget2D(g, shadowWidth, shadowHeight, 1, SurfaceFormat.Single);
            smapStencilBuffer = new DepthStencilBuffer(g, shadowWidth, shadowHeight, g.DepthStencilBuffer.Format);
        }
Example #7
0
        public WheelMenu( MenuScreen screen, Camera camera, float wheelScale, 
            float screenScale, float startX, float activeX, float finishX, float y)
            : base(screen, Vector2.Zero)
        {
            this.wheelScale = wheelScale;
              scaleMatrix = Matrix.CreateScale( wheelScale );
              this.camera = camera;
              angle = MathHelper.PiOver4;

              TransitionOnPosition = new Vector2( startX, y );
              Position = new Vector2( activeX, y );
              TransitionOffPosition = new Vector2( finishX, y );

              rotateSpring = new SpringInterpolater( 1, 50, SpringInterpolater.GetCriticalDamping( 50 ) );

              lastX = startX;

              ContentManager content = screen.ScreenManager.Game.Content;

              entryEffect = content.Load<Effect>( "Effects/basic" ).Clone( Screen.ScreenManager.GraphicsDevice );
              entryEffect.CurrentTechnique = entryEffect.Techniques["DiffuseColor"];
              entryEffect.Parameters["LightingEnabled"].SetValue( false );
              entryWorldEffectParameter = entryEffect.Parameters["World"];
              entryViewEffectParameter = entryEffect.Parameters["View"];
              entryProjectionEffectParameter = entryEffect.Parameters["Projection"];
              entryDiffuseEffectParameter = entryEffect.Parameters["DiffuseMap"];

              wheelModel = content.Load<CustomModel>( "Models/hamsterWheel" );
              foreach ( CustomModel.ModelPart part in wheelModel.ModelParts )
              {
            part.Effect.CurrentTechnique = part.Effect.Techniques["Color"];
            part.Effect.Parameters["Color"].SetValue( new Color( Color.LightGray, 0 ).ToVector4() );
              }
        }
Example #8
0
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="DepthOfFieldFilter"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public DepthOfFieldFilter(IGraphicsService graphicsService)
            : base(graphicsService)
        {
            _effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/DepthOfFieldFilter");
              _screenSizeParameter = _effect.Parameters["ScreenSize"];
              _depthTextureParameter = _effect.Parameters["DepthTexture"];
              _nearBlurDistanceParameter = _effect.Parameters["NearBlurDistance"];
              _nearFocusDistanceParameter = _effect.Parameters["NearFocusDistance"];
              _farFocusDistanceParameter = _effect.Parameters["FarFocusDistance"];
              _farBlurDistanceParameter = _effect.Parameters["FarBlurDistance"];
              _farParameter = _effect.Parameters["Far"];
              _blurTextureParameter = _effect.Parameters["BlurTexture"];
              _downsampledDepthTextureParameter = _effect.Parameters["DownsampledDepthTexture"];
              _downsampledCocTextureParameter = _effect.Parameters["DownsampledCocTexture"];
              _offsetsParameter = _effect.Parameters["Offsets"];
              _weightsParameter = _effect.Parameters["Weights"];
              _sceneTextureParameter = _effect.Parameters["SceneTexture"];
              _circleOfConfusionPass = _effect.CurrentTechnique.Passes["CircleOfConfusion"];
              _blurPass = _effect.CurrentTechnique.Passes["Blur"];
              _depthOfFieldPass = _effect.CurrentTechnique.Passes["DepthOfField"];

              _downsampleFilter = PostProcessHelper.GetDownsampleFilter(graphicsService);

              _cocBlur = new Blur(graphicsService);
              _cocBlur.InitializeBoxBlur(5, false);

              NearBlurDistance = 2;
              NearFocusDistance = 5;
              FarFocusDistance = 6;
              FarBlurDistance = 10;
              _downsampleFactor = 2;
              BlurStrength = 1;
        }
Example #9
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.Translation);

                dirtyFlags &= ~EffectDirtyFlags.EyePosition;
            }

            return dirtyFlags;
        }
Example #10
0
        public InstancedModelDrawer(Game game)
            : base(game)
        {
            instancingEffect = game.Content.Load<Effect>("InstancedEffect");

            worldTransformsParameter = instancingEffect.Parameters["WorldTransforms"];
            textureIndicesParameter = instancingEffect.Parameters["TextureIndices"];
            viewParameter = instancingEffect.Parameters["View"];
            projectionParameter = instancingEffect.Parameters["Projection"];

            instancingEffect.Parameters["LightDirection1"].SetValue(Vector3.Normalize(new Vector3(.8f, -1.5f, -1.2f)));
            instancingEffect.Parameters["DiffuseColor1"].SetValue(new Vector3(.66f, .66f, .66f));
            instancingEffect.Parameters["LightDirection2"].SetValue(Vector3.Normalize(new Vector3(-.8f, 1.5f, 1.2f)));
            instancingEffect.Parameters["DiffuseColor2"].SetValue(new Vector3(.3f, .3f, .5f));
            instancingEffect.Parameters["AmbientAmount"].SetValue(.5f);

            instancingEffect.Parameters["Texture0"].SetValue(textures[0]);
            instancingEffect.Parameters["Texture1"].SetValue(textures[1]);
            instancingEffect.Parameters["Texture2"].SetValue(textures[2]);
            instancingEffect.Parameters["Texture3"].SetValue(textures[3]);
            instancingEffect.Parameters["Texture4"].SetValue(textures[4]);
            instancingEffect.Parameters["Texture5"].SetValue(textures[5]);
            instancingEffect.Parameters["Texture6"].SetValue(textures[6]);
            instancingEffect.Parameters["Texture7"].SetValue(textures[7]);

            //This vertex declaration could be compressed or made more efficient, but such optimizations weren't critical.
            instancingVertexDeclaration = new VertexDeclaration(new[] {new VertexElement(0, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1)});
        }
Example #11
0
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="GodRayFilter"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public GodRayFilter(IGraphicsService graphicsService)
            : base(graphicsService)
        {
            Effect effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/GodRayFilter");
              _viewportSizeParameter = effect.Parameters["ViewportSize"];
              _parameters0Parameter = effect.Parameters["Parameters0"];
              _parameters1Parameter = effect.Parameters["Parameters1"];
              _intensityParameter = effect.Parameters["Intensity"];
              _numberOfSamplesParameter = effect.Parameters["NumberOfSamples"];
              _sourceTextureParameter = effect.Parameters["SourceTexture"];
              _gBuffer0Parameter = effect.Parameters["GBuffer0"];
              _rayTextureParameter = effect.Parameters["RayTexture"];
              _createMaskPass = effect.CurrentTechnique.Passes["CreateMask"];
              _blurPass = effect.CurrentTechnique.Passes["Blur"];
              _combinePass = effect.CurrentTechnique.Passes["Combine"];

              _downsampleFilter = graphicsService.GetDownsampleFilter();

              Scale = 1;
              LightDirection = new Vector3F(0, -1, 0);
              LightRadius = 0.2f;
              Intensity = new Vector3F(1, 1, 1);
              DownsampleFactor = 4;
              NumberOfSamples = 8;
              NumberOfPasses = 2;
              Softness = 1;
        }
Example #12
0
 public DepthMapEffect(Effect cloneSource)
     : base(cloneSource)
 {
     world = Parameters["World"];
     view = Parameters["View"];
     projection = Parameters["Projection"];
 }
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="CubeMapShadowMaskRenderer"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public CubeMapShadowMaskRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Deferred/CubeMapShadowMask");
              _parameterViewInverse = _effect.Parameters["ViewInverse"];
              _parameterFrustumCorners = _effect.Parameters["FrustumCorners"];
              _parameterGBuffer0 = _effect.Parameters["GBuffer0"];
              _parameterParameters0 = _effect.Parameters["Parameters0"];
              _parameterParameters1 = _effect.Parameters["Parameters1"];
              _parameterParameters2 = _effect.Parameters["Parameters2"];
              _parameterLightPosition = _effect.Parameters["LightPosition"];
              _parameterShadowView = _effect.Parameters["ShadowView"];
              _parameterJitterMap = _effect.Parameters["JitterMap"];
              _parameterShadowMap = _effect.Parameters["ShadowMap"];
              _parameterSamples = _effect.Parameters["Samples"];

              Debug.Assert(_parameterSamples.Elements.Count == _samples.Length);

              // TODO: Use struct parameter. Not yet supported in MonoGame.
              // Struct effect parameters are not yet supported in the MonoGame effect processor.
              //var parameterShadow = _effect.Parameters["ShadowParam"];
              //_parameterNear = parameterShadow.StructureMembers["Near"];
              //...
        }
Example #14
0
        public CloudLayerRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              if (graphicsService.GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach)
            throw new NotSupportedException("The CloudLayerRenderer does not support the Reach profile.");

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Sky/CloudLayer");
              _parameterView = _effect.Parameters["View"];
              _parameterProjection = _effect.Parameters["Projection"];
              _parameterSunDirection = _effect.Parameters["SunDirection"];
              _parameterSkyCurvature = _effect.Parameters["SkyCurvature"];
              _parameterTextureMatrix = _effect.Parameters["Matrix0"];
              _parameterNumberOfSamples = _effect.Parameters["NumberOfSamples"];
              _parameterSampleDistance = _effect.Parameters["SampleDistance"];
              _parameterScatterParameters = _effect.Parameters["ScatterParameters"];
              _parameterHorizonFade = _effect.Parameters["HorizonFade"];
              _parameterSunLight = _effect.Parameters["SunLight"];
              _parameterAmbientLight = _effect.Parameters["AmbientLight"];
              _parameterTexture = _effect.Parameters["NoiseTexture0"];
              _passCloudRgbLinear = _effect.Techniques[0].Passes["CloudRgbLinear"];
              _passCloudAlphaLinear = _effect.Techniques[0].Passes["CloudAlphaLinear"];
              _passCloudRgbGamma = _effect.Techniques[0].Passes["CloudRgbGamma"];
              _passCloudAlphaGamma = _effect.Techniques[0].Passes["CloudAlphaGamma"];
              _passOcclusionRgb = _effect.Techniques[0].Passes["OcclusionRgb"];
              _passOcclusionAlpha = _effect.Techniques[0].Passes["OcclusionAlpha"];

              // We render a spherical patch into the sky. But any mesh which covers the top
              // hemisphere works too.
              //_submesh = MeshHelper.CreateSpherePatch(graphicsService.GraphicsDevice, 1, 1.1f, 10);
              _submesh = MeshHelper.CreateBox(graphicsService.GraphicsDevice);

              _queryGeometry = new Vector3F[4];
        }
Example #15
0
        public override void Initialize()
        {
            base.Initialize();

            ball = GameContainer.Content.Load<Model>("Content\\Models\\Ball");

            rubbery = GameContainer.Content.Load<Texture2D>("Content\\Textures\\Rubbery");

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

            fxWorldInvertedTranspose = velvety.Parameters["WorldITXf"];
            fxWvp = velvety.Parameters["WvpXf"];
            fxWorld = velvety.Parameters["WorldXf"];
            fxViewInverted = velvety.Parameters["ViewIXf"];
            fxTexture = velvety.Parameters["ColorTexture"];

            fxSubColor = velvety.Parameters["SubColor"];
            fxDiffColor = velvety.Parameters["DiffColor"];
            fxSpecColor = velvety.Parameters["SpecColor"];

            for (int i = 0; i < ball.Meshes.Count; i++) {
                for (int j = 0; j < ball.Meshes[i].MeshParts.Count; j++) {
                    ball.Meshes[i].MeshParts[j].Effect = velvety;
                }
            }
        }
Example #16
0
        public GdxSpriteBatch(GraphicsDevice graphicsDevice)
        {
            if (graphicsDevice == null)
                throw new ArgumentNullException("graphicsDevice");

            _device = graphicsDevice;

            _spriteEffect = new LocalSpriteEffect(graphicsDevice);
            _matrixTransform = _spriteEffect.Parameters["MatrixTransform"];
            _spritePass = _spriteEffect.CurrentTechnique.Passes[0];

            _transformMatrix = Matrix.Identity;
            //_projectionMatrix = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1);
            _projectionMatrix = XnaExt.Matrix.CreateOrthographic2D(0, 0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, -1, 0);

            Color = Color.White;

            CalculateIndexBuffer();

            _rasterizerScissorState = new RasterizerState() {
                CullMode = CullMode.None,
                ScissorTestEnable = true,
            };

            // projection uses CreateOrthographicOffCenter to create 2d projection
            // matrix with 0,0 in the upper left.
            /*_basicEffect.Projection = Matrix.CreateOrthographicOffCenter
                (0, graphicsDevice.Viewport.Width,
                graphicsDevice.Viewport.Height, 0,
                0, 1);
            this._basicEffect.World = Matrix.Identity;
            this._basicEffect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward,
                Vector3.Up);*/
        }
Example #17
0
        public RenderBatch(GraphicsDevice device, int primitivesPerBatch, bool enableAlphaBlend)
        {
            this.device = device;
            if (enableAlphaBlend)
            {
                BasicEffect be = new BasicEffect(device);
                Effect = be;
                fxMatrices = be;
                be.TextureEnabled = true;
                be.VertexColorEnabled = true;
                be.LightingEnabled = false;
                fxParamTexture = Effect.Parameters["Texture"];
            }
            else
            {
                AlphaTestEffect ate = new AlphaTestEffect(device);
                Effect = ate;
                fxMatrices = ate;
                ate.VertexColorEnabled = true;
                ate.ReferenceAlpha = 128;
                fxParamTexture = Effect.Parameters["Texture"];
            }

            this.maxPrimitivesPerBatch = primitivesPerBatch;
        }
Example #18
0
 public DefaultEffect(Effect effect)
     : base(effect)
 {
     world = Parameters["World"];
     projection = Parameters["Projection"];
     texture = Parameters["DiffuseTexture"];
 }
        protected override void _LoadParameters()
        {
            base._LoadParameters();

            _baseTextureParameter = EffectManager.GetParameter(Effect, "baseTexture");
            Assert.Fatal(_baseTextureParameter != null, "PostProcessMaterial._LoadParameters - Unable to load parameter 'baseTexture'!");
        }
        public GradientTextureSkyRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              if (graphicsService.GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach)
            throw new NotSupportedException("The GradientTextureSkyRenderer does not support the Reach profile.");

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Sky/GradientTextureSky");
              _parameterView = _effect.Parameters["View"];
              _parameterProjection = _effect.Parameters["Projection"];
              _parameterSunDirection = _effect.Parameters["SunDirection"];
              _parameterTime = _effect.Parameters["Time"];
              _parameterColor = _effect.Parameters["Color"];
              _parameterFrontTexture = _effect.Parameters["FrontTexture"];
              _parameterBackTexture = _effect.Parameters["BackTexture"];
              _parameterAbcd = _effect.Parameters["Abcd"];
              _parameterEAndStrength = _effect.Parameters["EAndStrength"];
              _passLinear = _effect.Techniques[0].Passes["Linear"];
              _passGamma = _effect.Techniques[0].Passes["Gamma"];
              _passCieLinear = _effect.Techniques[0].Passes["CieLinear"];
              _passCieGamma = _effect.Techniques[0].Passes["CieGamma"];

              _submesh = MeshHelper.GetBox(graphicsService);
        }
Example #21
0
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="SsaoFilter"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public SaoFilter(IGraphicsService graphicsService)
            : base(graphicsService)
        {
            Effect effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/SaoFilter");
              _frustumInfoParameter = effect.Parameters["FrustumInfo"];
              _numberOfAOSamplesParameter = effect.Parameters["NumberOfAOSamples"];
              _aoParameters0 = effect.Parameters["AOParameters0"];
              _aoParameters1 = effect.Parameters["AOParameters1"];
              _aoParameters2 = effect.Parameters["AOParameters2"];
              _sourceTextureParameter = effect.Parameters["SourceTexture"];
              _occlusionTextureParameter = effect.Parameters["OcclusionTexture"];
              _gBuffer0Parameter = effect.Parameters["GBuffer0"];
              //_viewParameter = _effect.Parameters["View"];
              //_gBuffer1Parameter = _effect.Parameters["GBuffer1"];
              _createAOPass = effect.CurrentTechnique.Passes["CreateAO"];
              _blurHorizontalPass = effect.CurrentTechnique.Passes["BlurHorizontal"];
              _blurVerticalPass = effect.CurrentTechnique.Passes["BlurVertical"];
              _blurVerticalAndCombinePass = effect.CurrentTechnique.Passes["BlurVerticalAndCombine"];

              Strength = 1;
              MaxOcclusion = 1;
              Radius = 0.5f;
              MinBias = 0.02f;
              Bias = 0.0004f;
              NumberOfSamples = 11;
              SampleDistribution = 7;
              BlurScale = 2;
              EdgeSoftness = 0.5f;
              CombineWithSource = true;
        }
Example #22
0
        public Quad( Vector3[] verts, Vector3 position, Texture2D texture )
        {
            if ( verts.Length != 4 )
            throw new InvalidOperationException( "Quad must have four vertices." );
              localPositions = verts;
              vertices = new VertexPositionTexture[4];
              Array.Copy( verts, localPositions, 4 );
              vertices[0].TextureCoordinate = new Vector2( 0, 0 );
              vertices[1].TextureCoordinate = new Vector2( 1, 0 );
              vertices[2].TextureCoordinate = new Vector2( 1, 1 );
              vertices[3].TextureCoordinate = new Vector2( 0, 1 );

              Position = position;
              Scale = 1f;

              device = ZombieCraft.Instance.GraphicsDevice;
              vertexDeclaraion = new VertexDeclaration( device, VertexPositionTexture.VertexElements );
              effect = ZombieCraft.Instance.Content.Load<Effect>( "Effects/Primitive" ).Clone( device );
              effect.CurrentTechnique = effect.Techniques["Texture"];
              viewParam = effect.Parameters["View"];
              projectionParam = effect.Parameters["Projection"];
              textureParam = effect.Parameters["Texture"];
              colorParam = effect.Parameters["Color"];

              Texture = texture;
        }
Example #23
0
        public override void Create()
        {
            buffer = Plane(xCount, yCount);

            //Load the correct shader and set up the parameters
            IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)GameInstance.Services.GetService(typeof(IGraphicsDeviceService));

            effect = SpacewarGame.ContentManager.Load<Effect>(SpacewarGame.Settings.MediaPath + @"shaders\sun");

            worldParam = effect.Parameters["world"];
            worldViewProjectionParam = effect.Parameters["worldViewProjection"];
            sun0TextureParam = effect.Parameters["Sun_Tex0"];
            sun1TextureParam = effect.Parameters["Sun_Tex1"];
            blendFactor = effect.Parameters["blendFactor"];

            //Preload the textures into the cache
            int numFrames = 5;
            sun = new Texture2D[numFrames];

            sun[0] = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + @"textures\suntest1");
            sun[1] = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + @"textures\suntest2");
            sun[2] = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + @"textures\suntest3");
            sun[3] = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + @"textures\suntest4");
            sun[4] = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + @"textures\suntest5");
        }
Example #24
0
 protected override void OnInit()
 {
     base.OnInit();
     //Texture2D texture = Texture;
     effTime = eff.Parameters["Time"];
     spriteSortMode = SpriteSortMode.Deferred;
 }
Example #25
0
 private int SetParameter(int offset, EffectParameter param)
 {
   if (param.Data == null)
     return 0;
   int num;
   if (param.Elements.Count > 0)
   {
     num = param.RowCount * param.Elements.Count;
     this.SetData(offset, param.RowCount * param.Elements.Count, param.ColumnCount, 0, param.Data);
   }
   else
   {
     switch (param.ParameterType)
     {
       case EffectParameterType.Bool:
       case EffectParameterType.Int32:
       case EffectParameterType.Single:
         if (param.ParameterClass == EffectParameterClass.Matrix)
         {
           num = param.ColumnCount;
           this.SetData(offset, param.ColumnCount, param.RowCount, param.RegisterCount, param.Data);
           break;
         }
         else
         {
           num = param.RowCount;
           this.SetData(offset, param.RowCount, param.ColumnCount, param.RegisterCount, param.Data);
           break;
         }
       default:
         throw new NotImplementedException("Not supported!");
     }
   }
   return num;
 }
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CopyFilter"/> class.
 /// </summary>
 /// <param name="graphicsService">The graphics service.</param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="graphicsService"/> is <see langword="null"/>.
 /// </exception>
 public CopyFilter(IGraphicsService graphicsService)
     : base(graphicsService)
 {
     _effect = GraphicsService.Content.Load<Effect>("DigitalRune/PostProcessing/CopyFilter");
       _sourceTextureParameter = _effect.Parameters["SourceTexture"];
       _viewportSizeParameter = _effect.Parameters["ViewportSize"];
 }
        public ParticleEffect(Effect _fx, ParticleEffectConfig conf)
        {
            fx = _fx;
            fx.CurrentTechnique = fx.Techniques[0];

            fxPassSimple = fx.CurrentTechnique.Passes[conf.PassSimple];
            fxpVP = fx.Parameters[conf.ParamVP];
            fxpTime = fx.Parameters[conf.ParamTime];
            fxpMapSize = fx.Parameters[conf.ParamMapSize];

            fxPassLightning = fx.CurrentTechnique.Passes[conf.PassLightning];
            fxpLSplits = fx.Parameters[conf.ParamSplits];

            fxPassFire = fx.CurrentTechnique.Passes[conf.PassFire];
            fxpFRates = fx.Parameters[conf.ParamRates];
            fxpFScales = fx.Parameters[conf.ParamScales];
            fxpFOff1 = fx.Parameters[conf.ParamOffset1];
            fxpFOff2 = fx.Parameters[conf.ParamOffset2];
            fxpFOff3 = fx.Parameters[conf.ParamOffset3];
            fxpFDistortScale = fx.Parameters[conf.ParamDistortScale];
            fxpFDistortBias = fx.Parameters[conf.ParamDistortBias];

            fxPassAlert = fx.CurrentTechnique.Passes[conf.PassAlert];

            // Set Default Values
            LightningSplits = DEFAULT_SPLITS;
            FireDistortScale = DEFAULT_DISTORT_SCALE;
            FireDistortBias = DEFAULT_DISTORT_BIAS;
            FireOffset1 = DEFAULT_OFFSET;
            FireOffset2 = DEFAULT_OFFSET;
            FireOffset3 = DEFAULT_OFFSET;
            FireRates = DEFAULT_RATES;
            FireScales = DEFAULT_SCALES;
        }
        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="ProjectorLightRenderer"/> class.
        /// </summary>
        /// <param name="graphicsService">The graphics service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicsService"/> is <see langword="null"/>.
        /// </exception>
        public ProjectorLightRenderer(IGraphicsService graphicsService)
        {
            if (graphicsService == null)
            throw new ArgumentNullException("graphicsService");

              _effect = graphicsService.Content.Load<Effect>("DigitalRune/Deferred/ProjectorLight");
              _parameterWorldViewProjection = _effect.Parameters["WorldViewProjection"];
              _parameterViewportSize = _effect.Parameters["ViewportSize"];
              _parameterFrustumCorners = _effect.Parameters["FrustumCorners"];
              _parameterDiffuseColor = _effect.Parameters["ProjectorLightDiffuse"];
              _parameterSpecularColor = _effect.Parameters["ProjectorLightSpecular"];
              _parameterPosition = _effect.Parameters["ProjectorLightPosition"];
              _parameterRange = _effect.Parameters["ProjectorLightRange"];
              _parameterAttenuation = _effect.Parameters["ProjectorLightAttenuation"];
              _parameterTexture = _effect.Parameters["ProjectorLightTexture"];
              _parameterTextureMatrix = _effect.Parameters["ProjectorLightTextureMatrix"];
              _parameterGBuffer0 = _effect.Parameters["GBuffer0"];
              _parameterGBuffer1 = _effect.Parameters["GBuffer1"];
              _parameterShadowMaskChannel = _effect.Parameters["ShadowMaskChannel"];
              _parameterShadowMask = _effect.Parameters["ShadowMask"];
              _passClip = _effect.CurrentTechnique.Passes["Clip"];
              _passDefaultRgb = _effect.CurrentTechnique.Passes["DefaultRgb"];
              _passDefaultAlpha = _effect.CurrentTechnique.Passes["DefaultAlpha"];
              _passShadowedRgb = _effect.CurrentTechnique.Passes["ShadowedRgb"];
              _passShadowedAlpha = _effect.CurrentTechnique.Passes["ShadowedAlpha"];
        }
Example #29
0
 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)
 {
   if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != ~EffectDirtyFlags.All)
   {
     Matrix.Multiply(ref world, ref view, out worldView);
     Matrix result;
     Matrix.Multiply(ref worldView, ref projection, out result);
     worldViewProjParam.SetValue(result);
     dirtyFlags &= ~EffectDirtyFlags.WorldViewProj;
   }
   if (fogEnabled)
   {
     if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != ~EffectDirtyFlags.All)
     {
       EffectHelpers.SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam);
       dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable);
     }
   }
   else if ((dirtyFlags & EffectDirtyFlags.FogEnable) != ~EffectDirtyFlags.All)
   {
     fogVectorParam.SetValue(Vector4.Zero);
     dirtyFlags &= ~EffectDirtyFlags.FogEnable;
   }
   return dirtyFlags;
 }
Example #30
0
 public StencilSolidEffect(Effect effect)
 {
     _effect = effect;
     _pass = _effect.CurrentTechnique.Passes[0];
     _projection = effect.Parameters["Projection"];
     _transformation = effect.Parameters["Transformation"];
 }
Example #31
0
 /// <summary>
 /// Creates a new instance of <see cref="XNAEffectParameter"/>.
 /// </summary>
 /// <param name="param">The underlying XNA effect parameter.</param>
 internal XNAEffectParameter(XFG.EffectParameter param)
 {
     _param = param;
     SetClassAndType(param.ParameterClass, param.ParameterType);
     _elements      = new XNAEffectParameterCollection(param.Elements);
     _structMembers = new XNAEffectParameterCollection(param.StructureMembers);
     _annotations   = new XNAEffectAnnotationCollection(param.Annotations);
 }
Example #32
0
        internal EffectParameter(EffectParameter cloneSource)
        {
            // Share all the immutable types.
            ParameterClass = cloneSource.ParameterClass;
            ParameterType  = cloneSource.ParameterType;
            Name           = cloneSource.Name;
            Semantic       = cloneSource.Semantic;
            Annotations    = cloneSource.Annotations;
            RowCount       = cloneSource.RowCount;
            ColumnCount    = cloneSource.ColumnCount;

            // Clone the mutable types.
            Elements         = cloneSource.Elements.Clone();
            StructureMembers = cloneSource.StructureMembers.Clone();

            // The data is mutable, so we have to clone it.
            var array = cloneSource.Data as Array;

            if (array != null)
            {
                Data = array.Clone();
            }
            StateKey = unchecked (NextStateKey++);
        }
Example #33
0
 private static void SetEffectParameterVector(ShaderProgram program, int location, EffectParameter param)
 {
     //int elementCount = param.RowCount * param.ColumnCount;
     unsafe
     {
         float[] objArray = (float[])param.Data;
         fixed(float *data = objArray)
         {
             if (objArray.Length == 2)
             {
                 GL.Uniform2(location, 1, data);
             }
             else if (objArray.Length == 3)
             {
                 GL.Uniform3(location, 1, data);
             }
             else
             {
                 GL.Uniform4(location, 1, data);
             }
         }
     }
 }
Example #34
0
        public static void ApplyGL(this EffectPass pass)
        {
            // Set/get the correct shader handle/cleanups.
            //
            // TODO: This "reapply" if the shader index changes
            // trick is sort of ugly.  We should probably rework
            // this to use some sort of "technique/pass redirect".
            //
            EffectPassProperties props = PropertyTable.GetValue(pass, x => { return(new EffectPassProperties(pass)); });

            if (props.Effect.OnApply())
            {
                props.Effect.CurrentTechnique.Passes[0].ApplyGL();
                return;
            }

            var           device  = props.GraphicsDevice;
            ShaderProgram program = props.ShaderCache.GetProgram(props.VertexShader, props.PixelShader);

            GL.UseProgram(program.Program);
            if (props.VertexShader != null)
            {
                device.VertexShader = props.VertexShader;

                // Update the texture parameters.
                pass.SetShaderSamplers(props, props.VertexShader, device.VertexTextures, device.VertexSamplerStates);

                foreach (int paramIndex in props.VertexShaderParams)
                {
                    EffectParameter param = props.Effect.Parameters[paramIndex];
                    SetEffectParameter(program, param);
                }
                // Update the constant buffers.
                foreach (int c in props.VertexShader.CBuffers)
                {
                    device.SetConstantBuffer(ShaderStage.Vertex, c, null);
                }
            }

            if (props.PixelShader != null)
            {
                device.PixelShader = props.PixelShader;

                // Update the texture parameters.
                pass.SetShaderSamplers(props, props.PixelShader, device.Textures, device.SamplerStates);

                foreach (int paramIndex in props.PixelShaderParams)
                {
                    EffectParameter param = props.Effect.Parameters[paramIndex];
                    SetEffectParameter(program, param);
                }
                // Update the constant buffers.
                foreach (int c in props.PixelShader.CBuffers)
                {
                    device.SetConstantBuffer(ShaderStage.Pixel, c, null);
                }
            }


            // Set the render states if we have some.
            if (props.RasterizerState != null)
            {
                device.RasterizerState = props.RasterizerState;
            }
            if (props.BlendState != null)
            {
                device.BlendState = props.BlendState;
            }
            if (props.DepthStencilState != null)
            {
                device.DepthStencilState = props.DepthStencilState;
            }
        }
Example #35
0
 private static void SetEffectParameterObject(ShaderProgram program, int location, EffectParameter param)
 {
     object obj = param.Data;
 }
Example #36
0
 private static void SetEffectParameterMatrix(ShaderProgram program, int location, EffectParameter param)
 {
     //int elementCount = param.RowCount * param.ColumnCount;
     unsafe
     {
         float[] objArray = (float[])param.Data;
         fixed(float *data = objArray)
         {
             GL.UniformMatrix4(location, 1, false, data);
         }
     }
 }
Example #37
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.Translation);

                dirtyFlags &= ~EffectDirtyFlags.EyePosition;
            }

            return(dirtyFlags);
        }
Example #38
0
 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)
 {
     if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != ~EffectDirtyFlags.All)
     {
         Matrix.Multiply(ref world, ref view, out worldView);
         Matrix result;
         Matrix.Multiply(ref worldView, ref projection, out result);
         worldViewProjParam.SetValue(result);
         dirtyFlags &= ~EffectDirtyFlags.WorldViewProj;
     }
     if (fogEnabled)
     {
         if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != ~EffectDirtyFlags.All)
         {
             EffectHelpers.SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam);
             dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable);
         }
     }
     else if ((dirtyFlags & EffectDirtyFlags.FogEnable) != ~EffectDirtyFlags.All)
     {
         fogVectorParam.SetValue(Vector4.Zero);
         dirtyFlags &= ~EffectDirtyFlags.FogEnable;
     }
     return(dirtyFlags);
 }
Example #39
0
 internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view, EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam)
 {
     if ((dirtyFlags & EffectDirtyFlags.World) != ~EffectDirtyFlags.All)
     {
         Matrix result1;
         Matrix.Invert(ref world, out result1);
         Matrix result2;
         Matrix.Transpose(ref result1, out result2);
         worldParam.SetValue(world);
         worldInverseTransposeParam.SetValue(result2);
         dirtyFlags &= ~EffectDirtyFlags.World;
     }
     if ((dirtyFlags & EffectDirtyFlags.EyePosition) != ~EffectDirtyFlags.All)
     {
         Matrix result;
         Matrix.Invert(ref view, out result);
         eyePositionParam.SetValue(result.Translation);
         dirtyFlags &= ~EffectDirtyFlags.EyePosition;
     }
     return(dirtyFlags);
 }
 internal BasicDirectionalLight(EffectParameter direction, EffectParameter diffuseColor, EffectParameter specularColor)
 {
     this.directionParam     = direction;
     this.diffuseColorParam  = diffuseColor;
     this.specularColorParam = specularColor;
 }
Example #41
0
        public static bool TryParse(Stream s, GraphicsDevice g, ContentManager c, out Effect fx, ref List <object> refs, ParsingFlags ps = ParsingFlags.None)
        {
            fx = null;
            StreamReader f = new StreamReader(new BufferedStream(s));

            // Get The Arguments From The Material File
            List <string[]> args = new List <string[]>();

            while (!f.EndOfStream)
            {
                string line = f.ReadLine();
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }
                string[] split = line.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                if (split.Length < 1)
                {
                    continue;
                }
                split[0] = split[0].Trim().ToLower();
                switch (split[0])
                {
                case "fx": if (split.Length >= 2)
                    {
                        args.Add(split);
                    }
                    break;

                case "fxpt": if (split.Length >= 3)
                    {
                        args.Add(split);
                    }
                    break;

                case "fxptc": if (split.Length >= 3)
                    {
                        args.Add(split);
                    }
                    break;

                case "fxpf": if (split.Length >= 4)
                    {
                        args.Add(split);
                    }
                    break;
                }
            }

            // Get The Effect For This Material
            Predicate <string[]> fxMatch = (a) => { return(a[0].Equals("fx")); };

            string[] fxArg = args.Find(fxMatch);
            if (fxArg == null)
            {
                return(false);
            }
            args.RemoveAll(fxMatch);


            // Try To Create The Effect
            if (ps.HasFlag(ParsingFlags.LoadEffectByteCode))
            {
                try {
                    byte[] code = null;
                    using (FileStream fxs = File.OpenRead(fxArg[1].Trim())) {
                        code = new byte[fxs.Length];
                        fxs.Read(code, 0, code.Length);
                    }
                    fx = new Effect(g, code);
                }
                catch (Exception) { fx = null; return(false); }
            }
            else
            {
                try { fx = c.Load <Effect>(fxArg[1].Trim()); }
                catch (Exception) { fx = null; return(false); }
            }

            // Will Attempt To Set As Many Uniforms As Possible Without Raising Errors
            foreach (string[] arg in args)
            {
                switch (arg[0])
                {
                case "fxpt":
                    EffectParameter fxpt = fx.Parameters[arg[1].Trim()];
                    if (fxpt == null)
                    {
                        continue;
                    }
                    try {
                        Texture2D t = null;
                        if (ps.HasFlag(ParsingFlags.LoadTextureStream))
                        {
                            using (FileStream ts = File.OpenRead(arg[2].Trim())) {
                                t = Texture2D.FromStream(g, ts);
                            }
                        }
                        else
                        {
                            t = c.Load <Texture2D>(arg[2].Trim());
                        }
                        if (t != null)
                        {
                            refs.Add(t);
                            fxpt.SetValue(t);
                        }
                    }
                    catch (Exception) { continue; }
                    break;

                case "fxptc":     // Texture Cube Parameter
                    EffectParameter fxptc = fx.Parameters[arg[1].Trim()];
                    if (fxptc == null)
                    {
                        continue;
                    }
                    try {
                        TextureCube tc = c.Load <TextureCube>(arg[2].Trim());
                        if (tc != null)
                        {
                            refs.Add(tc);
                            fxptc.SetValue(tc);
                        }
                    }
                    catch (Exception) { continue; }
                    break;

                case "fxpf":     // Vector Parameter
                    EffectParameter fxptv = fx.Parameters[arg[1].Trim()];
                    int             comps;
                    if (fxptv == null || !int.TryParse(arg[2], out comps))
                    {
                        continue;
                    }
                    string[] sc = arg[3].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    if (sc.Length != comps)
                    {
                        continue;
                    }
                    switch (comps)
                    {
                    case 1:
                        float v1;
                        if (float.TryParse(sc[0], out v1))
                        {
                            fxptv.SetValue(v1);
                        }
                        break;

                    case 2:
                        Vector2 v2 = Vector2.Zero;
                        if (float.TryParse(sc[0], out v2.X) &&
                            float.TryParse(sc[1], out v2.Y)
                            )
                        {
                            fxptv.SetValue(v2);
                        }
                        break;

                    case 3:
                        Vector3 v3 = Vector3.Zero;
                        if (float.TryParse(sc[0], out v3.X) &&
                            float.TryParse(sc[1], out v3.Y) &&
                            float.TryParse(sc[2], out v3.Z)
                            )
                        {
                            fxptv.SetValue(v3);
                        }
                        break;

                    case 4:
                        Vector4 v4 = Vector4.Zero;
                        if (float.TryParse(sc[0], out v4.X) &&
                            float.TryParse(sc[1], out v4.Y) &&
                            float.TryParse(sc[2], out v4.Z) &&
                            float.TryParse(sc[3], out v4.W)
                            )
                        {
                            fxptv.SetValue(v4);
                        }
                        break;

                    default:
                        if (comps > 4)
                        {
                            float[] vn  = new float[comps];
                            bool    vnc = true;
                            for (int i = 0; i < sc.Length && i < vn.Length && vnc; i++)
                            {
                                if (!float.TryParse(sc[i], out vn[i]))
                                {
                                    vnc = false;
                                }
                            }
                            if (vnc)
                            {
                                fxptv.SetValue(vn);
                            }
                        }
                        break;
                    }
                    break;
                }
            }
            return(true);
        }
Example #42
0
 internal static void SetMaterialColor(bool lightingEnabled, float alpha, ref Vector3 diffuseColor, ref Vector3 emissiveColor, ref Vector3 ambientLightColor, EffectParameter diffuseColorParam, EffectParameter emissiveColorParam)
 {
     if (lightingEnabled)
     {
         Vector4 vector4 = new Vector4();
         Vector3 vector3 = new Vector3();
         vector4.X = diffuseColor.X * alpha;
         vector4.Y = diffuseColor.Y * alpha;
         vector4.Z = diffuseColor.Z * alpha;
         vector4.W = alpha;
         vector3.X = (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha;
         vector3.Y = (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha;
         vector3.Z = (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha;
         diffuseColorParam.SetValue(vector4);
         emissiveColorParam.SetValue(vector3);
     }
     else
     {
         diffuseColorParam.SetValue(new Vector4()
         {
             X = (diffuseColor.X + emissiveColor.X) * alpha,
             Y = (diffuseColor.Y + emissiveColor.Y) * alpha,
             Z = (diffuseColor.Z + emissiveColor.Z) * alpha,
             W = alpha
         });
     }
 }
Example #43
0
 /// <summary>
 /// Looks up shortcut references to our effect parameters.
 /// </summary>
 void CacheEffectParameters()
 {
     matrixParam = Parameters["MatrixTransform"];
 }
Example #44
0
        private static EffectParameterCollection ReadParameters(BinaryReader reader)
        {
            var count = (int)reader.ReadByte();

            if (count == 0)
            {
                return(EffectParameterCollection.Empty);
            }

            var parameters = new EffectParameter[count];

            for (var i = 0; i < count; i++)
            {
                var class_      = (EffectParameterClass)reader.ReadByte();
                var type        = (EffectParameterType)reader.ReadByte();
                var name        = reader.ReadString();
                var semantic    = reader.ReadString();
                var annotations = ReadAnnotations(reader);
                var rowCount    = (int)reader.ReadByte();
                var columnCount = (int)reader.ReadByte();

                var elements      = ReadParameters(reader);
                var structMembers = ReadParameters(reader);

                object data = null;
                if (elements.Count == 0 && structMembers.Count == 0)
                {
                    switch (type)
                    {
                    case EffectParameterType.Bool:
                    case EffectParameterType.Int32:
#if DIRECTX
                        // Under DirectX we properly store integers and booleans
                        // in an integer type.
                        //
                        // MojoShader on the otherhand stores everything in float
                        // types which is why this code is disabled under OpenGL.
                    {
                        var buffer = new int[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadInt32();
                        }
                        data = buffer;
                        break;
                    }
#endif

                    case EffectParameterType.Single:
                    {
                        var buffer = new float[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadSingle();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.String:
                        // TODO: We have not investigated what a string
                        // type should do in the parameter list.  Till then
                        // throw to let the user know.
                        throw new NotSupportedException();

                    default:
                        // NOTE: We skip over all other types as they
                        // don't get added to the constant buffer.
                        break;
                    }
                }

                parameters[i] = new EffectParameter(
                    class_, type, name, rowCount, columnCount, semantic,
                    annotations, elements, structMembers, data);
            }

            return(new EffectParameterCollection(parameters));
        }
Example #45
0
 private void CacheEffectParameters()
 {
     this.matrixParam = this.Parameters["MatrixTransform"];
 }
Example #46
0
        private static EffectParameterCollection ReadParameters(BinaryReader reader)
        {
            var collection = new EffectParameterCollection();
            var count      = (int)reader.ReadByte();

            if (count == 0)
            {
                return(collection);
            }

            for (var i = 0; i < count; i++)
            {
                var class_ = (EffectParameterClass)reader.ReadByte();
                var type   = (EffectParameterType)reader.ReadByte();

                var name        = reader.ReadString();
                var semantic    = reader.ReadString();
                var annotations = ReadAnnotations(reader);

                var rowCount    = (int)reader.ReadByte();
                var columnCount = (int)reader.ReadByte();

                var elements      = ReadParameters(reader);
                var structMembers = ReadParameters(reader);

                object data = null;
                if (elements.Count == 0 && structMembers.Count == 0)
                {
                    switch (type)
                    {
                    case EffectParameterType.Bool:
                    case EffectParameterType.Int32:
                    {
                        var buffer = new int[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadInt32();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.Single:
                    {
                        var buffer = new float[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadSingle();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.String:
                        throw new NotImplementedException();
                    }
                    ;
                }

                var param = new EffectParameter(
                    class_, type, name, rowCount, columnCount, semantic,
                    annotations, elements, structMembers, data);

                collection.Add(param);
            }

            return(collection);
        }
Example #47
0
        public DirectionalLight(EffectParameter directionParameter, EffectParameter diffuseColorParameter, EffectParameter specularColorParameter, DirectionalLight cloneSource)
        {
            if (cloneSource != null)
            {
                this.diffuseColorParameter  = cloneSource.diffuseColorParameter;
                this.directionParameter     = cloneSource.directionParameter;
                this.specularColorParameter = cloneSource.specularColorParameter;

                this.diffuseColor  = cloneSource.diffuseColor;
                this.direction     = cloneSource.direction;
                this.specularColor = cloneSource.specularColor;
                this.enabled       = cloneSource.enabled;
            }
            else
            {
                this.diffuseColorParameter  = diffuseColorParameter;
                this.directionParameter     = directionParameter;
                this.specularColorParameter = specularColorParameter;
            }
        }
Example #48
0
        internal EffectParameter(Effect parent, string paramName, int paramIndex, int userIndex, int uniformLocation,
                                 string paramSType, int paramLength, int numOfElements)
        {
            _parentEffect = parent;

            internalIndex      = paramIndex;
            internalLength     = paramLength;
            this.numOfElements = numOfElements;

            this.userIndex       = userIndex;
            this.uniformLocation = uniformLocation;

            elements = new EffectParameterCollection();

            // Check if the parameter is an array
            if (numOfElements > 1)
            {
                // We have to strip off the [0] at the end so that the
                // parameter can be references with just the name with no
                // index specifications
                if (paramName.EndsWith("[0]"))
                {
                    paramName = paramName.Remove(paramName.Length - 3);
                }
            }

            name = paramName;

            switch (paramSType)
            {
            case "Float":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Scalar;
                rowCount     = 1;
                colCount     = 1;
                _cachedValue = 0.0f;
                break;

            case "FloatVec2":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 2;
                _cachedValue = MonoMac.OpenGL.Vector2.Zero;
                break;

            case "FloatVec3":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 3;
                _cachedValue = MonoMac.OpenGL.Vector3.Zero;
                break;

            case "FloatVec4":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 4;
                _cachedValue = MonoMac.OpenGL.Vector4.Zero;
                break;

            case "Sampler2D":
                paramType  = EffectParameterType.Texture2D;
                paramClass = EffectParameterClass.Object;
                rowCount   = 0;
                colCount   = 0;
                break;

            case "FloatMat4":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Matrix;
                rowCount     = 4;
                colCount     = 4;
                _cachedValue = MonoMac.OpenGL.Matrix4.Identity;
                break;
            }

            if (numOfElements > 1)
            {
                // Setup our elements
                for (int x = 0; x < numOfElements; x++)
                {
                    EffectParameter ep = new EffectParameter(parent, name, paramIndex, userIndex, uniformLocation,
                                                             paramType, paramClass, rowCount, colCount, _cachedValue, paramLength);
                    elements._parameters.Add(ep.Name + "[" + x + "]", ep);
                }
            }
        }
Example #49
0
 private static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam)
 {
     if ((double)fogStart == (double)fogEnd)
     {
         fogVectorParam.SetValue(new Vector4(0.0f, 0.0f, 0.0f, 1f));
     }
     else
     {
         float num = (float)(1.0 / ((double)fogStart - (double)fogEnd));
         fogVectorParam.SetValue(new Vector4()
         {
             X = worldView.M13 * num,
             Y = worldView.M23 * num,
             Z = worldView.M33 * num,
             W = (worldView.M43 + fogStart) * num
         });
     }
 }
Example #50
0
        private static EffectParameterCollection ReadParameters(BinaryReader reader)
        {
            var collection = new EffectParameterCollection();
            var count      = (int)reader.ReadByte();

            if (count == 0)
            {
                return(collection);
            }

            for (var i = 0; i < count; i++)
            {
                var class_      = (EffectParameterClass)reader.ReadByte();
                var type        = (EffectParameterType)reader.ReadByte();
                var name        = reader.ReadString();
                var semantic    = reader.ReadString();
                var annotations = ReadAnnotations(reader);
                var rowCount    = (int)reader.ReadByte();
                var columnCount = (int)reader.ReadByte();

                var elements      = ReadParameters(reader);
                var structMembers = ReadParameters(reader);

                object data = null;
                if (elements.Count == 0 && structMembers.Count == 0)
                {
                    switch (type)
                    {
                    case EffectParameterType.Bool:
                    case EffectParameterType.Int32:
#if DIRECTX
                        // Under DirectX we properly store integers and booleans
                        // in an integer type.
                        //
                        // MojoShader on the otherhand stores everything in float
                        // types which is why this code is disabled under OpenGL.
                    {
                        var buffer = new int[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadInt32();
                        }
                        data = buffer;
                        break;
                    }
#endif

                    case EffectParameterType.Single:
                    {
                        var buffer = new float[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadSingle();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.String:
                        throw new NotImplementedException();
                    }
                }
                var param = new EffectParameter(
                    class_, type, name, rowCount, columnCount, semantic,
                    annotations, elements, structMembers, data);

                collection.Add(param);
            }

            return(collection);
        }
Example #51
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);
        }