Represents entire visible world.
상속: RenderLayer
예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rs"></param>
        internal ParticleSystem(RenderSystem rs, RenderWorld renderWorld)
        {
            this.rs          = rs;
            this.Game        = rs.Game;
            this.renderWorld = renderWorld;

            Gravity = Vector3.Down * 9.80665f;

            paramsCB = new ConstantBuffer(Game.GraphicsDevice, typeof(PrtParams));
            imagesCB = new ConstantBuffer(Game.GraphicsDevice, typeof(Vector4), MaxImages);

            injectionBuffer      = new StructuredBuffer(Game.GraphicsDevice, typeof(Particle), MaxInjectingParticles, StructuredBufferFlags.None);
            simulationBuffer     = new StructuredBuffer(Game.GraphicsDevice, typeof(Particle), MaxSimulatedParticles, StructuredBufferFlags.None);
            particleLighting     = new StructuredBuffer(Game.GraphicsDevice, typeof(Vector4), MaxSimulatedParticles, StructuredBufferFlags.None);
            sortParticlesBuffer  = new StructuredBuffer(Game.GraphicsDevice, typeof(Vector2), MaxSimulatedParticles, StructuredBufferFlags.None);
            deadParticlesIndices = new StructuredBuffer(Game.GraphicsDevice, typeof(uint), MaxSimulatedParticles, StructuredBufferFlags.Append);

            rs.Game.Reloading += LoadContent;
            LoadContent(this, EventArgs.Empty);

            //	initialize dead list :
            var device = Game.GraphicsDevice;

            device.SetCSRWBuffer(1, deadParticlesIndices, 0);
            device.PipelineState = factory[(int)Flags.INITIALIZE];
            device.Dispatch(MathUtil.IntDivUp(MaxSimulatedParticles, BlockSize));
        }
예제 #2
0
        /// <summary>
        /// Intializes graphics engine.
        /// </summary>
        public override void Initialize()
        {
            //	init components :
            InitializeComponent(spriteEngine);
            InitializeComponent(filter);
            InitializeComponent(ssaoFilter);
            InitializeComponent(hdrFilter);
            InitializeComponent(dofFilter);
            InitializeComponent(lightRenderer);
            InitializeComponent(sceneRenderer);
            InitializeComponent(sky);
            InitializeComponent(bitonicSort);
            InitializeComponent(vtSystem);

            //	create default textures :
            whiteTexture = new DynamicTexture(this, 4, 4, typeof(Color), false, false);
            whiteTexture.SetData(Enumerable.Range(0, 16).Select(i => Color.White).ToArray());

            grayTexture = new DynamicTexture(this, 4, 4, typeof(Color), false, false);
            grayTexture.SetData(Enumerable.Range(0, 16).Select(i => Color.Gray).ToArray());

            blackTexture = new DynamicTexture(this, 4, 4, typeof(Color), false, false);
            blackTexture.SetData(Enumerable.Range(0, 16).Select(i => Color.Black).ToArray());

            flatNormalMap = new DynamicTexture(this, 4, 4, typeof(Color), false, false);
            flatNormalMap.SetData(Enumerable.Range(0, 16).Select(i => new Color(127, 127, 255, 127)).ToArray());

            //	set sprite layers :
            SpriteLayers = new SpriteLayerCollection();

            //	add default render world :
            renderWorld = new RenderWorld(Game, Width, Height);

            DisplayBoundsChanged += (s, e) => renderWorld.Resize(DisplayBounds.Width, DisplayBounds.Height);
        }
예제 #3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sfxSystem"></param>
 /// <param name="fxEvent"></param>
 public SfxInstance( SfxSystem sfxSystem, FXEvent fxEvent )
 {
     this.sfxSystem	=	sfxSystem;
     this.rw			=	sfxSystem.rw;
     this.sw			=	sfxSystem.sw;
     this.fxEvent	=	fxEvent;
 }
예제 #4
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="game"></param>
        public SfxSystem( ShooterClient client, World world )
        {
            this.world	=	world;
            this.client	=	client;
            this.game	=	client.Game;
            this.rw		=	game.RenderSystem.RenderWorld;
            this.sw		=	game.SoundSystem.SoundWorld;

            Game_Reloading(this, EventArgs.Empty);
            game.Reloading +=	Game_Reloading;

            SfxInstance.EnumerateSFX( type => sfxDict.Add( type.Name, type ) );
        }
예제 #5
0
        /// <summary>
        ///
        /// </summary>
        void SetupGPUParameters(float stepTime, RenderWorld renderWorld, Matrix view, Matrix projection, Flags flags)
        {
            var deltaTime    = stepTime;
            var camera       = renderWorld.Camera;
            var cameraMatrix = Matrix.Invert(view);

            //	kill particles by applying very large delta.
            if (requestKill)
            {
                deltaTime   = float.MaxValue / 2;
                requestKill = false;
            }
            if (rs.FreezeParticles)
            {
                deltaTime = 0;
            }

            //	fill constant data :
            PrtParams param = new PrtParams();

            param.View            = view;
            param.Projection      = projection;
            param.MaxParticles    = 0;
            param.DeltaTime       = deltaTime;
            param.CameraForward   = new Vector4(cameraMatrix.Forward, 0);
            param.CameraRight     = new Vector4(cameraMatrix.Right, 0);
            param.CameraUp        = new Vector4(cameraMatrix.Up, 0);
            param.CameraPosition  = new Vector4(cameraMatrix.TranslationVector, 1);
            param.Gravity         = new Vector4(this.Gravity, 0);
            param.MaxParticles    = MaxSimulatedParticles;
            param.LinearizeDepthA = camera.LinearizeDepthScale;
            param.LinearizeDepthB = camera.LinearizeDepthBias;
            param.CocBias         = renderWorld.DofSettings.CocBias;
            param.CocScale        = renderWorld.DofSettings.CocScale;

            if (flags == Flags.INJECTION)
            {
                param.MaxParticles = injectionCount;
            }

            //	copy to gpu :
            paramsCB.SetData(param);

            //	set DeadListSize to prevent underflow:
            if (flags == Flags.INJECTION)
            {
                deadParticlesIndices.CopyStructureCount(paramsCB, Marshal.OffsetOf(typeof(PrtParams), "DeadListSize").ToInt32());
            }
        }
예제 #6
0
		/// <summary>
		/// 
		/// </summary>
		public override void Initialize ()
		{
			//	create view layer :
			master = new RenderWorld( Game, 0, 0 );

			//	add view to layer to scene :
			Game.RenderSystem.AddLayer( master );

			//	add console sprite layer to master view layer :
			master.SpriteLayers.Add( console.ConsoleSpriteLayer );

			//	load content and scubscribe on content reload.
			LoadContent();
			Game.Reloading += (s,e) => LoadContent();
		}
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="gameTime"></param>
        /// <param name="stereoEye"></param>
        internal void Draw(GameTime gameTime, StereoEye stereoEye)
        {
            Counters.Reset();

            var targetColorSurface = Device.Display.BackbufferColor.Surface;
            var targetDepthSurface = Device.Display.BackbufferDepth.Surface;

            //	render world :
            RenderWorld.Render(gameTime, stereoEye, targetColorSurface);

            //	draw sprites :
            SpriteEngine.DrawSprites(gameTime, stereoEye, targetColorSurface, SpriteLayers);

            if (ShowCounters)
            {
                Counters.PrintCounters();
            }
        }
예제 #8
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="view"></param>
		/// <param name="projection"></param>
		internal void RenderLighting ( StereoEye stereoEye, Camera camera, HdrFrame hdrFrame, RenderWorld viewLayer, RenderTargetCube envLight )
		{
			using ( new PixEvent("TiledLighting") ) {
				var view		=	camera.GetViewMatrix( stereoEye );
				var projection	=	camera.GetProjectionMatrix( stereoEye );

				var device = Game.GraphicsDevice;
				device.ResetStates();

				var width	=	hdrFrame.HdrBuffer.Width;
				var height	=	hdrFrame.HdrBuffer.Height;


				ICSMController csmCtrl	=	viewLayer.LightSet.DirectLight.CSMController ?? csmController;

				int activeCascadeCount	=	Math.Min( cascadedShadowMap.CascadeCount, csmCtrl.GetActiveCascadeCount() );


				//
				//	Setup compute shader parameters and states :
				//
				try {

					var cbData	=	new LightingParams();
					var invView	=	Matrix.Invert( view );
					var invVP	=	Matrix.Invert( view * projection );
					var viewPos	=	invView.TranslationVector;

					cbData.DirectLightDirection		=	new Vector4( viewLayer.LightSet.DirectLight.Direction, 0 );
					cbData.DirectLightIntensity		=	viewLayer.LightSet.DirectLight.Intensity.ToVector4();
					cbData.Projection				=	projection;

					cbData.CSMViewProjection0		=	csmCtrl.GetShadowViewMatrix(0) * csmCtrl.GetShadowProjectionMatrix(0);
					cbData.CSMViewProjection1		=	csmCtrl.GetShadowViewMatrix(1) * csmCtrl.GetShadowProjectionMatrix(1);
					cbData.CSMViewProjection2		=	csmCtrl.GetShadowViewMatrix(2) * csmCtrl.GetShadowProjectionMatrix(2);
					cbData.CSMViewProjection3		=	csmCtrl.GetShadowViewMatrix(3) * csmCtrl.GetShadowProjectionMatrix(3);

					cbData.View						=	view;
					cbData.ViewPosition				=	new Vector4(viewPos,1);
					cbData.InverseViewProjection	=	invVP;
					cbData.CSMFilterRadius			=	new Vector4( CSMFilterSize );

					cbData.AmbientColor				=	viewLayer.LightSet.AmbientLevel;
					cbData.Viewport					=	new Vector4( 0, 0, width, height );
					cbData.ShowCSLoadOmni			=	ShowOmniLightTileLoad ? 1 : 0;
					cbData.ShowCSLoadEnv			=	ShowEnvLightTileLoad  ? 1 : 0;
					cbData.ShowCSLoadSpot			=	ShowSpotLightTileLoad ? 1 : 0;

					cbData.CascadeCount				=	activeCascadeCount;
					cbData.CascadeScale				=	1.0f / (float)cascadedShadowMap.CascadeCount;


					ComputeOmniLightsTiles( view, projection, viewLayer.LightSet );
					ComputeSpotLightsTiles( view, projection, viewLayer.LightSet );
					ComputeEnvLightsTiles(  view, projection, viewLayer.LightSet );

					//
					//	set states :
					//
					device.SetTargets( null, hdrFrame.HdrBuffer.Surface );

					lightingCB.SetData( cbData );

					device.ComputeShaderSamplers[0]	=	SamplerState.PointClamp;
					device.ComputeShaderSamplers[1]	=	SamplerState.LinearClamp;
					device.ComputeShaderSamplers[2]	=	SamplerState.ShadowSampler;
					device.ComputeShaderSamplers[3]	=	SamplerState.LinearPointWrap;

					device.ComputeShaderResources[0]	=	hdrFrame.DiffuseBuffer;
					device.ComputeShaderResources[1]	=	hdrFrame.SpecularBuffer;
					device.ComputeShaderResources[2]	=	hdrFrame.NormalMapBuffer;
					device.ComputeShaderResources[3]	=	hdrFrame.ScatteringBuffer;
					device.ComputeShaderResources[4]	=	hdrFrame.DepthBuffer;
					device.ComputeShaderResources[5]	=	cascadedShadowMap.ColorBuffer;
					device.ComputeShaderResources[6]	=	spotColor;
					device.ComputeShaderResources[7]	=	viewLayer.LightSet.SpotAtlas==null ? rs.WhiteTexture.Srv : viewLayer.LightSet.SpotAtlas.Texture.Srv;
					device.ComputeShaderResources[8]	=	omniLightBuffer;
					device.ComputeShaderResources[9]	=	spotLightBuffer;
					device.ComputeShaderResources[10]	=	envLightBuffer;
					device.ComputeShaderResources[11]	=	rs.SsaoFilter.OcclusionMap;
					device.ComputeShaderResources[12]	=	viewLayer.RadianceCache;
					device.ComputeShaderResources[13]	=	viewLayer.ParticleSystem.SimulatedParticles;
					device.ComputeShaderResources[14]	=	cascadedShadowMap.ParticleShadow;

					device.ComputeShaderConstants[0]	=	lightingCB;

					device.SetCSRWTexture( 0, hdrFrame.LightAccumulator.Surface );
					device.SetCSRWTexture( 1, hdrFrame.SSSAccumulator.Surface );
					device.SetCSRWBuffer(  2, viewLayer.ParticleSystem.ParticleLighting );

					//
					//	Dispatch solids :
					//
					using (new PixEvent("Solid Lighting")) {
						device.PipelineState	=	factory[ (int)LightingFlags.SOLIDLIGHTING ];
						device.Dispatch( MathUtil.IntDivUp( width, BlockSizeX ), MathUtil.IntDivUp( height, BlockSizeY ), 1 );
					}

					//
					//	Dispatch particles :
					//
					using (new PixEvent("Particle Lighting")) {
						if (stereoEye!=StereoEye.Right) {
							int threadGroupCount	=	MathUtil.IntDivUp( ParticleSystem.MaxSimulatedParticles, ParticleSystem.BlockSize );
							device.PipelineState	=	factory[ (int)LightingFlags.PARTICLES ];
							device.Dispatch( threadGroupCount, 1, 1 );
						}
					}
	
				} catch ( UbershaderException e ) {
					Log.Warning("{0}", e.Message );
				}


				//
				//	Add accumulated light  :
				//
				rs.Filter.OverlayAdditive( hdrFrame.HdrBuffer.Surface, hdrFrame.LightAccumulator );

				//	Uncomment to enable SSS :
				#if false
				rs.Filter.GaussBlur( hdrFrame.SSSAccumulator, hdrFrame.LightAccumulator, 5, 0 ); 
				rs.Filter.OverlayAdditive( hdrFrame.HdrBuffer.Surface, hdrFrame.SSSAccumulator );
				#endif

				device.ResetStates();


				if (rs.ShowLightCounters) {
					var ls = viewLayer.LightSet;
					Log.Message("lights: {0,5} omni {1,5} spot {2,5} env", ls.OmniLights.Count, ls.SpotLights.Count, ls.EnvLights.Count );
				}
			}
		}
예제 #9
0
        /// <summary>
        /// Performs luminance measurement, tonemapping, applies bloom.
        /// </summary>
        /// <param name="target">LDR target.</param>
        /// <param name="hdrImage">HDR source image.</param>
        public void Render(GameTime gameTime, RenderTargetSurface target, ShaderResource hdrImage, RenderWorld viewLayer)
        {
            var device = Game.GraphicsDevice;
            var filter = Game.RenderSystem.Filter;

            var settings = viewLayer.HdrSettings;

            using (new PixEvent("HDR Postprocessing")) {
                //
                //	Rough downsampling of source HDR-image :
                //
                filter.StretchRect(averageLum.Surface, hdrImage, SamplerState.PointClamp);
                averageLum.BuildMipmaps();

                //
                //	Make bloom :
                //
                filter.StretchRect(viewLayer.Bloom0.Surface, hdrImage, SamplerState.LinearClamp);
                viewLayer.Bloom0.BuildMipmaps();

                filter.GaussBlur(viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 0);
                filter.GaussBlur(viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 1);
                filter.GaussBlur(viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 2);
                filter.GaussBlur(viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 3);

                //
                //	Setup parameters :
                //
                var paramsData = new Params();
                paramsData.AdaptationRate     = 1 - (float)Math.Pow(0.5f, gameTime.ElapsedSec / settings.AdaptationHalfLife);
                paramsData.LuminanceLowBound  = settings.LuminanceLowBound;
                paramsData.LuminanceHighBound = settings.LuminanceHighBound;
                paramsData.KeyValue           = settings.KeyValue;
                paramsData.BloomAmount        = settings.BloomAmount;
                paramsData.DirtMaskLerpFactor = settings.DirtMaskLerpFactor;
                paramsData.DirtAmount         = settings.DirtAmount;
                paramsData.Saturation         = settings.Saturation;
                paramsData.MaximumOutputValue = settings.MaximumOutputValue;
                paramsData.MinimumOutputValue = settings.MinimumOutputValue;
                paramsData.DitherAmount       = settings.DitherAmount;

                paramsCB.SetData(paramsData);
                device.PixelShaderConstants[0] = paramsCB;

                //
                //	Measure and adapt :
                //
                device.SetTargets(null, viewLayer.MeasuredNew);

                device.PixelShaderResources[0] = averageLum;
                device.PixelShaderResources[1] = viewLayer.MeasuredOld;

                device.PipelineState = factory[(int)(Flags.MEASURE_ADAPT)];

                device.Draw(3, 0);


                //
                //	Tonemap and compose :
                //
                device.SetTargets(null, target);

                device.PixelShaderResources[0] = hdrImage;                       // averageLum;
                device.PixelShaderResources[1] = viewLayer.MeasuredNew;          // averageLum;
                device.PixelShaderResources[2] = viewLayer.Bloom0;               // averageLum;
                device.PixelShaderResources[3] = settings.DirtMask1 == null ? whiteTex.Srv : settings.DirtMask1.Srv;
                device.PixelShaderResources[4] = settings.DirtMask2 == null ? whiteTex.Srv : settings.DirtMask2.Srv;
                device.PixelShaderResources[5] = noiseTex.Srv;
                device.PixelShaderSamplers[0]  = SamplerState.LinearClamp;

                Flags op = Flags.LINEAR;
                if (settings.TonemappingOperator == TonemappingOperator.Filmic)
                {
                    op = Flags.FILMIC;
                }
                if (settings.TonemappingOperator == TonemappingOperator.Linear)
                {
                    op = Flags.LINEAR;
                }
                if (settings.TonemappingOperator == TonemappingOperator.Reinhard)
                {
                    op = Flags.REINHARD;
                }

                device.PipelineState = factory[(int)(Flags.TONEMAPPING | op)];

                device.Draw(3, 0);

                device.ResetStates();


                //	swap luminanice buffers :
                Misc.Swap(ref viewLayer.MeasuredNew, ref viewLayer.MeasuredOld);
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="camera"></param>
        /// <param name="depthBuffer"></param>
        /// <param name="hdrTarget"></param>
        /// <param name="diffuse"></param>
        /// <param name="specular"></param>
        /// <param name="normals"></param>
        internal void RenderGBuffer(GameTime gameTime, StereoEye stereoEye, Camera camera, HdrFrame frame, RenderWorld rw, bool staticOnly)
        {
            using (new PixEvent("RenderGBuffer")) {
                if (surfaceShader == null)
                {
                    return;
                }

                if (rs.SkipSceneRendering)
                {
                    return;
                }

                var device = Game.GraphicsDevice;

                var view         = camera.GetViewMatrix(stereoEye);
                var projection   = camera.GetProjectionMatrix(stereoEye);
                var viewPosition = camera.GetCameraPosition4(stereoEye);

                var cbData       = new CBMeshInstanceData();
                var cbDataSubset = new CBSubsetData();

                var hdr      = frame.HdrBuffer.Surface;
                var depth    = frame.DepthBuffer.Surface;
                var gbuffer0 = frame.GBuffer0.Surface;
                var gbuffer1 = frame.GBuffer1.Surface;
                var feedback = frame.FeedbackBuffer.Surface;

                device.ResetStates();

                device.SetTargets(depth, hdr, gbuffer0, gbuffer1, feedback);
                device.PixelShaderSamplers[0] = SamplerState.LinearPointClamp;
                device.PixelShaderSamplers[1] = SamplerState.PointClamp;
                device.PixelShaderSamplers[2] = SamplerState.AnisotropicClamp;

                var instances = rw.Instances;

                if (instances.Any())
                {
                    device.PixelShaderResources[1] = rs.VTSystem.PageTable;
                    device.PixelShaderResources[2] = rs.VTSystem.PhysicalPages0;
                    device.PixelShaderResources[3] = rs.VTSystem.PhysicalPages1;
                    device.PixelShaderResources[4] = rs.VTSystem.PhysicalPages2;
                }

                //#warning INSTANSING!
                foreach (var instance in instances)
                {
                    if (!instance.Visible)
                    {
                        continue;
                    }

                    if (staticOnly && !instance.Static)
                    {
                        continue;
                    }

                    cbData.View           = view;
                    cbData.Projection     = projection;
                    cbData.World          = instance.World;
                    cbData.ViewPos        = viewPosition;
                    cbData.Color          = instance.Color;
                    cbData.ViewBounds     = new Vector4(hdr.Width, hdr.Height, hdr.Width, hdr.Height);
                    cbData.VTPageScaleRCP = rs.VTSystem.PageScaleRCP;

                    constBuffer.SetData(cbData);

                    device.PixelShaderConstants[0]  = constBuffer;
                    device.VertexShaderConstants[0] = constBuffer;
                    device.PixelShaderConstants[1]  = constBufferSubset;

                    device.SetupVertexInput(instance.vb, instance.ib);

                    if (instance.IsSkinned)
                    {
                        constBufferBones.SetData(instance.BoneTransforms);
                        device.VertexShaderConstants[3] = constBufferBones;
                    }

                    try {
                        device.PipelineState = factory[(int)(SurfaceFlags.GBUFFER | SurfaceFlags.RIGID)];


                        foreach (var subset in instance.Subsets)
                        {
                            var vt   = rw.VirtualTexture;
                            var rect = vt.GetTexturePosition(subset.Name);

                            cbDataSubset.Rectangle = new Vector4(rect.X, rect.Y, rect.Width, rect.Height);

                            constBufferSubset.SetData(cbDataSubset);
                            device.PixelShaderConstants[1] = constBufferSubset;

                            device.DrawIndexed(subset.PrimitiveCount * 3, subset.StartPrimitive * 3, 0);
                        }

                        rs.Counters.SceneDIPs++;
                    } catch (UbershaderException e) {
                        Log.Warning(e.Message);
                        ExceptionDialog.Show(e);
                    }
                }


                //
                //	downsample feedback buffer and readback it to virtual texture :
                //
                rs.Filter.StretchRect(frame.FeedbackBufferRB.Surface, frame.FeedbackBuffer, SamplerState.PointClamp);

                var feedbackBuffer = new VTAddress[HdrFrame.FeedbackBufferWidth * HdrFrame.FeedbackBufferHeight];
                frame.FeedbackBufferRB.GetFeedback(feedbackBuffer);
                rs.VTSystem.Update(feedbackBuffer, gameTime);
            }
        }
예제 #11
0
		/// <summary>
		/// Performs luminance measurement, tonemapping, applies bloom.
		/// </summary>
		/// <param name="target">LDR target.</param>
		/// <param name="hdrImage">HDR source image.</param>
		public void Render ( GameTime gameTime, RenderTargetSurface target, ShaderResource hdrImage, RenderWorld viewLayer )
		{
			var device	=	Game.GraphicsDevice;
			var filter	=	Game.RenderSystem.Filter;

			var settings	=	viewLayer.HdrSettings;

			//
			//	Rough downsampling of source HDR-image :
			//
			filter.StretchRect( averageLum.Surface, hdrImage, SamplerState.PointClamp );
			averageLum.BuildMipmaps();

			//
			//	Make bloom :
			//
			filter.StretchRect( viewLayer.Bloom0.Surface, hdrImage, SamplerState.LinearClamp );
			viewLayer.Bloom0.BuildMipmaps();

			filter.GaussBlur( viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 0 );
			filter.GaussBlur( viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 1 );
			filter.GaussBlur( viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 2 );
			filter.GaussBlur( viewLayer.Bloom0, viewLayer.Bloom1, settings.GaussBlurSigma, 3 );

			//
			//	Setup parameters :
			//
			var paramsData	=	new Params();
			paramsData.AdaptationRate		=	1 - (float)Math.Pow( 0.5f, gameTime.ElapsedSec / settings.AdaptationHalfLife );
			paramsData.LuminanceLowBound	=	settings.LuminanceLowBound;
			paramsData.LuminanceHighBound	=	settings.LuminanceHighBound;
			paramsData.KeyValue				=	settings.KeyValue;
			paramsData.BloomAmount			=	settings.BloomAmount;
			paramsData.DirtMaskLerpFactor	=	settings.DirtMaskLerpFactor;
			paramsData.DirtAmount			=	settings.DirtAmount;

			paramsCB.SetData( paramsData );
			device.PixelShaderConstants[0]	=	paramsCB;

			//
			//	Measure and adapt :
			//
			device.SetTargets( null, viewLayer.MeasuredNew );

			device.PixelShaderResources[0]	=	averageLum;
			device.PixelShaderResources[1]	=	viewLayer.MeasuredOld;

			device.PipelineState		=	factory[ (int)(Flags.MEASURE_ADAPT) ];
				
			device.Draw( 3, 0 );


			//
			//	Tonemap and compose :
			//
			device.SetTargets( null, target );

			device.PixelShaderResources[0]	=	hdrImage;// averageLum;
			device.PixelShaderResources[1]	=	viewLayer.MeasuredNew;// averageLum;
			device.PixelShaderResources[2]	=	viewLayer.Bloom0;// averageLum;
			device.PixelShaderResources[3]	=	settings.DirtMask1==null ? whiteTex.Srv : settings.DirtMask1.Srv;
			device.PixelShaderResources[4]	=	settings.DirtMask2==null ? whiteTex.Srv : settings.DirtMask2.Srv;
			device.PixelShaderSamplers[0]	=	SamplerState.LinearClamp;

			Flags op = Flags.LINEAR;
			if (settings.TonemappingOperator==TonemappingOperator.Filmic)   { op = Flags.FILMIC;   }
			if (settings.TonemappingOperator==TonemappingOperator.Linear)   { op = Flags.LINEAR;	 }
			if (settings.TonemappingOperator==TonemappingOperator.Reinhard) { op = Flags.REINHARD; }

			device.PipelineState		=	factory[ (int)(Flags.TONEMAPPING|op) ];
				
			device.Draw( 3, 0 );
			
			device.ResetStates();


			//	swap luminanice buffers :
			Misc.Swap( ref viewLayer.MeasuredNew, ref viewLayer.MeasuredOld );
		}
예제 #12
0
		/// <summary>
		/// Intializes graphics engine.
		/// </summary>
		public override void Initialize ()
		{
			whiteTexture	=	new DynamicTexture( this, 4,4, typeof(Color), false, false );
			whiteTexture.SetData( Enumerable.Range(0,16).Select( i => Color.White ).ToArray() );
			
			grayTexture		=	new DynamicTexture( this, 4,4, typeof(Color), false, false );
			grayTexture.SetData( Enumerable.Range(0,16).Select( i => Color.Gray ).ToArray() );

			blackTexture	=	new DynamicTexture( this, 4,4, typeof(Color), false, false );
			blackTexture.SetData( Enumerable.Range(0,16).Select( i => Color.Black ).ToArray() );

			flatNormalMap	=	new DynamicTexture( this, 4,4, typeof(Color), false, false );
			flatNormalMap.SetData( Enumerable.Range(0,16).Select( i => new Color(127,127,255,127) ).ToArray() );

			var baseIllum = new BaseIllum();
			defaultMaterial	=	baseIllum.CreateMaterialInstance(this, Game.Content);

			//	add default render world
			renderWorld	=	new RenderWorld(Game, Width, Height);
			AddLayer( renderWorld );
		}
예제 #13
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="camera"></param>
		/// <param name="depthBuffer"></param>
		/// <param name="hdrTarget"></param>
		/// <param name="diffuse"></param>
		/// <param name="specular"></param>
		/// <param name="normals"></param>
		internal void RenderGBuffer ( StereoEye stereoEye, Camera camera, HdrFrame frame, RenderWorld viewLayer )
		{		
			using ( new PixEvent("RenderGBuffer") ) {
				if (surfaceShader==null) {	
					return;
				}

				if (rs.SkipSceneRendering) {
					return;
				}

				var device		=	Game.GraphicsDevice;

				var view			=	camera.GetViewMatrix( stereoEye );
				var projection		=	camera.GetProjectionMatrix( stereoEye );
				var viewPosition	=	camera.GetCameraPosition4( stereoEye );

				var cbData		=	new CBMeshInstanceData();

				var hdr			=	frame.HdrBuffer.Surface;
				var depth		=	frame.DepthBuffer.Surface;
				var diffuse		=	frame.DiffuseBuffer.Surface;
				var specular	=	frame.SpecularBuffer.Surface;
				var normals		=	frame.NormalMapBuffer.Surface;
				var scattering	=	frame.ScatteringBuffer.Surface;

				device.ResetStates();

				device.SetTargets( depth, hdr, diffuse, specular, normals, scattering );
				device.PixelShaderSamplers[0]	= SamplerState.AnisotropicWrap ;

				var instances	=	viewLayer.Instances;

				//#warning INSTANSING!
				foreach ( var instance in instances ) {

					if (!instance.Visible) {
						continue;
					}

					cbData.View			=	view;
					cbData.Projection	=	projection;
					cbData.World		=	instance.World;
					cbData.ViewPos		=	viewPosition;
					
					constBuffer.SetData( cbData );

					device.PixelShaderConstants[0]	= constBuffer ;
					device.VertexShaderConstants[0]	= constBuffer ;

					device.SetupVertexInput( instance.vb, instance.ib );

					if (instance.IsSkinned) {
						constBufferBones.SetData( instance.BoneTransforms );
						device.VertexShaderConstants[3]	= constBufferBones ;
					}

					try {

						foreach ( var sg in instance.ShadingGroups ) {

							device.PipelineState	=	instance.IsSkinned ? sg.Material.GBufferSkinned : sg.Material.GBufferRigid;

							device.PixelShaderConstants[1]	= sg.Material.ConstantBufferParameters;
							device.PixelShaderConstants[2]	= sg.Material.ConstantBufferUVModifiers;
							device.VertexShaderConstants[1]	= sg.Material.ConstantBufferParameters;
							device.VertexShaderConstants[2]	= sg.Material.ConstantBufferUVModifiers;

							sg.Material.SetTextures( device );

							device.DrawIndexed( sg.IndicesCount, sg.StartIndex, 0 );

							rs.Counters.SceneDIPs++;
						}
					} catch ( UbershaderException e ) {
						Log.Warning( e.Message );					
						ExceptionDialog.Show( e );
					}
				}
			}
		}
예제 #14
0
		/// <summary>
		/// 
		/// </summary>
		void SetupGPUParameters ( float stepTime, RenderWorld renderWorld, Matrix view, Matrix projection, Flags flags )
		{
			var deltaTime		=	stepTime;
			var camera			=	renderWorld.Camera;
			var cameraMatrix	=	Matrix.Invert( view );

			//	kill particles by applying very large delta.
			if (requestKill) {
				deltaTime	=	float.MaxValue / 2;
				requestKill	=	false;
			}
			if (rs.FreezeParticles) {
				deltaTime = 0;
			}

			//	fill constant data :
			PrtParams param		=	new PrtParams();

			param.View				=	view;
			param.Projection		=	projection;
			param.MaxParticles		=	0;
			param.DeltaTime			=	deltaTime;
			param.CameraForward		=	new Vector4( cameraMatrix.Forward	, 0 );
			param.CameraRight		=	new Vector4( cameraMatrix.Right	, 0 );
			param.CameraUp			=	new Vector4( cameraMatrix.Up		, 0 );
			param.CameraPosition	=	new Vector4( cameraMatrix.TranslationVector	, 1 );
			param.Gravity			=	new Vector4( this.Gravity, 0 );
			param.MaxParticles		=	MaxSimulatedParticles;
			param.LinearizeDepthA	=	camera.LinearizeDepthScale;
			param.LinearizeDepthB	=	camera.LinearizeDepthBias;
			param.CocBias			=	renderWorld.DofSettings.CocBias;
			param.CocScale			=	renderWorld.DofSettings.CocScale;

			if (flags==Flags.INJECTION) {
				param.MaxParticles	=	injectionCount;
			}

			//	copy to gpu :
			paramsCB.SetData( param );

			//	set DeadListSize to prevent underflow:
			if (flags==Flags.INJECTION) {
				deadParticlesIndices.CopyStructureCount( paramsCB, Marshal.OffsetOf( typeof(PrtParams), "DeadListSize").ToInt32() );
			}
		}
예제 #15
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="rs"></param>
		internal ParticleSystem ( RenderSystem rs, RenderWorld renderWorld )
		{
			this.rs				=	rs;
			this.Game			=	rs.Game;
			this.renderWorld	=	renderWorld;

			Gravity	=	Vector3.Down * 9.80665f;

			paramsCB		=	new ConstantBuffer( Game.GraphicsDevice, typeof(PrtParams) );
			imagesCB		=	new ConstantBuffer( Game.GraphicsDevice, typeof(Vector4), MaxImages );

			injectionBuffer			=	new StructuredBuffer( Game.GraphicsDevice, typeof(Particle),	MaxInjectingParticles, StructuredBufferFlags.None );
			simulationBuffer		=	new StructuredBuffer( Game.GraphicsDevice, typeof(Particle),	MaxSimulatedParticles, StructuredBufferFlags.None );
			particleLighting		=	new StructuredBuffer( Game.GraphicsDevice, typeof(Vector4),		MaxSimulatedParticles, StructuredBufferFlags.None );
			sortParticlesBuffer		=	new StructuredBuffer( Game.GraphicsDevice, typeof(Vector2),		MaxSimulatedParticles, StructuredBufferFlags.None );
			deadParticlesIndices	=	new StructuredBuffer( Game.GraphicsDevice, typeof(uint),		MaxSimulatedParticles, StructuredBufferFlags.Append );

			rs.Game.Reloading += LoadContent;
			LoadContent(this, EventArgs.Empty);

			//	initialize dead list :
			var device = Game.GraphicsDevice;

			device.SetCSRWBuffer( 1, deadParticlesIndices, 0 );
			device.PipelineState	=	factory[ (int)Flags.INITIALIZE ];
			device.Dispatch( MathUtil.IntDivUp( MaxSimulatedParticles, BlockSize ) );
		}
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="view"></param>
        /// <param name="projection"></param>
        internal void RenderLighting(StereoEye stereoEye, Camera camera, HdrFrame hdrFrame, RenderWorld viewLayer, RenderTargetCube envLight)
        {
            using (new PixEvent("TiledLighting")) {
                var view       = camera.GetViewMatrix(stereoEye);
                var projection = camera.GetProjectionMatrix(stereoEye);

                var device = Game.GraphicsDevice;
                device.ResetStates();

                var width  = hdrFrame.HdrBuffer.Width;
                var height = hdrFrame.HdrBuffer.Height;


                ICSMController csmCtrl = viewLayer.LightSet.DirectLight.CSMController ?? csmController;

                int activeCascadeCount = Math.Min(cascadedShadowMap.CascadeCount, csmCtrl.GetActiveCascadeCount());


                //
                //	Setup compute shader parameters and states :
                //
                try {
                    var cbData  = new LightingParams();
                    var invView = Matrix.Invert(view);
                    var invVP   = Matrix.Invert(view * projection);
                    var viewPos = invView.TranslationVector;

                    cbData.DirectLightDirection = new Vector4(viewLayer.LightSet.DirectLight.Direction, 0);
                    cbData.DirectLightIntensity = viewLayer.LightSet.DirectLight.Intensity.ToVector4();
                    cbData.Projection           = projection;

                    cbData.CSMViewProjection0 = csmCtrl.GetShadowViewMatrix(0) * csmCtrl.GetShadowProjectionMatrix(0);
                    cbData.CSMViewProjection1 = csmCtrl.GetShadowViewMatrix(1) * csmCtrl.GetShadowProjectionMatrix(1);
                    cbData.CSMViewProjection2 = csmCtrl.GetShadowViewMatrix(2) * csmCtrl.GetShadowProjectionMatrix(2);
                    cbData.CSMViewProjection3 = csmCtrl.GetShadowViewMatrix(3) * csmCtrl.GetShadowProjectionMatrix(3);

                    cbData.View                  = view;
                    cbData.ViewPosition          = new Vector4(viewPos, 1);
                    cbData.InverseViewProjection = invVP;
                    cbData.CSMFilterRadius       = new Vector4(CSMFilterSize);

                    cbData.AmbientColor   = viewLayer.LightSet.AmbientLevel;
                    cbData.Viewport       = new Vector4(0, 0, width, height);
                    cbData.ShowCSLoadOmni = ShowOmniLightTileLoad ? 1 : 0;
                    cbData.ShowCSLoadEnv  = ShowEnvLightTileLoad  ? 1 : 0;
                    cbData.ShowCSLoadSpot = ShowSpotLightTileLoad ? 1 : 0;

                    cbData.CascadeCount = activeCascadeCount;
                    cbData.CascadeScale = 1.0f / (float)cascadedShadowMap.CascadeCount;

                    cbData.FogDensity = viewLayer.FogSettings.Density;


                    ComputeOmniLightsTiles(view, projection, viewLayer.LightSet);
                    ComputeSpotLightsTiles(view, projection, viewLayer.LightSet);
                    ComputeEnvLightsTiles(view, projection, viewLayer.LightSet);
                    ComputeDecalTiles(view, projection, viewLayer.LightSet);


                    //
                    //	set states :
                    //
                    device.SetTargets(null, hdrFrame.HdrBuffer.Surface);

                    lightingCB.SetData(cbData);

                    device.ComputeShaderSamplers[0] = SamplerState.PointClamp;
                    device.ComputeShaderSamplers[1] = SamplerState.LinearClamp;
                    device.ComputeShaderSamplers[2] = SamplerState.ShadowSampler;
                    device.ComputeShaderSamplers[3] = SamplerState.LinearPointWrap;

                    device.ComputeShaderResources[0]  = hdrFrame.GBuffer0;
                    device.ComputeShaderResources[1]  = hdrFrame.GBuffer1;
                    device.ComputeShaderResources[2]  = rs.Sky.SkyCube;
                    device.ComputeShaderResources[4]  = hdrFrame.DepthBuffer;
                    device.ComputeShaderResources[5]  = cascadedShadowMap.ColorBuffer;
                    device.ComputeShaderResources[6]  = spotColor;
                    device.ComputeShaderResources[7]  = viewLayer.LightSet.SpotAtlas == null ? rs.WhiteTexture.Srv : viewLayer.LightSet.SpotAtlas.Texture.Srv;
                    device.ComputeShaderResources[8]  = omniLightBuffer;
                    device.ComputeShaderResources[9]  = spotLightBuffer;
                    device.ComputeShaderResources[10] = envLightBuffer;
                    device.ComputeShaderResources[11] = rs.SsaoFilter.OcclusionMap;
                    device.ComputeShaderResources[12] = viewLayer.RadianceCache;
                    device.ComputeShaderResources[13] = viewLayer.ParticleSystem.SimulatedParticles;
                    device.ComputeShaderResources[14] = cascadedShadowMap.ParticleShadow;
                    device.ComputeShaderResources[15] = envLut.Srv;
                    device.ComputeShaderResources[16] = decalBuffer;
                    device.ComputeShaderResources[17] = viewLayer.LightSet.DecalAtlas == null ? rs.WhiteTexture.Srv : viewLayer.LightSet.DecalAtlas.Texture.Srv;

                    device.ComputeShaderConstants[0] = lightingCB;

                    device.SetCSRWTexture(0, hdrFrame.LightAccumulator.Surface);
                    device.SetCSRWBuffer(1, viewLayer.ParticleSystem.ParticleLighting);

                    //
                    //	Dispatch solids :
                    //
                    using (new PixEvent("Solid Lighting")) {
                        device.PipelineState = factory[(int)LightingFlags.SOLIDLIGHTING];
                        device.Dispatch(MathUtil.IntDivUp(width, BlockSizeX), MathUtil.IntDivUp(height, BlockSizeY), 1);
                    }

                    //
                    //	Dispatch particles :
                    //
                    using (new PixEvent("Particle Lighting")) {
                        if (stereoEye != StereoEye.Right && !rs.SkipParticles)
                        {
                            int threadGroupCount = MathUtil.IntDivUp(ParticleSystem.MaxSimulatedParticles, ParticleSystem.BlockSize);
                            device.PipelineState = factory[(int)LightingFlags.PARTICLES];
                            device.Dispatch(threadGroupCount, 1, 1);
                        }
                    }
                } catch (UbershaderException e) {
                    Log.Warning("{0}", e.Message);
                }


                //
                //	Add accumulated light  :
                //
                rs.Filter.OverlayAdditive(hdrFrame.HdrBuffer.Surface, hdrFrame.LightAccumulator);

                //	Uncomment to enable SSS :
                                #if false
                rs.Filter.GaussBlur(hdrFrame.SSSAccumulator, hdrFrame.LightAccumulator, 5, 0);
                rs.Filter.OverlayAdditive(hdrFrame.HdrBuffer.Surface, hdrFrame.SSSAccumulator);
                                #endif

                device.ResetStates();


                if (rs.ShowLightCounters)
                {
                    var ls = viewLayer.LightSet;
                    Log.Message("lights: {0,5} omni {1,5} spot {2,5} env", ls.OmniLights.Count, ls.SpotLights.Count, ls.EnvLights.Count);
                }
            }
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="?"></param>
		internal void RenderShadows ( RenderWorld renderWorld, LightSet lightSet )
		{
			var device = Game.GraphicsDevice;
			var camera		=	renderWorld.Camera;
			var instances	=	renderWorld.Instances;

			if (SkipShadows) {
				return;
			}


			CheckShadowSize();


			csmController.ComputeMatricies( 
				camera.GetViewMatrix(StereoEye.Mono), 
				lightSet.DirectLight.Direction, 
				cascadedShadowMap.CascadeSize,
				this.SplitSize,
				this.SplitOffset,
				this.SplitFactor,
				this.CSMProjectionDepth );


			ICSMController csmCtrl	=	lightSet.DirectLight.CSMController ?? csmController;


			int activeCascadeCount	=	Math.Min( cascadedShadowMap.CascadeCount, csmCtrl.GetActiveCascadeCount() );


			using (new PixEvent("Cascaded Shadow Maps")) {

				Game.GraphicsDevice.ResetStates();
			
				cascadedShadowMap.Clear();

				for (int i=0; i<activeCascadeCount; i++) {

					var context = new ShadowContext();
					context.ShadowView			=	csmCtrl.GetShadowViewMatrix( i );
					context.ShadowProjection	=	csmCtrl.GetShadowProjectionMatrix( i );
					context.ShadowViewport		=	cascadedShadowMap.GetSplitViewport( i );
					context.FarDistance			=	1;
					context.SlopeBias			=	CSMSlopeBias;
					context.DepthBias			=	CSMDepthBias;
					context.ColorBuffer			=	cascadedShadowMap.ColorBuffer.Surface;
					context.DepthBuffer			=	cascadedShadowMap.DepthBuffer.Surface;

					Game.RenderSystem.SceneRenderer.RenderShadowMapCascade( context, instances );
				}
			}



			using (new PixEvent("Particle Shadows")) {
			
				for (int i=0; i<activeCascadeCount; i++) {

					var viewport = cascadedShadowMap.GetSplitViewport(i);
					var colorBuffer = cascadedShadowMap.ParticleShadow.Surface;
					var depthBuffer = cascadedShadowMap.DepthBuffer.Surface;
					var viewMatrix	= csmController.GetShadowViewMatrix( i );
					var projMatrix	= csmController.GetShadowProjectionMatrix( i );

					renderWorld.ParticleSystem.RenderShadow( new GameTime(), viewport, viewMatrix, projMatrix, colorBuffer, depthBuffer );
				}
			}



			using (new PixEvent("Spotlight Shadow Maps")) {

				device.Clear( spotDepth.Surface, 1, 0 );
				device.Clear( spotColor.Surface, Color4.White );
				int index = 0;

				foreach ( var spot in lightSet.SpotLights ) {

					var smSize	= SpotShadowSize;
					var context = new ShadowContext();
					var dx      = index % 4;
					var dy		= index / 4;
					var far		= spot.Projection.GetFarPlaneDistance();

					index++;

					context.ShadowView			=	spot.SpotView;
					context.ShadowProjection	=	spot.Projection;
					context.ShadowViewport		=	new Viewport( smSize * dx, smSize * dy, smSize, smSize );
					context.FarDistance			=	far;
					context.SlopeBias			=	SpotSlopeBias;
					context.DepthBias			=	SpotDepthBias;
					context.ColorBuffer			=	spotColor.Surface;
					context.DepthBuffer			=	spotDepth.Surface;

					Game.RenderSystem.SceneRenderer.RenderShadowMapCascade( context, instances );
				}
			}
		}
예제 #18
0
		/// <summary>
		/// 
		/// </summary>
		public override void Initialize ()
		{
			debugFont		=	Game.Content.Load<DiscTexture>("conchars");

			var bounds		=	Game.RenderSystem.DisplayBounds;
			masterView		=	Game.RenderSystem.RenderWorld;


			Game.RenderSystem.RemoveLayer(masterView);

			viewLayer = new RenderLayer(Game);
			Game.RenderSystem.AddLayer(viewLayer);

			//Game.RenderSystem.DisplayBoundsChanged += (s,e) => {
			//	masterView.Resize( Game.RenderSystem.DisplayBounds.Width, Game.RenderSystem.DisplayBounds.Height );
			//};

			targetTexture		=	new TargetTexture(Game.RenderSystem, bounds.Width, bounds.Height, TargetFormat.LowDynamicRange );

			testLayer	=	new SpriteLayer( Game.RenderSystem, 1024 );
			uiLayer		=	new SpriteLayer( Game.RenderSystem, 1024 );

			tiles = new TilesGisLayer(Game, viewLayer.GlobeCamera);
			viewLayer.GisLayers.Add(tiles);

			text = new TextGisLayer(Game, 100, viewLayer.GlobeCamera);
			//masterView.GisLayers.Add(text);

			//masterView.SpriteLayers.Add( testLayer );
			//masterView.SpriteLayers.Add( text.TextSpriteLayer );
			viewLayer.SpriteLayers.Add(console.ConsoleSpriteLayer);

			
			text.GeoTextArray[0] = new TextGisLayer.GeoText {
				Color	= Color.Red,
				Text	= "Arrow",
				LonLat	= DMathUtil.DegreesToRadians(new DVector2(30.306473, 59.944082))
			};

			text.GeoTextArray[1] = new TextGisLayer.GeoText {
				Color	= Color.Teal,
				Text	= "Park",
				LonLat	= DMathUtil.DegreesToRadians(new DVector2(30.313897, 59.954623))
			};

			Game.Keyboard.KeyDown += Keyboard_KeyDown;

			LoadContent();

			Game.Reloading += (s,e) => LoadContent();


			var r = new Random();

			//pointsCPU = new PointsGisLayerCPU(Game, 8000000);
			//pointsCPU.TextureAtlas = Game.Content.Load<Texture2D>("Zombie");
			//
			//for (int i = 0; i < pointsCPU.PointsCountToDraw; i++) {
			//	pointsCPU.AddPoint(i, DMathUtil.DegreesToRadians(new DVector2(30.240383 + r.NextDouble(-1, 1) * 0.1, 59.944007 - r.NextDouble(-1, 1) * 0.05)), 0, 0.01f);
			//}
			//pointsCPU.UpdatePointsBuffer();
			//viewLayer.GisLayers.Add(pointsCPU);
			

			pointsGPU = new PointsGisLayer(Game, 1677000, true);
			pointsGPU.TextureAtlas = Game.Content.Load<Texture2D>("Zombie");
			pointsGPU.ImageSizeInAtlas = new Vector2(36, 36);
			
			for (int i = 0; i < pointsGPU.PointsCountToDraw; i++) {
				var pos = DMathUtil.DegreesToRadians(new DVector2(30.240383 + r.NextDouble(-1, 1)*0.2, 59.944007 - r.NextDouble(-1, 1)*0.1));
				pointsGPU.PointsCpu[i] = new Gis.GeoPoint {
					Lon = pos.X,
					Lat = pos.Y,
					Color = Color4.White,
					Tex0 = new Vector4(0, 0, 0.02f, 0)
				};
			}
			pointsGPU.UpdatePointsBuffer();
			viewLayer.GisLayers.Add(pointsGPU);


			viewLayer.GlobeCamera.GoToPlace(GlobeCamera.Places.SaintPetersburg_VO);
			viewLayer.GlobeCamera.CameraDistance = GeoHelper.EarthRadius + 5;
		}
예제 #19
0
		/// <summary>
		/// Applies DOF effect
		/// </summary>
		public void Render ( GameTime gameTime, RenderTarget2D temp, RenderTarget2D hdrImage, ShaderResource depthBuffer, RenderWorld renderWorld )
		{
			if (!renderWorld.DofSettings.Enabled) {
				return;
			}

			var device	=	Game.GraphicsDevice;
			var filter	=	Game.RenderSystem.Filter;

			device.ResetStates();


			//
			//	Setup parameters :
			//
			var paramsData	=	new Params();
			paramsData.LinearDepthBias	=	renderWorld.Camera.LinearizeDepthBias;
			paramsData.LinearDepthScale	=	renderWorld.Camera.LinearizeDepthScale;	
			paramsData.CocBias			=	renderWorld.DofSettings.CocBias;
			paramsData.CocScale			=	renderWorld.DofSettings.CocScale;

			paramsCB.SetData( paramsData );
			device.PixelShaderConstants[0]	=	paramsCB;

			//
			//	Compute COC and write it in alpha channel :
			//
			device.SetTargets( (DepthStencilSurface)null, hdrImage.Surface );

			device.PixelShaderResources[0]	=	depthBuffer;
			device.PipelineState			=	factory[ (int)(Flags.COC_TO_ALPHA) ];
				
			device.Draw( 3, 0 );


			//
			//	Perform DOF :
			//
			device.SetTargets( null, temp );

			device.PixelShaderResources[0]	=	hdrImage;
			device.PixelShaderSamplers[0]	=	SamplerState.LinearClamp;
			device.VertexShaderResources[0]	=	hdrImage;
			device.VertexShaderSamplers[0]	=	SamplerState.LinearClamp;

			device.PipelineState			=	factory[ (int)(Flags.DEPTH_OF_FIELD) ];
				
			device.Draw( 3, 0 );
			
			device.ResetStates();


			//
			//	Copy DOFed image back to source :
			//
			filter.Copy( hdrImage.Surface, temp );
		}
예제 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="?"></param>
        internal void RenderShadows(RenderWorld renderWorld, LightSet lightSet)
        {
            var device    = Game.GraphicsDevice;
            var camera    = renderWorld.Camera;
            var instances = renderWorld.Instances;

            if (SkipShadows)
            {
                return;
            }


            CheckShadowSize();


            csmController.ComputeMatricies(
                camera.GetViewMatrix(StereoEye.Mono),
                lightSet.DirectLight.Direction,
                cascadedShadowMap.CascadeSize,
                this.SplitSize,
                this.SplitOffset,
                this.SplitFactor,
                this.CSMProjectionDepth);


            ICSMController csmCtrl = lightSet.DirectLight.CSMController ?? csmController;


            int activeCascadeCount = Math.Min(cascadedShadowMap.CascadeCount, csmCtrl.GetActiveCascadeCount());


            using (new PixEvent("Cascaded Shadow Maps")) {
                Game.GraphicsDevice.ResetStates();

                cascadedShadowMap.Clear();

                for (int i = 0; i < activeCascadeCount; i++)
                {
                    var context = new ShadowContext();
                    context.ShadowView       = csmCtrl.GetShadowViewMatrix(i);
                    context.ShadowProjection = csmCtrl.GetShadowProjectionMatrix(i);
                    context.ShadowViewport   = cascadedShadowMap.GetCascadeViewport(i);
                    context.FarDistance      = 1;
                    context.SlopeBias        = CSMSlopeBias;
                    context.DepthBias        = CSMDepthBias;
                    context.ColorBuffer      = cascadedShadowMap.ColorBuffer.Surface;
                    context.DepthBuffer      = cascadedShadowMap.DepthBuffer.Surface;

                    Game.RenderSystem.SceneRenderer.RenderShadowMapCascade(context, instances);
                }
            }



            using (new PixEvent("Particle Shadows")) {
                for (int i = 0; i < activeCascadeCount; i++)
                {
                    var viewport    = cascadedShadowMap.GetCascadeViewport(i);
                    var colorBuffer = cascadedShadowMap.ParticleShadow.Surface;
                    var depthBuffer = cascadedShadowMap.DepthBuffer.Surface;
                    var viewMatrix  = csmController.GetShadowViewMatrix(i);
                    var projMatrix  = csmController.GetShadowProjectionMatrix(i);

                    renderWorld.ParticleSystem.RenderShadow(new GameTime(), viewport, viewMatrix, projMatrix, colorBuffer, depthBuffer);
                }
            }



            using (new PixEvent("Spotlight Shadow Maps")) {
                device.Clear(spotDepth.Surface, 1, 0);
                device.Clear(spotColor.Surface, Color4.White);
                int index = 0;

                foreach (var spot in lightSet.SpotLights)
                {
                    var smSize  = SpotShadowSize;
                    var context = new ShadowContext();
                    var dx      = index % 4;
                    var dy      = index / 4;
                    var far     = spot.Projection.GetFarPlaneDistance();

                    index++;

                    context.ShadowView       = spot.SpotView;
                    context.ShadowProjection = spot.Projection;
                    context.ShadowViewport   = new Viewport(smSize * dx, smSize * dy, smSize, smSize);
                    context.FarDistance      = far;
                    context.SlopeBias        = spot.SlopeBias;
                    context.DepthBias        = spot.DepthBias;
                    context.ColorBuffer      = spotColor.Surface;
                    context.DepthBuffer      = spotDepth.Surface;

                    Game.RenderSystem.SceneRenderer.RenderShadowMapCascade(context, instances);
                }
            }
        }
예제 #21
0
		/// <summary>
		/// 
		/// </summary>
		public override void Initialize ()
		{
			debugFont		=	Game.Content.Load<DiscTexture>("conchars");
			//videoPlayer	=	new VideoPlayer();
			//video		=	new Video(@"C:\infection_demo.wmv");//*/
			////video		=	GameEngine.Content.Load<Video>("infection_demo");
			//video		=	new Video(File.ReadAllBytes(@"C:\infection_demo.wmv"));//*/

			//var mtrl		=	GameEngine.Content.Load<Material>("testMtrl");

			var bounds		=	Game.RenderSystem.DisplayBounds;
			masterView		=	Game.RenderSystem.RenderWorld;

			Game.RenderSystem.DisplayBoundsChanged += (s,e) => {
				masterView.Resize( Game.RenderSystem.DisplayBounds.Width, Game.RenderSystem.DisplayBounds.Height );
				//Log.Warning("{0} {1}", GameEngine.GraphicsEngine.DisplayBounds.Width, GameEngine.GraphicsEngine.DisplayBounds.Height);
			};

			targetTexture		=	new TargetTexture(Game.RenderSystem, bounds.Width, bounds.Height, TargetFormat.LowDynamicRange );
			//masterView.Target	=	targetTexture;

			testLayer	=	new SpriteLayer( Game.RenderSystem, 1024 );
			uiLayer		=	new SpriteLayer( Game.RenderSystem, 1024 );
			texture		=	Game.Content.Load<DiscTexture>( "lena" );

			masterView.SkySettings.SunPosition			=	new Vector3(20,30,40);
			masterView.SkySettings.SunLightIntensity	=	50;
			masterView.SkySettings.SkyTurbidity			=	3;

			masterView.LightSet.SpotAtlas				=	Game.Content.Load<TextureAtlas>("spots/spots");
			masterView.LightSet.DirectLight.Direction	=	masterView.SkySettings.SunLightDirection;
			masterView.LightSet.DirectLight.Intensity	=	masterView.SkySettings.SunLightColor;
			masterView.LightSet.DirectLight.Enabled		=	true;
			masterView.LightSet.AmbientLevel			=	Color4.Zero;
			//masterView.LightSet.AmbientLevel			=	masterView.SkySettings.AmbientLevel;

			masterView.LightSet.EnvLights.Add( new EnvLight( new Vector3(0,4,-10), 1,  500 ) );

			//masterView.LightSet.EnvLights.Add( new EnvLight( new Vector3(0,4,-10), 1,  15 ) );
			//masterView.LightSet.EnvLights.Add( new EnvLight( new Vector3(0,4, 10), 1, 15 ) );


			var rand = new Random();

			/*for (int i=0; i<64; i++) {
				var light = new OmniLight();
				light.Position		=	new Vector3( 8*(i/8-4), 4, 8*(i%8-4) );
				light.RadiusInner	=	1;
				light.RadiusOuter	=	8;
				light.Intensity		=	rand.NextColor4() * 100;
				masterView.LightSet.OmniLights.Add( light );
			} //*/
														 
			/*for (int i=0; i<256; i++) {
				var light = new EnvLight();
				light.Position		=	new Vector3( 7*(i/16-8), 6, 7*(i%16-8) );
				light.RadiusInner	=	2;
				light.RadiusOuter	=	8;
				masterView.LightSet.EnvLights.Add( light );
			} //*/

			fireLight	=	new OmniLight();
			fireLight.Position	=	Vector3.UnitZ * (-10) + Vector3.UnitY * 5 + Vector3.UnitX * 20;
			fireLight.RadiusOuter	=	7;
			fireLight.Intensity		=	new Color4(249, 172, 61, 0)/2;

			masterView.LightSet.OmniLights.Add( fireLight );
			


			masterView.SpriteLayers.Add( console.ConsoleSpriteLayer );
			masterView.SpriteLayers.Add( uiLayer );
			masterView.SpriteLayers.Add( testLayer );


			Game.Keyboard.KeyDown += Keyboard_KeyDown;

			LoadContent();

			Game.Reloading += (s,e) => LoadContent();

			Game.Touch.Tap			+= vector2 => System.Console.WriteLine("You just perform tap gesture at point: " + vector2);
			Game.Touch.DoubleTap	+= vector2 => System.Console.WriteLine("You just perform double tap gesture at point: " + vector2);
			Game.Touch.SecondaryTap += vector2 => System.Console.WriteLine("You just perform secondary tap gesture at point: " + vector2);
			Game.Touch.Manipulate	+= (center, delta, scale) => System.Console.WriteLine("You just perform touch manipulation: " + center + "	" + delta + "	" + scale);
		}
예제 #22
0
        /// <summary>
        /// Applies DOF effect
        /// </summary>
        public void Render(GameTime gameTime, RenderTarget2D temp, RenderTarget2D hdrImage, ShaderResource depthBuffer, RenderWorld renderWorld)
        {
            if (!renderWorld.DofSettings.Enabled)
            {
                return;
            }

            var device = Game.GraphicsDevice;
            var filter = Game.RenderSystem.Filter;

            device.ResetStates();


            //
            //	Setup parameters :
            //
            var paramsData = new Params();

            paramsData.LinearDepthBias  = renderWorld.Camera.LinearizeDepthBias;
            paramsData.LinearDepthScale = renderWorld.Camera.LinearizeDepthScale;
            paramsData.CocBias          = renderWorld.DofSettings.CocBias;
            paramsData.CocScale         = renderWorld.DofSettings.CocScale;

            paramsCB.SetData(paramsData);
            device.PixelShaderConstants[0] = paramsCB;

            //
            //	Compute COC and write it in alpha channel :
            //
            device.SetTargets((DepthStencilSurface)null, hdrImage.Surface);

            device.PixelShaderResources[0] = depthBuffer;
            device.PipelineState           = factory[(int)(Flags.COC_TO_ALPHA)];

            device.Draw(3, 0);


            //
            //	Perform DOF :
            //
            device.SetTargets(null, temp);

            device.PixelShaderResources[0]  = hdrImage;
            device.PixelShaderSamplers[0]   = SamplerState.LinearClamp;
            device.VertexShaderResources[0] = hdrImage;
            device.VertexShaderSamplers[0]  = SamplerState.LinearClamp;

            device.PipelineState = factory[(int)(Flags.DEPTH_OF_FIELD)];

            device.Draw(3, 0);

            device.ResetStates();


            //
            //	Copy DOFed image back to source :
            //
            filter.Copy(hdrImage.Surface, temp);
        }