public static void Register() {
		style = Settings.GetChoice("style");
		OnScreenInterface.Register(new OSIBossHPBar(),OnScreenInterface.LAYER_INTERFACE_SCREEN);
		
		if (style == "circular_bottomleft") {
			dss1 = new DepthStencilState {
				StencilEnable = true,
				StencilFunction = CompareFunction.Equal,
				StencilPass = StencilOperation.Increment,
				ReferenceStencil = 0,
				DepthBufferEnable = false,
			};
			bs1 = new BlendState();
			bs1.ColorWriteChannels = ColorWriteChannels.None;
			
			dss2 = new DepthStencilState {
				StencilEnable = true,
				StencilFunction = CompareFunction.NotEqual,
				StencilPass = StencilOperation.Keep,
				ReferenceStencil = 0,
				DepthBufferEnable = false,
			};
			
			rt = new RenderTarget2D(
				Config.mainInstance.graphics.GraphicsDevice,
				1920,
				96,
				false,Config.mainInstance.graphics.GraphicsDevice.DisplayMode.Format,DepthFormat.Depth24Stencil8
			);
			sb = new SpriteBatch(Config.mainInstance.graphics.GraphicsDevice);
		}
	}
 public static void Apply(vec4 cameraPos, float cameraAspect, Texture2D Current, RenderTarget2D Output)
 {
     GridHelper.GraphicsDevice.SetRenderTarget(Output);
     GridHelper.GraphicsDevice.Clear(Color.Transparent);
     Using(cameraPos, cameraAspect, Current);
     GridHelper.DrawGrid();
 }
        private void InitializeTargets()
        {
            PresentationParameters pp = _engine.GraphicsDevice.PresentationParameters;

            _diffuseTarget = new RenderTarget2D(_engine.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
            _normalTarget = new RenderTarget2D(_engine.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
            _lightingTarget = new RenderTarget2D(_engine.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
            _combineTarget = new RenderTarget2D(_engine.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
        }
示例#4
0
        /// <summary>
        /// Load content
        /// </summary>
        public void CreateTargets()
        {
            var vp		=	GraphicsDevice.DisplayBounds;

            SafeDispose( ref hdrTarget );
            SafeDispose( ref ldrTarget );

            hdrTarget	=	new RenderTarget2D( GraphicsDevice, ColorFormat.Rgba16F, vp.Width, vp.Height, true );
            ldrTarget	=	new RenderTarget2D( GraphicsDevice, ColorFormat.Rgba8,   vp.Width, vp.Height, true );
        }
示例#5
0
		/// <summary>
		/// Create target texture with specified size and format
		/// </summary>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="format"></param>
		internal TargetTexture ( RenderTarget2D renderTarget )
		{
			createdFromRT	=	true;

			this.Width	=	renderTarget.Width;
			this.Height	=	renderTarget.Height;
			this.Format	=	TargetFormat.LowDynamicRange;

			RenderTarget	=	renderTarget; 
			Srv				=	RenderTarget;
		}
示例#6
0
		/// <summary>
		/// /
		/// </summary>
		public override void Initialize ()
		{
			averageLum	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba16F, 256,256, true, false );
			paramsCB	=	new ConstantBuffer( Game.GraphicsDevice, typeof(Params) );
			whiteTex	=	new DynamicTexture( Game.RenderSystem, 4,4, typeof(Color), false, false);
			whiteTex.SetData( Enumerable.Range(0,16).Select( i=> Color.White ).ToArray() );

			LoadContent();

			Game.Reloading += (s,e) => LoadContent();
		}
示例#7
0
        public Renderer(ref GraphicsDeviceManager graphics, int frameWidth, int frameHeight)
        {
            graphics.PreferredBackBufferWidth = frameWidth;
            graphics.PreferredBackBufferHeight = frameHeight;
            graphics.ApplyChanges();

            this.spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
            this.lightTarget = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
            this.lightBlockerTarget = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
            this.debugTarget = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);

            this.SetAmbientLight(graphics, 1);
        }
示例#8
0
		public HdrFrame ( Game game, int width, int height )
		{
			HdrBuffer			=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba16F,		width,	height,	false, false );
			LightAccumulator	=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba16F,		width,	height,	false, true );
			SSSAccumulator		=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba16F,		width,	height,	false, true );
			DepthBuffer			=	new DepthStencil2D( game.GraphicsDevice, DepthFormat.D24S8,			width,	height,	1 );
			DiffuseBuffer		=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba8_sRGB,	width,	height,	false, false );
			SpecularBuffer 		=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba8_sRGB,	width,	height,	false, false );
			NormalMapBuffer		=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgb10A2,		width,	height,	false, false );
			ScatteringBuffer	=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba8_sRGB,	width,	height,	false, false );
			SSAOBuffer			=	new RenderTarget2D( game.GraphicsDevice, ColorFormat.Rgba8,			width,	height, false, false );

			Clear();
		}
示例#9
0
        /// <summary>
        /// /
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            averageLum	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba16F, 256,256, true, false );
            measuredOld	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba32F,   1,  1 );
            measuredNew	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba32F,   1,  1 );
            paramsCB	=	new ConstantBuffer( Game.GraphicsDevice, typeof(Params) );

            CreateTargets();
            LoadContent();

            Game.GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateTargets();
            Game.Reloading += (s,e) => LoadContent();
        }
示例#10
0
		/// <summary>
		/// Create target texture with specified size and format
		/// </summary>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="format"></param>
		public TargetTexture ( RenderSystem rs, int width, int height, TargetFormat format )
		{
			this.Width	=	width;
			this.Height	=	height;
			this.Format	=	format;

			var clrFrmt	=	ColorFormat.Unknown;
			var samples	=	1;

			switch (format) {
				case TargetFormat.LowDynamicRange		: clrFrmt = ColorFormat.Rgba8;	break;
				case TargetFormat.LowDynamicRangeMSAA	: clrFrmt = ColorFormat.Rgba8;	samples = 4; break;
				case TargetFormat.HighDynamicRange		: clrFrmt = ColorFormat.Rgba16F;	break;
				default: throw new ArgumentException("format");
			}

			RenderTarget	=	new RenderTarget2D( rs.Device, clrFrmt, width, height, samples ); 
			Srv	=	RenderTarget;
		}	
示例#11
0
		public HeatMapLayer(Game engine, Gis.GeoPoint[] points, int[] indeces, int mapDimX, int mapDimY, bool isDynamic = false) : base(engine)
		{
			Initialize(points, indeces, isDynamic);

			factory = shader.CreateFactory( typeof(PolyFlags), Primitive.TriangleList, VertexInputElement.FromStructure<Gis.GeoPoint>(), BlendState.AlphaBlend, RasterizerState.CullNone, DepthStencilState.None);

			MapDimX = mapDimX;
			MapDimY = mapDimY;

			HeatTexture = new Texture2D(Game.GraphicsDevice, MapDimX, MapDimY, ColorFormat.R32F, false);
			Temp		= new RenderTarget2D(Game.GraphicsDevice, ColorFormat.R32F, MapDimX, MapDimY, true);
			FirstFinal	= new RenderTarget2D(Game.GraphicsDevice, ColorFormat.R32F, MapDimX, MapDimY, true);
			SecondFinal = new RenderTarget2D(Game.GraphicsDevice, ColorFormat.R32F, MapDimX, MapDimY, true);

			Final	= SecondFinal;
			Prev	= FirstFinal;

			Data = new float[MapDimX * MapDimY];

			//HeatMapPalettes		= new Texture2D[1];
			//HeatMapPalettes[0]	= Game.Content.Load<Texture2D>("palette");
			Palette = Game.Content.Load<Texture2D>("palette");

			//cb			= new ConstantBuffer(Game.GraphicsDevice, typeof(ConstData));
			//constData	= new ConstData();

			Flags = (int)(PolyFlags.PIXEL_SHADER | PolyFlags.VERTEX_SHADER | PolyFlags.DRAW_HEAT);

			blurFactory = shader.CreateFactory( typeof(PolyFlags), Primitive.TriangleList,
					null,
					BlendState.AlphaBlend,
					RasterizerState.CullNone,
					DepthStencilState.None);

			MaxHeatMapLevel = 100;
			MinHeatMapLevel = 0;
			HeatMapTransparency = 1.0f;
		}
示例#12
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="left">Left source buffer</param>
		/// <param name="right">Right source buffer</param>
		/// <param name="leftResolved">Buffer to resolve left MSAA buffer. (NULL if left buffer is not MSAA buffer)</param>
		/// <param name="rightResolved">Buffer to resolve right MSAA buffer. (NULL if right buffer is not MSAA buffer)</param>
		/// <param name="destination">Target buffer</param>
		/// <param name="mode">Ubershader flag</param>
		protected void MergeStereoBuffers ( RenderTarget2D left, RenderTarget2D right, RenderTarget2D leftResolved, RenderTarget2D rightResolved, RenderTarget2D destination, Flags flag )
		{
			device.ResetStates();

			device.SetTargets( null, destination );

			if (leftResolved!=null) {
				device.Resolve( left, leftResolved );
			} 
			if (rightResolved!=null) {
				device.Resolve( right, rightResolved );
			} 


			device.PipelineState		=	factory[ (int)flag ];

			device.PixelShaderSamplers[0]	=	SamplerState.LinearClamp;
			device.PixelShaderResources[0]	=	leftResolved  == null ? left  : leftResolved;
			device.PixelShaderResources[1]	=	rightResolved == null ? right : rightResolved;

			device.SetupVertexInput( null, null, null );
			device.Draw( 3, 0 );
		}
示例#13
0
        public void RadialBlur( RenderTargetSurface dst, RenderTarget2D src, Vector2 blurPoint, float offset, float size )
        {
            SetDefaultRenderStates();

            var data = new Vector4(blurPoint.X, blurPoint.Y, offset, size);
            radialDataCB.SetData(data);

            using( new PixEvent() ) {

                rs.SetTargets( null, dst );
                SetViewport(dst);

                rs.PipelineState			=	factory[ (int)ShaderFlags.RADIAL_BLUR ];
                rs.VertexShaderResources[0] =	src;
                rs.PixelShaderResources[0]	=	src;
                rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;
                rs.PixelShaderConstants[0]	=	radialDataCB;
                rs.VertexShaderConstants[0] =	radialDataCB;

                rs.Draw( 3, 0 );
            }
            rs.ResetStates();
        }
		/// <summary>
		/// 
		/// </summary>
		public override void CreateDisplayResources ()
		{
			base.CreateDisplayResources();

			backbufferColor = new RenderTarget2D(device, swapChain.GetBackBuffer<D3D.Texture2D>(0));

			int ms	= backbufferColor.SampleCount;
			int w	= backbufferColor.Width;
			int h	= backbufferColor.Height;

			backbufferColor1	=	new RenderTarget2D( device, ColorFormat.Rgba8, w, h, ms );
			backbufferDepth1	=	new DepthStencil2D( device, DepthFormat.D24S8, w, h, ms );
			backbufferColor2	=	new RenderTarget2D( device, ColorFormat.Rgba8, w, h, ms );
			backbufferDepth2	=	new DepthStencil2D( device, DepthFormat.D24S8, w, h, ms );

			if (ms>1) {
				backbufferColor1Resolved	=	new RenderTarget2D( device, ColorFormat.Rgba8, w, h );
				backbufferColor2Resolved	=	new RenderTarget2D( device, ColorFormat.Rgba8, w, h );
			}
		}
示例#15
0
        void CheckRenderTargetSupport()
        {
            RenderTarget2D temp;

            if (_supersample == 16)
            {
                try
                {
                    temp = new RenderTarget2D(GraphicsDevice, 1, 1, 1, SurfaceFormat.Vector4, MultiSampleType.SixteenSamples, 0);
                    GraphicsDevice.PresentationParameters.MultiSampleType    = MultiSampleType.SixteenSamples;
                    GraphicsDevice.PresentationParameters.MultiSampleQuality = 0;
                }
                catch (InvalidOperationException e)
                {
                    _supersample = 8;
                }
            }
            if (_supersample == 8)
            {
                try
                {
                    temp = new RenderTarget2D(GraphicsDevice, 1, 1, 1, SurfaceFormat.Vector4, MultiSampleType.EightSamples, 0);
                    GraphicsDevice.PresentationParameters.MultiSampleType    = MultiSampleType.EightSamples;
                    GraphicsDevice.PresentationParameters.MultiSampleQuality = 0;
                }
                catch (InvalidOperationException e)
                {
                    _supersample = 4;
                }
            }
            if (_supersample == 4)
            {
                try
                {
                    temp = new RenderTarget2D(GraphicsDevice, 1, 1, 1, SurfaceFormat.Vector4, MultiSampleType.FourSamples, 0);
                    GraphicsDevice.PresentationParameters.MultiSampleType    = MultiSampleType.FourSamples;
                    GraphicsDevice.PresentationParameters.MultiSampleQuality = 0;
                }
                catch (InvalidOperationException e)
                {
                    _supersample = 2;
                }
            }
            if (_supersample == 2)
            {
                try
                {
                    temp = new RenderTarget2D(GraphicsDevice, 1, 1, 1, SurfaceFormat.Vector4, MultiSampleType.TwoSamples, 0);
                    GraphicsDevice.PresentationParameters.MultiSampleType    = MultiSampleType.TwoSamples;
                    GraphicsDevice.PresentationParameters.MultiSampleQuality = 0;
                }
                catch (InvalidOperationException e)
                {
                    _supersample = 1;
                }
            }
            if (_supersample == 1)
            {
                graphics.PreferMultiSampling = false;
                GraphicsDevice.PresentationParameters.MultiSampleType    = MultiSampleType.None;
                GraphicsDevice.PresentationParameters.MultiSampleQuality = 0;
            }
            graphics.ApplyChanges();
        }
示例#16
0
 public BlockArea(GraphicsDevice device)
 {
     this.device  = device;
     this.tiles   = new BlockAreaTileType[8, 8];
     this.texture = new RenderTarget2D(device, AreaSize * TileSize, AreaSize * TileSize);
 }
示例#17
0
        float screenScaleX, screenScaleY; // Used to scale mouse coordinates to match game resolution

        // Constructor
        public Input(PresentationParameters pp, RenderTarget2D target)
        {
            screenScaleX = 1.0f / ((float)pp.BackBufferWidth / (float)target.Width);
            screenScaleY = 1.0f / ((float)pp.BackBufferHeight / (float)target.Height);
        }
示例#18
0
        protected override void OnPreDraw(GameTime gameTime)
        {
            if (player.ActorHost == null) return;

            if (ControlTexture == null)
            {
                ControlTexture = new RenderTarget2D(Manager.GraphicsDevice, ActualClientArea.Width, ActualClientArea.Height, PixelInternalFormat.Rgb8);
            }

            float octoDaysPerEarthDay = 360f;
            float inclinationVariance = MathHelper.Pi / 3f;

            float playerPosX = ((float)player.ActorHost.Player.Position.GlobalPosition.X / (planet.Size.X * Chunk.CHUNKSIZE_X)) * MathHelper.TwoPi;
            float playerPosY = ((float)player.ActorHost.Player.Position.GlobalPosition.Y / (planet.Size.Y * Chunk.CHUNKSIZE_Y)) * MathHelper.TwoPi;

            TimeSpan diff = DateTime.UtcNow - new DateTime(1888, 8, 8);

            float inclination = ((float)Math.Sin(playerPosY) * inclinationVariance) + MathHelper.Pi / 6f;
            //Console.WriteLine("Stand: " + (MathHelper.Pi + playerPosX) + " Neigung: " + inclination);
            Matrix sunMovement =
                Matrix.CreateRotationX(inclination) *
                //Matrix.CreateRotationY((((float)gameTime.TotalGameTime.TotalMinutes * MathHelper.TwoPi) + playerPosX) * -1);
                Matrix.CreateRotationY((float)(MathHelper.TwoPi - ((diff.TotalDays * octoDaysPerEarthDay * MathHelper.TwoPi) % MathHelper.TwoPi)));

            Vector3 sunDirection = Vector3.Transform(new Vector3(0, 0, 1), sunMovement);

            simpleShader.Parameters["DiffuseColor"].SetValue(new Color(190, 190, 190));
            simpleShader.Parameters["DiffuseIntensity"].SetValue(0.6f);
            simpleShader.Parameters["DiffuseDirection"].SetValue(sunDirection);

            // Console.WriteLine(sunDirection);

            // Index3 chunkOffset = player.ActorHost.Position.ChunkIndex;
            Index3 chunkOffset = camera.CameraChunk;
            Color background =
                new Color(181, 224, 255);

            Manager.GraphicsDevice.SetRenderTarget(MiniMapTexture);
            Manager.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            Manager.GraphicsDevice.Clear(background);

            foreach (var renderer in chunkRenderer)
            {
                if (!renderer.ChunkPosition.HasValue)
                    continue;

                Index3 shift = chunkOffset.ShortestDistanceXY(
                    renderer.ChunkPosition.Value, new Index2(
                        planet.Size.X,
                        planet.Size.Y));

                BoundingBox chunkBox = new BoundingBox(
                new Vector3(
                    shift.X * Chunk.CHUNKSIZE_X,
                    shift.Y * Chunk.CHUNKSIZE_Y,
                    shift.Z * Chunk.CHUNKSIZE_Z),
                new Vector3(
                    (shift.X + 1) * Chunk.CHUNKSIZE_X,
                    (shift.Y + 1) * Chunk.CHUNKSIZE_Y,
                    (shift.Z + 1) * Chunk.CHUNKSIZE_Z));

                int range = 3;
                if (shift.X >= -range && shift.X <= range &&
                    shift.Y >= -range && shift.Y <= range)
                    renderer.Draw(camera.MinimapView, miniMapProjectionMatrix, shift);
            }

            Manager.GraphicsDevice.SetRenderTarget(ControlTexture);
            Manager.GraphicsDevice.Clear(background);

            Manager.GraphicsDevice.BlendState = BlendState.AlphaBlend;
            Manager.GraphicsDevice.DepthStencilState = DepthStencilState.None;

            // Draw Sun
            // GraphicsDevice.RasterizerState = RasterizerState.CullNone;
            sunEffect.Texture = sunTexture;
            Matrix billboard = Matrix.Invert(camera.View);
            billboard.Translation = player.ActorHost.Position.LocalPosition + (sunDirection * -10);
            sunEffect.World = billboard;
            sunEffect.View = camera.View;
            sunEffect.Projection = camera.Projection;
            sunEffect.CurrentTechnique.Passes[0].Apply();
            Manager.GraphicsDevice.VertexBuffer = billboardVertexbuffer;
            Manager.GraphicsDevice.DrawPrimitives(PrimitiveType.Triangles, 0, 2);

            Manager.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            foreach (var renderer in chunkRenderer)
            {
                if (!renderer.ChunkPosition.HasValue)
                    continue;

                Index3 shift = chunkOffset.ShortestDistanceXY(
                    renderer.ChunkPosition.Value, new Index2(
                        planet.Size.X,
                        planet.Size.Y));

                BoundingBox chunkBox = new BoundingBox(
                new Vector3(
                    shift.X * Chunk.CHUNKSIZE_X,
                    shift.Y * Chunk.CHUNKSIZE_Y,
                    shift.Z * Chunk.CHUNKSIZE_Z),
                new Vector3(
                    (shift.X + 1) * Chunk.CHUNKSIZE_X,
                    (shift.Y + 1) * Chunk.CHUNKSIZE_Y,
                    (shift.Z + 1) * Chunk.CHUNKSIZE_Z));

                if (camera.Frustum.Intersects(chunkBox))
                    renderer.Draw(camera.View, camera.Projection, shift);
            }

            if (player.SelectedBox.HasValue)
            {
                // Index3 offset = player.ActorHost.Position.ChunkIndex * Chunk.CHUNKSIZE;
                Index3 offset = camera.CameraChunk * Chunk.CHUNKSIZE;
                Index3 planetSize = planet.Size * Chunk.CHUNKSIZE;
                Index3 relativePosition = new Index3(
                    Index2.ShortestDistanceOnAxis(offset.X, player.SelectedBox.Value.X, planetSize.X),
                    Index2.ShortestDistanceOnAxis(offset.Y, player.SelectedBox.Value.Y, planetSize.Y),
                    player.SelectedBox.Value.Z - offset.Z);

                Vector3 selectedBoxPosition = new Vector3(
                    player.SelectedBox.Value.X - (chunkOffset.X * Chunk.CHUNKSIZE_X),
                    player.SelectedBox.Value.Y - (chunkOffset.Y * Chunk.CHUNKSIZE_Y),
                    player.SelectedBox.Value.Z - (chunkOffset.Z * Chunk.CHUNKSIZE_Z));
                // selectionEffect.World = Matrix.CreateTranslation(selectedBoxPosition);
                selectionEffect.World = Matrix.CreateTranslation(relativePosition);
                selectionEffect.View = camera.View;
                selectionEffect.Projection = camera.Projection;
                Manager.GraphicsDevice.VertexBuffer = selectionLines;
                Manager.GraphicsDevice.IndexBuffer = selectionIndexBuffer;
                foreach (var pass in selectionEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    Manager.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.Lines, 0, 0, 8, 0, 12);
                    //Manager.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.Lines, selectionLines, 0, 8, selectionIndeces, 0, 12);
                }
            }

            Manager.GraphicsDevice.SetRenderTarget(null);
        }
示例#19
0
        public void LoadContent()
        {
            content = new ContentManager(ScreenManager.Instance.Content.ServiceProvider, "Content");

            if (source != String.Empty)
            {
                Texture = content.Load <Texture2D>(source);
            }

            font = content.Load <SpriteFont>(FontName);

            Vector2 dimensions = Vector2.Zero;

            if (Texture != null)
            {
                dimensions.X += Texture.Width;
            }
            dimensions.X += font.MeasureString(Text).X;

            if (Texture != null)
            {
                dimensions.Y = Math.Max(Texture.Height, font.MeasureString(Text).Y);
            }
            else
            {
                dimensions.Y = font.MeasureString(Text).Y;
            }

            if (SourceRect == Rectangle.Empty)
            {
                SourceRect = new Rectangle(0, 0, (int)dimensions.X, (int)dimensions.Y);
            }

            renderTarget = new RenderTarget2D(ScreenManager.Instance.GraphicsDevice,
                                              (int)dimensions.X, (int)dimensions.Y);

            ScreenManager.Instance.GraphicsDevice.SetRenderTarget(renderTarget);
            //The screen is its own render target
            ScreenManager.Instance.GraphicsDevice.Clear(Color.Transparent);
            ScreenManager.Instance.Spritebatch.Begin();
            if (Texture != null)
            {
                ScreenManager.Instance.Spritebatch.Draw(Texture, Vector2.Zero, Color.White);
            }
            ScreenManager.Instance.Spritebatch.DrawString(font, Text, Vector2.Zero, Color.White);
            ScreenManager.Instance.Spritebatch.End();

            Texture = renderTarget;

            ScreenManager.Instance.GraphicsDevice.SetRenderTarget(null);

            SetEffect <FadeEffect>(ref FadeEffect);
            SetEffect <SpriteSheetEffect>(ref SpriteSheetEffect);

            if (Effects != String.Empty)
            {
                string[] split = Effects.Split(':');
                foreach (string item in split)
                {
                    ActivateEffect(item);
                }
            }
        }
示例#20
0
 private void PipelineInitProbes()
 {
     GPUDownloadCache = new RenderTarget2D(XDevice, XPanel.Width, XPanel.Height, false, SurfaceFormat.Vector4, DepthFormat.None);
 }
示例#21
0
        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            GraphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PlatformContents;

            _blinkShowtime += gameTime.ElapsedGameTime;

            if (_blinkShowtime >= Skin.CursorBlinkSpeed)
            {
                _cursorVisiblePhase = !_cursorVisiblePhase;
                _blinkShowtime      = TimeSpan.Zero;
            }

            var inputFieldBounds   = _inputField.Bounds;
            var historyFieldBounds = _historyField.Bounds;

            //TODO: renderTarget redraw only if history or client size changed
            RenderTarget2D historyOutput = new RenderTarget2D(GraphicsDevice, historyFieldBounds.Width,
                                                              historyFieldBounds.Height, false, SurfaceFormat.Bgra32, DepthFormat.None, 1, RenderTargetUsage.PlatformContents);

            GraphicsDevice.SetRenderTarget(historyOutput);

            HistoryRenderer.Render(gameTime, spriteBatch, new Rectangle(_historyField.TextPadding, historyOutput.Bounds.Size));

            GraphicsDevice.SetRenderTarget(null);

            /////////////////////////////////////////////////////////
            //The better way to draw it on new RenderTarget2D////////
            //but in this case it will lose the different opacities//
            ////////////on game-rendered background//////////////////
            /////////////////////////////////////////////////////////
            spriteBatch.Begin();

            spriteBatch.DrawRect(ConsoleBounds, Skin.ConsoleBackground);             // BG

            spriteBatch.DrawRect(historyFieldBounds, Skin.HistoryField.BackColor);   // BG HISTORY

            spriteBatch.DrawRect(inputFieldBounds, Skin.InputField.BackColor);       // BG INPUT

            string croppedInput = InputTarget.CurrentInput.Substring(_visibleInputRange.X,
                                                                     _visibleInputRange.Y - _visibleInputRange.X);

            spriteBatch.DrawString(Font, croppedInput,
                                   inputFieldBounds.Location.ToVector2() + _inputField.TextPadding.ToVector2(),
                                   Skin.InputField.TextColor); // INPUT TEXT

            if (InputTarget.TextEditor.IsTextHighlighted)
            {
                Point highlightRange = InputTarget.TextEditor.HighlightRange;

                int offsetBeforeHighlight = _inputField.TextPadding.X;

                // If the beginning of the highlight is further
                // than the beginning of the fragment
                // we should calculate size of string before highlight is start
                if (highlightRange.X > _visibleInputRange.X)
                {
                    string textBeforeHighlighting =
                        InputTarget.CurrentInput.Substring(_visibleInputRange.X, highlightRange.X - _visibleInputRange.X);
                    offsetBeforeHighlight += (int)Font.MeasureString(textBeforeHighlighting).X;
                }

                Point visiblePartOfHighlight = new Point(Math.Max(highlightRange.X, _visibleInputRange.X),
                                                         Math.Min(highlightRange.Y, _visibleInputRange.Y));

                int highlightWidth = (int)Font.MeasureString(InputTarget.CurrentInput
                                                             .Substring(visiblePartOfHighlight.X, visiblePartOfHighlight.Y - visiblePartOfHighlight.X))
                                     .X;

                Rectangle highlightBounds = new Rectangle(inputFieldBounds.Location +
                                                          new Point(offsetBeforeHighlight, _highlightingPadding.Y),
                                                          new Point(highlightWidth, inputFieldBounds.Height - _highlightingPadding.Y * 2));

                spriteBatch.DrawRect(highlightBounds, Skin.HighlightColor);
            }

            //===============Cursor================//
            bool forciblyIgnore = _shouldIgnoreBlinking > TimeSpan.Zero;

            if (_cursorVisiblePhase || InputTarget.TextEditor.CursorMoving || forciblyIgnore)
            {
                int relativeCursorPosition = InputTarget.CursorPosition - _visibleInputRange.X;
                int offsetBeforeCursor     = (int)Font.MeasureString(croppedInput.Substring(0, relativeCursorPosition)).X + 2;

                if (relativeCursorPosition != 0)
                {
                    offsetBeforeCursor += (int)Font.Spacing / 2;
                }

                spriteBatch.DrawRect(new Rectangle(inputFieldBounds.X + offsetBeforeCursor, inputFieldBounds.Y
                                                   + _inputField.Padding.Y + 1, Skin.CursorWidth,
                                                   inputFieldBounds.Height - _inputField.Padding.Y * 2 - 1),
                                     Skin.CursorColor);

                if (forciblyIgnore)
                {
                    _shouldIgnoreBlinking -= gameTime.ElapsedGameTime;
                }
            }

            //===============History================//
            spriteBatch.Draw(historyOutput, historyFieldBounds, new Rectangle(Point.Zero, historyFieldBounds.Size), Color.White);


            //===============AutoComplete============//
            var autoCompleteBounds = _autoCompleteField.Bounds;

            spriteBatch.DrawRect(autoCompleteBounds, Skin.AutoCompleteField.BackColor);

            spriteBatch.DrawRect(new Rectangle(autoCompleteBounds.X, autoCompleteBounds.Y, 3, autoCompleteBounds.Height + 1),
                                 Skin.AutoCompleteBorder);

            spriteBatch.DrawRect(new Rectangle(autoCompleteBounds.Right - 3, autoCompleteBounds.Y, 3,
                                               autoCompleteBounds.Height + 1), Skin.AutoCompleteBorder);

            for (int i = 0; i < InputTarget.AutoCompleteVariation.Length; i++)
            {
                var position = new Vector2(autoCompleteBounds.X + _autoCompleteField.TextPadding.X,
                                           autoCompleteBounds.Y + _autoCompleteField.TextPadding.Y + Font.LineSpacing * i);

                spriteBatch.DrawString(Font, InputTarget.AutoCompleteVariation[i].CommandName, position,
                                       i == InputTarget.AutoCompleteSelectedIndex
                                                ? Skin.AutoCompleteSelectedTextColor
                                                : Skin.AutoCompleteField.TextColor);

                spriteBatch.DrawRect(new Rectangle((int)position.X - _autoCompleteField.TextPadding.X + 3,
                                                   (int)position.Y + Font.LineSpacing - 2, autoCompleteBounds.Width - 6, 2),
                                     Skin.AutoCompleteBorder);
            }

            spriteBatch.End();


            historyOutput.Dispose();
            GraphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.DiscardContents;
        }
示例#22
0
        public void RenderLightMap(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam, RenderTarget2D backgroundObstructor = null)
        {
            if (!LightingEnabled)
            {
                return;
            }

            if (Math.Abs(currLightMapScale - GameMain.Config.LightMapScale) > 0.01f)
            {
                //lightmap scale has changed -> recreate render targets
                CreateRenderTargets(graphics);
            }

            Matrix spriteBatchTransform = cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f));
            Matrix transform            = cam.ShaderTransform
                                          * Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f;

            bool highlightsVisible = UpdateHighlights(graphics, spriteBatch, spriteBatchTransform, cam);

            Rectangle viewRect = cam.WorldView;

            viewRect.Y -= cam.WorldView.Height;
            //check which lights need to be drawn
            activeLights.Clear();
            foreach (LightSource light in lights)
            {
                if (!light.Enabled)
                {
                    continue;
                }
                if ((light.Color.A < 1 || light.Range < 1.0f) && !light.LightSourceParams.OverrideLightSpriteAlpha.HasValue)
                {
                    continue;
                }
                if (light.ParentBody != null)
                {
                    light.Position = light.ParentBody.DrawPosition;
                    if (light.ParentSub != null)
                    {
                        light.Position -= light.ParentSub.DrawPosition;
                    }
                }

                float range = light.LightSourceParams.TextureRange;
                if (light.LightSprite != null)
                {
                    float spriteRange = Math.Max(
                        light.LightSprite.size.X * light.SpriteScale.X * (0.5f + Math.Abs(light.LightSprite.RelativeOrigin.X - 0.5f)),
                        light.LightSprite.size.Y * light.SpriteScale.Y * (0.5f + Math.Abs(light.LightSprite.RelativeOrigin.Y - 0.5f)));
                    range = Math.Max(spriteRange, range);
                }
                if (!MathUtils.CircleIntersectsRectangle(light.WorldPosition, range, viewRect))
                {
                    continue;
                }
                activeLights.Add(light);
            }

            //draw light sprites attached to characters
            //render into a separate rendertarget using alpha blending (instead of on top of everything else with alpha blending)
            //to prevent the lights from showing through other characters or other light sprites attached to the same character
            //---------------------------------------------------------------------------------------------------
            graphics.SetRenderTarget(LimbLightMap);
            graphics.Clear(Color.Black);
            graphics.BlendState = BlendState.NonPremultiplied;
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
            foreach (LightSource light in activeLights)
            {
                if (light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                //draw limb lights at this point, because they were skipped over previously to prevent them from being obstructed
                if (light.ParentBody?.UserData is Limb limb && !limb.Hide)
                {
                    light.DrawSprite(spriteBatch, cam);
                }
            }
            spriteBatch.End();

            //draw background lights
            //---------------------------------------------------------------------------------------------------
            graphics.SetRenderTarget(LightMap);
            graphics.Clear(AmbientLight);
            graphics.BlendState = BlendState.Additive;
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
            Level.Loaded?.BackgroundCreatureManager?.DrawLights(spriteBatch, cam);
            foreach (LightSource light in activeLights)
            {
                if (!light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawSprite(spriteBatch, cam);
                light.DrawLightVolume(spriteBatch, lightEffect, transform);
            }
            GameMain.ParticleManager.Draw(spriteBatch, true, null, Particles.ParticleBlendState.Additive);
            spriteBatch.End();

            //draw a black rectangle on hulls to hide background lights behind subs
            //---------------------------------------------------------------------------------------------------

            if (backgroundObstructor != null)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
                spriteBatch.Draw(backgroundObstructor, new Rectangle(0, 0,
                                                                     (int)(GameMain.GraphicsWidth * currLightMapScale), (int)(GameMain.GraphicsHeight * currLightMapScale)), Color.Black);
                spriteBatch.End();
            }

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, transformMatrix: spriteBatchTransform);
            Dictionary <Hull, Rectangle> visibleHulls = GetVisibleHulls(cam);

            foreach (KeyValuePair <Hull, Rectangle> hull in visibleHulls)
            {
                GUI.DrawRectangle(spriteBatch,
                                  new Vector2(hull.Value.X, -hull.Value.Y),
                                  new Vector2(hull.Value.Width, hull.Value.Height),
                                  hull.Key.AmbientLight == Color.TransparentBlack ? Color.Black : hull.Key.AmbientLight.Multiply(hull.Key.AmbientLight.A / 255.0f), true);
            }
            spriteBatch.End();

            SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidColor"];
            SolidColorEffect.Parameters["color"].SetValue(AmbientLight.ToVector4());
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform, effect: SolidColorEffect);
            Submarine.DrawDamageable(spriteBatch, null);
            spriteBatch.End();

            graphics.BlendState = BlendState.Additive;


            //draw the focused item and character to highlight them,
            //and light sprites (done before drawing the actual light volumes so we can make characters obstruct the highlights and sprites)
            //---------------------------------------------------------------------------------------------------
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
            foreach (LightSource light in activeLights)
            {
                //don't draw limb lights at this point, they need to be drawn after lights have been obstructed by characters
                if (light.IsBackground || light.ParentBody?.UserData is Limb || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawSprite(spriteBatch, cam);
            }
            spriteBatch.End();

            if (highlightsVisible)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
                spriteBatch.Draw(HighlightMap, Vector2.Zero, Color.White);
                spriteBatch.End();
            }

            //draw characters to obstruct the highlighted items/characters and light sprites
            //---------------------------------------------------------------------------------------------------

            SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidVertexColor"];
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, effect: SolidColorEffect, transformMatrix: spriteBatchTransform);
            foreach (Character character in Character.CharacterList)
            {
                if (character.CurrentHull == null || !character.Enabled || !character.IsVisible)
                {
                    continue;
                }
                if (Character.Controlled?.FocusedCharacter == character)
                {
                    continue;
                }
                Color lightColor = character.CurrentHull.AmbientLight == Color.TransparentBlack ?
                                   Color.Black :
                                   character.CurrentHull.AmbientLight.Multiply(character.CurrentHull.AmbientLight.A / 255.0f).Opaque();
                foreach (Limb limb in character.AnimController.Limbs)
                {
                    if (limb.DeformSprite != null)
                    {
                        continue;
                    }
                    limb.Draw(spriteBatch, cam, lightColor);
                }
            }
            spriteBatch.End();

            DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShaderSolidVertexColor"];
            DeformableSprite.Effect.CurrentTechnique.Passes[0].Apply();
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
            foreach (Character character in Character.CharacterList)
            {
                if (character.CurrentHull == null || !character.Enabled || !character.IsVisible)
                {
                    continue;
                }
                if (Character.Controlled?.FocusedCharacter == character)
                {
                    continue;
                }
                Color lightColor = character.CurrentHull.AmbientLight == Color.TransparentBlack ?
                                   Color.Black :
                                   character.CurrentHull.AmbientLight.Multiply(character.CurrentHull.AmbientLight.A / 255.0f).Opaque();
                foreach (Limb limb in character.AnimController.Limbs)
                {
                    if (limb.DeformSprite == null)
                    {
                        continue;
                    }
                    limb.Draw(spriteBatch, cam, lightColor);
                }
            }
            spriteBatch.End();
            DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShader"];
            graphics.BlendState = BlendState.Additive;

            //draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
            //---------------------------------------------------------------------------------------------------
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);

            spriteBatch.Draw(LimbLightMap, new Rectangle(cam.WorldView.X, -cam.WorldView.Y, cam.WorldView.Width, cam.WorldView.Height), Color.White);

            foreach (ElectricalDischarger discharger in ElectricalDischarger.List)
            {
                discharger.DrawElectricity(spriteBatch);
            }

            foreach (LightSource light in activeLights)
            {
                if (light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawLightVolume(spriteBatch, lightEffect, transform);
            }

            lightEffect.World = transform;

            GameMain.ParticleManager.Draw(spriteBatch, false, null, Particles.ParticleBlendState.Additive);

            if (Character.Controlled != null)
            {
                DrawHalo(Character.Controlled);
            }
            else
            {
                foreach (Character character in Character.CharacterList)
                {
                    if (character.Submarine == null || character.IsDead || !character.IsHuman)
                    {
                        continue;
                    }
                    DrawHalo(character);
                }
            }

            void DrawHalo(Character character)
            {
                if (character == null || character.Removed)
                {
                    return;
                }
                Vector2 haloDrawPos = character.DrawPosition;

                haloDrawPos.Y = -haloDrawPos.Y;

                //ambient light decreases the brightness of the halo (no need for a bright halo if the ambient light is bright enough)
                float ambientBrightness = (AmbientLight.R + AmbientLight.B + AmbientLight.G) / 255.0f / 3.0f;
                Color haloColor         = Color.White.Multiply(0.3f - ambientBrightness);

                if (haloColor.A > 0)
                {
                    float scale = 512.0f / LightSource.LightTexture.Width;
                    spriteBatch.Draw(
                        LightSource.LightTexture, haloDrawPos, null, haloColor, 0.0f,
                        new Vector2(LightSource.LightTexture.Width, LightSource.LightTexture.Height) / 2, scale, SpriteEffects.None, 0.0f);
                }
            }

            spriteBatch.End();

            //draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
            //---------------------------------------------------------------------------------------------------

            graphics.SetRenderTarget(null);
            graphics.BlendState = BlendState.NonPremultiplied;
        }
示例#23
0
        public void PostProcess(RenderTarget2D result, RenderParameters parameters)
        {
            if (this.needBufferReallocation())
            {
                return;
            }

            Vector3         originalCameraPosition  = parameters.Camera.Position;
            Matrix          originalViewMatrix      = parameters.Camera.View;
            BoundingFrustum originalBoundingFrustum = parameters.Camera.BoundingFrustum;

            parameters.Camera.Position.Value = Vector3.Zero;
            Matrix newViewMatrix = originalViewMatrix;

            newViewMatrix.Translation    = Vector3.Zero;
            parameters.Camera.View.Value = newViewMatrix;

            RasterizerState originalState = this.main.GraphicsDevice.RasterizerState;

            bool enableSSAO = this.allowSSAO && this.EnableSSAO;

            if (enableSSAO)
            {
                // Down-sample depth buffer
                this.downsampleEffect.CurrentTechnique = this.downsampleEffect.Techniques["DownsampleDepth"];
                this.sources2[0]      = this.depthBuffer;
                this.sources2[1]      = this.normalBuffer;
                this.destinations2[0] = this.halfDepthBuffer;
                this.destinations2[1] = this.halfBuffer1;
                if (!this.preparePostProcess(this.sources2, this.destinations2, this.downsampleEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                // Compute SSAO
                parameters.Camera.SetParameters(this.ssaoEffect);
                this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["SSAO"];
                this.sources2[0]      = this.halfDepthBuffer;
                this.sources2[1]      = this.halfBuffer1;
                this.destinations1[0] = this.halfBuffer2;
                if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                // Blur
                this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["BlurHorizontal"];
                this.sources2[0]      = this.halfBuffer2;
                this.sources2[1]      = this.halfDepthBuffer;
                this.destinations1[0] = this.halfBuffer1;
                if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["Composite"];
                this.sources2[0]      = this.halfBuffer1;
                this.sources2[1]      = this.halfDepthBuffer;
                this.destinations1[0] = this.halfBuffer2;
                if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);
            }

            // Global lighting
            this.destinations2[0] = this.lightingBuffer;
            this.destinations2[1] = this.specularBuffer;
            if (!this.setTargets(this.destinations2))
            {
                return;
            }
            string globalLightTechnique = "GlobalLight";

            if (this.lightingManager.EnableGlobalShadowMap && this.lightingManager.HasGlobalShadowLight)
            {
                if (parameters.IsMainRender)
                {
                    if (this.lightingManager.HasGlobalShadowLightClouds)
                    {
                        if (this.lightingManager.EnableDetailGlobalShadowMap)
                        {
                            globalLightTechnique = "GlobalLightDetailShadowClouds";
                        }
                        else
                        {
                            globalLightTechnique = "GlobalLightShadowClouds";
                        }
                    }
                    else
                    {
                        if (this.lightingManager.EnableDetailGlobalShadowMap)
                        {
                            globalLightTechnique = "GlobalLightDetailShadow";
                        }
                        else
                        {
                            globalLightTechnique = "GlobalLightShadow";
                        }
                    }
                }
                else
                {
                    globalLightTechnique = "GlobalLightShadow";
                }
            }
            Renderer.globalLightEffect.CurrentTechnique = Renderer.globalLightEffect.Techniques[globalLightTechnique];
            parameters.Camera.SetParameters(Renderer.globalLightEffect);
            this.lightingManager.SetGlobalLightParameters(Renderer.globalLightEffect, parameters.Camera, originalCameraPosition);
            Renderer.globalLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData);
            this.sources3[0]      = this.depthBuffer;
            this.sources3[1]      = this.normalBuffer;
            this.sources3[2]      = this.colorBuffer1;
            this.destinations2[0] = this.lightingBuffer;
            this.destinations2[1] = this.specularBuffer;
            this.setTargetParameters(this.sources3, this.destinations2, Renderer.globalLightEffect);
            this.applyEffect(Renderer.globalLightEffect);
            Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

            // Spot and point lights
            if (!parameters.ReverseCullOrder)
            {
                this.main.GraphicsDevice.RasterizerState = this.reverseCullState;
            }

            // HACK
            // Increase the far plane to prevent clipping back faces of huge lights
            float originalFarPlane = parameters.Camera.FarPlaneDistance;

            parameters.Camera.FarPlaneDistance.Value *= 4.0f;
            parameters.Camera.SetParameters(Renderer.pointLightEffect);
            parameters.Camera.SetParameters(Renderer.spotLightEffect);
            parameters.Camera.FarPlaneDistance.Value = originalFarPlane;

            // Spot lights
            Renderer.spotLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData);
            this.setTargetParameters(this.sources3, this.destinations2, Renderer.spotLightEffect);
            for (int i = 0; i < SpotLight.All.Count; i++)
            {
                SpotLight light = SpotLight.All[i];
                if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || light.Color.Value.LengthSquared() == 0.0f || !originalBoundingFrustum.Intersects(light.BoundingFrustum))
                {
                    continue;
                }

                this.lightingManager.SetSpotLightParameters(light, Renderer.spotLightEffect, originalCameraPosition);
                this.applyEffect(Renderer.spotLightEffect);
                this.drawModel(Renderer.spotLightModel);
            }

            // Point lights
            Renderer.pointLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData);
            this.setTargetParameters(this.sources3, this.destinations2, Renderer.pointLightEffect);
            for (int i = 0; i < PointLight.All.Count; i++)
            {
                PointLight light = PointLight.All[i];
                if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || light.Color.Value.LengthSquared() == 0.0f || !originalBoundingFrustum.Intersects(light.BoundingSphere))
                {
                    continue;
                }
                this.lightingManager.SetPointLightParameters(light, Renderer.pointLightEffect, originalCameraPosition);
                this.applyEffect(Renderer.pointLightEffect);
                this.drawModel(Renderer.pointLightModel);
            }

            if (!parameters.ReverseCullOrder)
            {
                this.main.GraphicsDevice.RasterizerState = originalState;
            }

            RenderTarget2D colorSource      = this.colorBuffer1;
            RenderTarget2D colorDestination = this.hdrBuffer2;
            RenderTarget2D colorTemp        = null;

            // Compositing
            this.compositeEffect.CurrentTechnique = this.compositeEffect.Techniques[enableSSAO ? "CompositeSSAO" : "Composite"];
            this.lightingManager.SetCompositeParameters(this.compositeEffect);
            parameters.Camera.SetParameters(this.compositeEffect);
            this.compositeEffect.Parameters["Materials"].SetValue(parameters.MaterialData);
            RenderTarget2D[] compositeSources;
            if (enableSSAO)
            {
                compositeSources    = this.sources4;
                compositeSources[3] = this.halfBuffer2;
            }
            else
            {
                compositeSources = this.sources3;
            }

            compositeSources[0] = colorSource;
            compositeSources[1] = this.lightingBuffer;
            compositeSources[2] = this.specularBuffer;

            this.destinations1[0] = colorDestination;

            if (!this.preparePostProcess(compositeSources, this.destinations1, this.compositeEffect))
            {
                return;
            }

            Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

            bool enableBloom      = this.allowBloom && this.EnableBloom;
            bool enableMotionBlur = this.MotionBlurAmount > 0.0f;

#if VR
            if (this.main.VR)
            {
                enableMotionBlur = false;
            }
#endif

            bool enableBlur = this.BlurAmount > 0.0f;

            // Swap the color buffers
            colorSource      = this.hdrBuffer2;
            colorDestination = enableBloom || this.allowToneMapping || enableBlur || enableMotionBlur ? this.hdrBuffer1 : result;

            parameters.DepthBuffer = this.depthBuffer;
            parameters.FrameBuffer = colorSource;

            // Alpha components

            // Drawing to the color destination
            this.destinations1[0] = colorDestination;
            if (!this.setTargets(this.destinations1))
            {
                return;
            }

            // Copy the color source to the destination
            this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, DepthStencilState.None, originalState);
            this.spriteBatch.Draw(colorSource, Vector2.Zero, Color.White);
            this.spriteBatch.End();

            parameters.Camera.Position.Value = originalCameraPosition;
            parameters.Camera.View.Value     = originalViewMatrix;

            this.main.DrawAlphaComponents(parameters);
            this.main.DrawPostAlphaComponents(parameters);

            // Swap the color buffers
            colorTemp              = colorDestination;
            colorDestination       = colorSource;
            parameters.FrameBuffer = colorSource = colorTemp;

            // Bloom
            if (enableBloom)
            {
                this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["Downsample"];
                this.sources1[0]      = colorSource;
                this.destinations1[0] = this.halfBuffer1;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["BlurHorizontal"];
                this.sources1[0]      = this.halfBuffer1;
                this.destinations1[0] = this.halfBuffer2;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["BlurVertical"];
                this.sources1[0]      = this.halfBuffer2;
                this.destinations1[0] = this.halfBuffer1;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["Composite"];
                this.sources2[0]      = colorSource;
                this.sources2[1]      = this.halfBuffer1;
                this.destinations1[0] = enableBlur || enableMotionBlur ? this.colorBuffer2 : result;
                if (!this.preparePostProcess(this.sources2, this.destinations1, this.bloomEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                // Swap the color buffers
                colorDestination = this.colorBuffer1;
                colorSource      = this.colorBuffer2;
            }
            else if (this.allowToneMapping)
            {
                this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["ToneMapOnly"];
                this.sources1[0]      = colorSource;
                this.destinations1[0] = enableBlur || enableMotionBlur ? this.colorBuffer2 : result;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                // Swap the color buffers
                colorDestination = this.colorBuffer1;
                colorSource      = this.colorBuffer2;
            }

            // Motion blur
            if (enableMotionBlur)
            {
                this.motionBlurEffect.CurrentTechnique = this.motionBlurEffect.Techniques["MotionBlur"];
                parameters.Camera.SetParameters(this.motionBlurEffect);

                // If we just reallocated our buffers, don't use the velocity buffer from the last frame because it will be empty
                this.sources3[0]      = colorSource;
                this.sources3[1]      = this.normalBuffer;
                this.sources3[2]      = this.justReallocatedBuffers ? this.normalBuffer : this.normalBufferLastFrame;
                this.destinations1[0] = enableBlur ? colorDestination : result;
                if (!this.preparePostProcess(this.sources3, this.destinations1, this.motionBlurEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);

                // Swap the velocity buffers
                RenderTarget2D temp = this.normalBufferLastFrame;
                this.normalBufferLastFrame = this.normalBuffer;
                this.normalBuffer          = temp;

                // Swap the color buffers
                colorTemp        = colorDestination;
                colorDestination = colorSource;
                colorSource      = colorTemp;
            }

            if (enableBlur)
            {
                // Blur
                this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["BlurHorizontal"];
                parameters.Camera.SetParameters(this.blurEffect);
                this.sources1[0]      = colorSource;
                this.destinations1[0] = colorDestination;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.blurEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);
                this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["Composite"];

                // Swap the color buffers
                colorTemp        = colorDestination;
                colorDestination = colorSource;
                colorSource      = colorTemp;

                this.sources1[0]      = colorSource;
                this.destinations1[0] = result;
                if (!this.preparePostProcess(this.sources1, this.destinations1, this.blurEffect))
                {
                    return;
                }
                Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);
            }

            parameters.DepthBuffer = null;
            parameters.FrameBuffer = null;

            this.justReallocatedBuffers = false;
        }
示例#24
0
        public void ReallocateBuffers(Point size)
        {
            this.compositeEffect = this.main.Content.Load <Effect>("Effects\\PostProcess\\Composite").Clone();
            this.compositeEffect.CurrentTechnique = this.compositeEffect.Techniques["Composite"];
            this.blurEffect = this.main.Content.Load <Effect>("Effects\\PostProcess\\Blur").Clone();

            this.downsampleEffect  = this.main.Content.Load <Effect>("Effects\\PostProcess\\Downsample").Clone();
            this.ssaoEffect        = this.main.Content.Load <Effect>("Effects\\PostProcess\\SSAO").Clone();
            this.ssaoRandomTexture = this.main.Content.Load <Texture2D>("Textures\\random");
            this.ssaoEffect.Parameters[paramRandomSampler].SetValue(this.ssaoRandomTexture);

            this.bloomEffect = this.main.Content.Load <Effect>("Effects\\PostProcess\\Bloom").Clone();

            this.loadLightRampTexture(this.LightRampTexture);

            this.clearEffect = this.main.Content.Load <Effect>("Effects\\PostProcess\\Clear").Clone();

            this.motionBlurEffect = this.main.Content.Load <Effect>("Effects\\PostProcess\\MotionBlur").Clone();

            this.screenSize = size;

            if (size.X > 0 && size.Y > 0)
            {
                // Lighting buffer
                if (this.lightingBuffer != null && !this.lightingBuffer.IsDisposed)
                {
                    this.lightingBuffer.Dispose();
                }
                this.lightingBuffer = new RenderTarget2D(this.main.GraphicsDevice,
                                                         size.X,
                                                         size.Y,
                                                         false,
                                                         SurfaceFormat.Color,
                                                         DepthFormat.None,
                                                         0,
                                                         RenderTargetUsage.DiscardContents);

                // Specular lighting buffer
                if (this.specularBuffer != null && !this.specularBuffer.IsDisposed)
                {
                    this.specularBuffer.Dispose();
                }
                this.specularBuffer = new RenderTarget2D(this.main.GraphicsDevice,
                                                         size.X,
                                                         size.Y,
                                                         false,
                                                         SurfaceFormat.Color,
                                                         DepthFormat.None,
                                                         0,
                                                         RenderTargetUsage.DiscardContents);

                // Depth buffer
                if (this.depthBuffer != null && !this.depthBuffer.IsDisposed)
                {
                    this.depthBuffer.Dispose();
                }
                this.depthBuffer = new RenderTarget2D(this.main.GraphicsDevice,
                                                      size.X,
                                                      size.Y,
                                                      false,
                                                      SurfaceFormat.HalfVector2,
                                                      DepthFormat.Depth24,
                                                      0,
                                                      RenderTargetUsage.DiscardContents);

                // Normal buffer
                if (this.normalBuffer != null && !this.normalBuffer.IsDisposed)
                {
                    this.normalBuffer.Dispose();
                }
                this.normalBuffer = new RenderTarget2D(this.main.GraphicsDevice,
                                                       size.X,
                                                       size.Y,
                                                       false,
                                                       SurfaceFormat.Color,
                                                       DepthFormat.None,
                                                       0,
                                                       RenderTargetUsage.DiscardContents);

                // Color buffer 1
                if (this.colorBuffer1 != null && !this.colorBuffer1.IsDisposed)
                {
                    this.colorBuffer1.Dispose();
                }
                this.colorBuffer1 = new RenderTarget2D(this.main.GraphicsDevice,
                                                       size.X,
                                                       size.Y,
                                                       false,
                                                       SurfaceFormat.Color,
                                                       DepthFormat.Depth24,
                                                       0,
                                                       RenderTargetUsage.DiscardContents);

                // Color buffer 2
                if (this.colorBuffer2 != null && !this.colorBuffer2.IsDisposed)
                {
                    this.colorBuffer2.Dispose();
                }
                this.colorBuffer2 = new RenderTarget2D(this.main.GraphicsDevice,
                                                       size.X,
                                                       size.Y,
                                                       false,
                                                       SurfaceFormat.Color,
                                                       DepthFormat.Depth24,
                                                       0,
                                                       RenderTargetUsage.DiscardContents);

                if (this.hdr)
                {
                    // HDR buffer 1
                    if (this.hdrBuffer1 != null && !this.hdrBuffer1.IsDisposed)
                    {
                        this.hdrBuffer1.Dispose();
                    }
                    this.hdrBuffer1 = new RenderTarget2D(this.main.GraphicsDevice,
                                                         size.X,
                                                         size.Y,
                                                         false,
                                                         this.hdrSurfaceFormat,
                                                         DepthFormat.Depth24,
                                                         0,
                                                         RenderTargetUsage.DiscardContents);

                    // HDR buffer 2
                    if (this.hdrBuffer2 != null && !this.hdrBuffer2.IsDisposed)
                    {
                        this.hdrBuffer2.Dispose();
                    }
                    this.hdrBuffer2 = new RenderTarget2D(this.main.GraphicsDevice,
                                                         size.X,
                                                         size.Y,
                                                         false,
                                                         this.hdrSurfaceFormat,
                                                         DepthFormat.None,
                                                         0,
                                                         RenderTargetUsage.DiscardContents);
                }
                else
                {
                    this.hdrBuffer1 = this.colorBuffer1;
                    this.hdrBuffer2 = this.colorBuffer2;
                }

                if (this.normalBufferLastFrame != null)
                {
                    if (!this.normalBufferLastFrame.IsDisposed)
                    {
                        this.normalBufferLastFrame.Dispose();
                    }
                    this.normalBufferLastFrame = null;
                }

                // Normal buffer from last frame
                this.normalBufferLastFrame = new RenderTarget2D(this.main.GraphicsDevice,
                                                                size.X,
                                                                size.Y,
                                                                false,
                                                                SurfaceFormat.Color,
                                                                DepthFormat.None,
                                                                0,
                                                                RenderTargetUsage.DiscardContents);

                if (this.halfBuffer1 != null)
                {
                    if (!this.halfBuffer1.IsDisposed)
                    {
                        this.halfBuffer1.Dispose();
                    }
                    this.halfBuffer1 = null;
                }
                if (this.halfBuffer2 != null)
                {
                    if (!this.halfBuffer2.IsDisposed)
                    {
                        this.halfBuffer2.Dispose();
                    }
                    this.halfBuffer2 = null;
                }
                if (this.halfDepthBuffer != null)
                {
                    if (!this.halfDepthBuffer.IsDisposed)
                    {
                        this.halfDepthBuffer.Dispose();
                    }
                    this.halfDepthBuffer = null;
                }

                if (this.allowBloom || this.allowSSAO)
                {
                    this.halfBuffer1 = new RenderTarget2D(this.main.GraphicsDevice,
                                                          size.X / 2,
                                                          size.Y / 2,
                                                          false,
                                                          SurfaceFormat.Color,
                                                          DepthFormat.None,
                                                          0,
                                                          RenderTargetUsage.DiscardContents);
                    this.halfBuffer2 = new RenderTarget2D(this.main.GraphicsDevice,
                                                          size.X / 2,
                                                          size.Y / 2,
                                                          false,
                                                          SurfaceFormat.Color,
                                                          DepthFormat.None,
                                                          0,
                                                          RenderTargetUsage.DiscardContents);
                }

                if (this.allowSSAO)
                {
                    this.halfDepthBuffer = new RenderTarget2D(this.main.GraphicsDevice,
                                                              size.X / 2,
                                                              size.Y / 2,
                                                              false,
                                                              SurfaceFormat.Single,
                                                              DepthFormat.None,
                                                              0,
                                                              RenderTargetUsage.DiscardContents);
                }
            }

            this.BlurAmount.Reset();
            this.SpeedBlurAmount.Reset();
            this.Tint.Reset();
            this.InternalGamma.Reset();
            this.Gamma.Reset();
            this.Brightness.Reset();
            this.MotionBlurAmount.Reset();
            this.LightRampTexture.Reset();

            this.justReallocatedBuffers = true;
        }
示例#25
0
        public override void Draw(GameTime gameTime)
        {
            if (!Visible)
            {
                return;
            }

#if SILVERLIGHT
            var oldRenderTarget = GraphicsDevice.GetRenderTarget(0) as RenderTarget2D;
            this.GraphicsDevice.SetRenderTarget(0, _renderTarget);

            // Fix para GraphicsDevice.Clear que não limpa com Transparent
            Array.Clear(_renderTarget.GetTexture().ImageSource.Pixels, 0, _renderTarget.GetTexture().ImageSource.Pixels.Length);
#else
            RenderTarget2D oldRenderTarget = null;
            if (GraphicsDevice.GetRenderTargets().Count() > 0)
            {
                oldRenderTarget = GraphicsDevice.GetRenderTargets()[0].RenderTarget as RenderTarget2D;
            }
            GraphicsDevice.SetRenderTarget(_renderTarget);
#endif

            GraphicsDevice.Clear(BackgroundColor);

#if SILVERLIGHT
            SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None, MatrixInternal);
#else
            SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, MatrixInternal);
#endif


            int size = Math.Min(_contentSize, Horizontal ? _Width : _Height);

            if (_scrollable != null)
            {
                _scrollable.Alpha    = Alpha;
                _scrollable.Position = Horizontal ? new Vector2(-PosDif, 0) : new Vector2(0, -PosDif);
                var scrollableCullable = _scrollable as IScrollableCullable;
                if (Culling && scrollableCullable != null)
                {
                    scrollableCullable.DrawLimited(gameTime, PosDif, size);
                }
                else
                {
                    _scrollable.Draw(gameTime);
                }
            }

            SpriteBatch.End();

#if SILVERLIGHT
            GraphicsDevice.SetRenderTarget(0, oldRenderTarget);
            SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None, Matrix);

            var       color = new Color(Color, MathHelper.Clamp((float)Alpha, 0, 1));
            Texture2D tex   = _renderTarget.GetTexture();
#else
            GraphicsDevice.SetRenderTarget(oldRenderTarget);
            SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Matrix);

            var       color = Color * (float)Alpha;
            Texture2D tex   = _renderTarget;
#endif

            if (Horizontal)
            {
                _rectDraw.Width  = size;
                _rectDraw.Height = _Height;
            }
            else
            {
                _rectDraw.Width  = _Width;
                _rectDraw.Height = size;
            }

            SpriteBatch.Draw(tex, Position, _rectDraw, color);

            if (_scroll != null)
            {
                _scroll.Alpha = Alpha;
                _scroll.Draw(gameTime);
            }

            SpriteBatch.End();

            base.Draw(gameTime);
        }
示例#26
0
        public void Dump()
        {
            try {
                Texture2D             texture         = Texture2D.FromStream(this.GraphicsDevice, File.OpenRead(@"C:\Users\Oxysoft\Desktop\_splitter_tool\input.png"));
                string                dumploc         = @"C:\Users\Oxysoft\Desktop\_splitter_tool\newdump\";
                const int             cols            = 10;
                const int             rows            = 10;
                TileableTexture       tileableTexture = new TileableTexture(texture, cols, rows);
                List <RenderTarget2D> results         = new List <RenderTarget2D>();
                Color chroma1 = new Color(0xBF, 0xC8, 0xFF);
                Color chroma2 = new Color(0xD8, 0xDE, 0xFF);
                for (int y = 0; y < rows; y++)
                {
                    for (int x = 0; x < cols; x++)
                    {
                        int[] order = new int[4 * 4];

                        order[0]  = 5;
                        order[1]  = 11;
                        order[2]  = 5;
                        order[3]  = 8;
                        order[4]  = 6;
                        order[5]  = 3;
                        order[6]  = 6;
                        order[7]  = 9;
                        order[8]  = 1;
                        order[9]  = 4;
                        order[10] = 1;
                        order[11] = 7;
                        order[12] = 0;
                        order[13] = 2;
                        order[14] = 0;
                        order[15] = 10;

                        RenderTarget2D  renderTarget         = new RenderTarget2D(GraphicsDevice, 96, 128);
                        TileableTexture tileableRenderTarget = new TileableTexture(renderTarget, 3, 4);
                        GraphicsDevice.SetRenderTarget(renderTarget);
                        SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);
                        spriteBatch.Begin();
                        spriteBatch.Draw(texture, new Rectangle(0, 0, 96, 128), tileableTexture.GetSource(tileableTexture.GetIndex(x, y)), Color.White);
                        spriteBatch.End();
                        GraphicsDevice.SetRenderTarget(null);
                        RenderTarget2D  resultTarget         = new RenderTarget2D(GraphicsDevice, 128, 128);
                        TileableTexture tileableResultTarget = new TileableTexture(resultTarget, 4, 4);
                        GraphicsDevice.SetRenderTarget(resultTarget);
                        GraphicsDevice.Clear(Color.Transparent);

                        spriteBatch.Begin();
                        for (int i = 0; i < order.Length; i++)
                        {
                            Rectangle target = tileableResultTarget.GetSource(i);
                            spriteBatch.Draw(renderTarget, target, tileableRenderTarget.GetSource(order[i]), Color.White);
                        }
                        spriteBatch.End();
                        GraphicsDevice.SetRenderTarget(null);

                        //----> Start of CHROMA CLEARING
                        Color[] colors = new Color[resultTarget.Width * resultTarget.Height];
                        resultTarget.GetData <Color>(colors);

                        for (int i = 0; i < colors.Length; i++)
                        {
                            if (colors[i] == chroma1 || colors[i] == chroma2)
                            {
                                colors[i] = Color.Transparent;
                            }
                        }

                        resultTarget.SetData <Color>(colors);
                        //End of CHROMA CLEARING <----

                        results.Add(resultTarget);
                    }
                }
                for (int i = 0; i < results.Count; i++)
                {
                    results[i].SaveAsPng(File.OpenWrite(dumploc + i + ".png"), results[i].Width, results[i].Height);
                }
            } catch (Exception e) {
                Console.WriteLine("what da fack");
            }
        }
示例#27
0
		/// <summary>
		/// 
		/// </summary>
		void CreateTargets ()
		{
			var disp	=	Game.GraphicsDevice.DisplayBounds;

			var newWidth	=	Math.Max(64, disp.Width);
			var newHeight	=	Math.Max(64, disp.Height);

			SafeDispose( ref downsampledDepth );
			SafeDispose( ref downsampledNormals );
			SafeDispose( ref occlusionMap0 );
			SafeDispose( ref occlusionMap1 );

			downsampledDepth	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.R32F,  newWidth, newHeight, false, false );
			downsampledNormals	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba8, newWidth, newHeight, false, false );
			occlusionMap0		=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba8, newWidth, newHeight, false, false );
			occlusionMap1		=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba8, newWidth, newHeight, false, false );
		}
示例#28
0
 public override void UpdateBuffer()
 {
     m_color = TestAndCreateColorBuffer(m_color);
 }
示例#29
0
        /// <summary>
        /// 
        /// </summary>
        void CreateShadowMaps()
        {
            SafeDispose( ref csmColor );
            SafeDispose( ref csmDepth );

            SafeDispose( ref spotColor );
            SafeDispose( ref spotDepth );

            csmColor	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.R32F,  Config.CSMSize * 4, Config.CSMSize );
            csmDepth	=	new DepthStencil2D( Game.GraphicsDevice, DepthFormat.D24S8, Config.CSMSize * 4, Config.CSMSize );

            spotColor	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.R32F,  Config.SpotShadowSize * 4, Config.SpotShadowSize * 4 );
            spotDepth	=	new DepthStencil2D( Game.GraphicsDevice, DepthFormat.D24S8, Config.SpotShadowSize * 4, Config.SpotShadowSize * 4 );
        }
示例#30
0
 /// <summary>
 /// sets render target.
 /// </summary>
 /// <param name="index">an index of render target</param>
 /// <param name="renderTarget"></param>
 public void SetRenderTarget(int index, RenderTarget2D renderTarget)
 {
     GraphicsDevice.SetRenderTarget(index, renderTarget);
 }
示例#31
0
		/// <summary>
		/// Performs good-old StretchRect to destination buffer with blending.
		/// </summary>
		/// <param name="dst"></param>
		/// <param name="src"></param>
		/// <param name="filter"></param>
		/// <param name="rect"></param>
		public void RenderSsao ( RenderTargetSurface ssaoDst, StereoEye stereoEye, Camera camera, DepthStencil2D depthSource, RenderTarget2D normalsSource )
		{
			SetDefaultRenderStates();

			using( new PixEvent("SSAO") ) {

				var ssaoParams = new SsaoParams();

				ssaoParams.View					=	camera.GetViewMatrix( stereoEye );	
				ssaoParams.Projection			=	camera.GetProjectionMatrix( stereoEye );	
				ssaoParams.InverseProjection	=	Matrix.Invert( ssaoParams.Projection );	
				paramsCB.SetData( ssaoParams );


				SetViewport( ssaoDst );
				device.SetTargets( null, ssaoDst );

				device.PipelineState			=	factory[ (int)(ShaderFlags.SSAO) ];

				device.VertexShaderResources[0] =	depthSource;
				device.PixelShaderResources[0]	=	depthSource;
				device.PixelShaderSamplers[0]	=	SamplerState.PointClamp;

				device.PixelShaderConstants[0]	=	paramsCB;
				device.PixelShaderConstants[1]	=	randomDirsCB;

				device.Draw( 3, 0 );
			}
			device.ResetStates();
		}
示例#32
0
        protected override void DrawCustomEffect()
        {
            if (!is2DTexInitialized)
            {
                // BB - The 2D textures have to be initialized here because of the multithreading
                // going on.  C# throws an exception when trying to access a UI element in a
                // different thread than it was created.  Since the draw is running on our own
                // thread and 2DTextures are UI elements, this causes problems.
                PresentationParameters pp     = Game.GraphicsDevice.PresentationParameters;
                SurfaceFormat          format = pp.BackBufferFormat;
                MultiSampleType        msType = pp.MultiSampleType;
                int msQuality = pp.MultiSampleQuality;

                //create the front and back position textures
                //check to make sure that there is a sutiable format supported
                SurfaceFormat rtFormat = SurfaceFormat.HalfVector4;
                if (isFormatSupported(SurfaceFormat.HalfVector4))
                {
                    rtFormat = SurfaceFormat.HalfVector4;
                }
                else if (isFormatSupported(SurfaceFormat.Vector4))
                {
                    rtFormat = SurfaceFormat.Vector4;
                }
                else if (isFormatSupported(SurfaceFormat.Rgba64))
                {
                    rtFormat = SurfaceFormat.Rgba64;
                }
                else //no suitable format found
                {
                    Debug.Assert(false, "Hardware must be SM 3.0 compliant and support RGBA16F, RGBA32F, or RGBA64. Error creating position render targets");
                }

                front2DTex = new RenderTarget2D(VolumetricRenderer.Game.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight,
                                                1, rtFormat, msType, msQuality);
                back2DTex = new RenderTarget2D(VolumetricRenderer.Game.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight,
                                               1, rtFormat, msType, msQuality);
                is2DTexInitialized = true;
            }
            else
            {
                //Game.GraphicsDevice.RenderState.AlphaBlendEnable = true;
                VolumetricRenderer.Game.GraphicsDevice.RenderState.SourceBlend      = Blend.SourceAlpha;
                VolumetricRenderer.Game.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;

                //draw wireframe
                if (drawWireframeBox)
                {
                    VolumetricRenderer.Game.GraphicsDevice.RenderState.CullMode = CullMode.None;
                    VolumetricRenderer.Game.GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;

                    effect.CurrentTechnique = effect.Techniques["WireFrame"];
                    base.DrawCustomEffect();

                    VolumetricRenderer.Game.GraphicsDevice.RenderState.CullMode = CullMode.CullClockwiseFace;
                    VolumetricRenderer.Game.GraphicsDevice.RenderState.FillMode = FillMode.Solid;
                }

                effect.CurrentTechnique = effect.Techniques[technique];
                effect.Parameters["Front"].SetValue(front2DTex.GetTexture());
                effect.Parameters["Back"].SetValue(back2DTex.GetTexture());
                effect.Parameters["DoLighting1"].SetValue(doLighting1);
                effect.Parameters["DoLighting2"].SetValue(doLighting2);
                effect.Parameters["DoLighting3"].SetValue(doLighting3);
                effect.Parameters["DoTransferFunction"].SetValue(doTransferFunction);
                base.DrawCustomEffect();
            }
        }
示例#33
0
        /// <summary>
        /// Used to load the tree texture by batching together the textures from XNB into a custom render target
        /// </summary>
        internal void loadTreeTexture()
        {
            // the list of seasons
            var seasons = new string[] { "spring", "summer", "fall", "winter" };

            // create a render target to prepare the tree texture to
            var texture = new RenderTarget2D(Game1.graphics.GraphicsDevice, 144, 96 * seasons.Length);

            // set the render target and clear the buffer
            Game1.graphics.GraphicsDevice.SetRenderTarget(texture);
            Game1.graphics.GraphicsDevice.Clear(Color.Transparent);

            // begin drawing session
            Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp);

            for (int s = 0; s < seasons.Length; s++)
            {
                // loop through the three trees in the game
                for (int i = 0; i < 3; i++)
                {
                    // get the current season
                    string season = seasons[s];

                    // spring and summer share the same texture for the pine tree
                    if (i == 2 && season.Equals("summer"))
                    {
                        season = "spring";
                    }

                    // load the texture into memory
                    string treeString = $"TerrainFeatures\\tree{i + 1}_{season}";

                    // get the current tree's texture
                    Texture2D currentTreeTexture = Game1.content.Load <Texture2D>(treeString);

                    // draw the trunk of the tree
                    Game1.spriteBatch.Draw(
                        currentTreeTexture,
                        new Vector2((48 * i) + 16, (96 * (s + 1)) - 32),
                        Tree.stumpSourceRect,
                        Color.White);

                    // draw the top of the tree
                    Game1.spriteBatch.Draw(
                        currentTreeTexture,
                        new Vector2(48 * i, 96 * s),
                        Tree.treeTopSourceRect,
                        Color.White);
                }
            }
            Game1.spriteBatch.End();

            // reset the render target back to the back buffer
            Game1.graphics.GraphicsDevice.SetRenderTarget(null);

            // create memory stream to save texture as PNG
            var stream = new MemoryStream();

            (texture as Texture2D).SaveAsPng(stream, texture.Width, texture.Height);

            // return our tree texture
            treeTexture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream);
        }
示例#34
0
        static public void LoadContent()
        {
            //DEVICE STATES
            Content      = currentGame.Content;
            graphics     = currentGame.graphics;
            device       = graphics.GraphicsDevice;
            spriteBatch  = new SpriteBatch(device);
            windowWidth  = defaultWindowWidth;
            windowHeight = defaultWindowHeight;

            //ASSETS
            #region ASSETS
            //2D
            Consolas18  = Content.Load <SpriteFont>(@"GUI\Consolas18");
            Verdana8    = Content.Load <SpriteFont>(@"GUI\Verdana8");
            cursorImage = Content.Load <Texture2D>(@"GUI\cursor");
            placeholder = Content.Load <Texture2D>(@"GUI\nick");
            crosshairs  = Content.Load <Texture2D>(@"GUI\crosshairs");

            //3D
            quadRenderer     = new QuadRenderComponent(device);
            effect           = Content.Load <Effect>(@"World\Effects\effects");
            nullDiffuse      = Content.Load <Texture2D>(@"World\Models\null_c");
            nullNormal       = Content.Load <Texture2D>(@"World\Models\null_n");
            nullSpecular     = Content.Load <Texture2D>(@"World\Models\null_s");
            skyboxModel      = Content.Load <Model>(@"World\Models\skybox");
            zombieModel      = Content.Load <Model>(@"World\Models\zombie");
            zombieSceneModel = Content.Load <Model>(@"World\Models\zombieScene");
            zombieDiffuse    = Content.Load <Texture2D>(@"World\Models\zombie_c");
            zombieNormal     = Content.Load <Texture2D>(@"World\Models\zombie_n");
            groundDiffuse    = Content.Load <Texture2D>(@"World\Models\ground_c");
            groundNormal     = Content.Load <Texture2D>(@"World\Models\ground_n");
            groundSpecular   = Content.Load <Texture2D>(@"World\Models\ground_s");
            ship1Model       = Content.Load <Model>(@"World\Models\ship1");
            ship1Diffuse     = Content.Load <Texture2D>(@"World\Models\ship1_c");
            ship1Normal      = Content.Load <Texture2D>(@"World\Models\ship1_n");
            ship1Specular    = Content.Load <Texture2D>(@"World\Models\ship1_s");
            ship2Model       = Content.Load <Model>(@"World\Models\ship2");
            ship2Diffuse     = Content.Load <Texture2D>(@"World\Models\ship2_c");
            ship2Normal      = Content.Load <Texture2D>(@"World\Models\ship2_n");
            ship2Specular    = Content.Load <Texture2D>(@"World\Models\ship2_s");
            sphereModel      = Content.Load <Model>(@"World\Models\sphere");
            arrowHead        = Content.Load <Model>(@"World\Models\arrowHead");
            arrowShaft       = Content.Load <Model>(@"World\Models\arrowShaft");

            cameraModel = Content.Load <Model>(@"World\Models\camera");
            #endregion

            //EFFECTS
            #region EFFECTS
            blackImage = new Texture2D(device, screenWidth, screenHeight, false, SurfaceFormat.Color);
            halfPixel  = new Vector2
            {
                X = 0.5f / (float)device.PresentationParameters.BackBufferWidth,
                Y = 0.5f / (float)device.PresentationParameters.BackBufferHeight
            };
            //INPUT
            World              = effect.Parameters["xWorld"];
            ViewProjection     = effect.Parameters["xViewProjection"];
            InvViewProjection  = effect.Parameters["xInvViewProjection"];
            CameraPosition     = effect.Parameters["xCameraPosition"];
            ColorMap           = effect.Parameters["xColorMap"];
            NormalMap          = effect.Parameters["xNormalMap"];
            DepthMap           = effect.Parameters["xDepthMap"];
            SpecularMap        = effect.Parameters["xSpecularMap"];
            ShadowMap          = effect.Parameters["xShadowMap"];
            LightMap           = effect.Parameters["xLightMap"];
            PreviousLightMap   = effect.Parameters["xPreviousLightMap"];
            ReflectMap         = effect.Parameters["xReflectMap"];
            PreviousReflectMap = effect.Parameters["xPreviousReflectMap"];
            HalfPixel          = effect.Parameters["xHalfPixel"];
            HalfPixel.SetValue(halfPixel);
            //LIGHT
            LightColor                = effect.Parameters["xLightColor"];
            LightIntensity            = effect.Parameters["xLightIntensity"];
            LightSpecFactor           = effect.Parameters["xLightSpecFactor"];
            LightSpecPower            = effect.Parameters["xLightSpecPower"];
            LightPosition             = effect.Parameters["xLightPosition"];
            LightDirection            = effect.Parameters["xLightDirection"];
            LightAngle                = effect.Parameters["xLightAngle"];
            LightDecay                = effect.Parameters["xLightDecay"];
            LightRadius               = effect.Parameters["xLightRadius"];
            LightViewProjection       = effect.Parameters["xLightViewProjection"];
            LightAttenuationConstant  = effect.Parameters["xLightAttC"];
            LightAttenuationLinear    = effect.Parameters["xLightAttL"];
            LightAttenuationQuadratic = effect.Parameters["xLightAttQ"];
            //MATERIAL
            MaterialAmbient   = effect.Parameters["xMaterialAmbient"];
            MaterialColor     = effect.Parameters["xMaterialColor"];
            MaterialDiffuse   = effect.Parameters["xMaterialDiffuse"];
            MaterialShininess = effect.Parameters["xMaterialShininess"];
            MaterialMatte     = effect.Parameters["xMaterialMatte"];
            //TECHNIQUES
            Texture      = effect.Techniques["Texture"];
            Scene        = effect.Techniques["Scene"];
            Ambient      = effect.Techniques["Ambient"];
            Directional  = effect.Techniques["Directional"];
            Point        = effect.Techniques["Point"];
            Spot         = effect.Techniques["Spot"];
            Spot2        = effect.Techniques["Spot2"];
            Shadow       = effect.Techniques["Shadow"];
            Final        = effect.Techniques["Final"];
            NoTexture    = effect.Techniques["NoTexture"];
            Basic        = effect.Techniques["BasicNoTexture"];
            TextureBlend = effect.Techniques["TextureBlend"];
            Black        = effect.Techniques["Black"];
            //RENDER TARGETS
            colorTarget       = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            normalTarget      = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            specularTarget    = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            depthTarget       = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Single, DepthFormat.Depth24);
            shadowTarget      = new RenderTarget2D(device, windowWidth * 2, windowHeight * 2, false, SurfaceFormat.Single, DepthFormat.Depth24);
            lightTarget       = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            prevLightTarget   = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            reflectTarget     = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            prevReflectTarget = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            debugTarget       = new RenderTarget2D(device, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            #endregion
        }
示例#35
0
 /// <summary>
 /// creates a new hard group element
 /// </summary>
 /// <param name="uiManager">the ui manager</param>
 /// <param name="position">the position</param>
 /// <param name="size">the size</param>
 /// <param name="layer">the draw layer</param>
 /// <param name="name">the element name</param>
 public HardGroupElement(UIManager uiManager, Vector2 position, Vector2 size, float layer, string name) : base(uiManager, position, size, layer, name)
 {
     Graphics = new RenderTarget2D(UIManager.Game.GraphicsDevice, (int)Size.X, (int)Size.Y);
 }
示例#36
0
        public void LoadContent()
        {
            content =
                new ContentManager(ScreenManager.Instance.Content.ServiceProvider, "Content");

            if (path != string.Empty)
            {
                texture = content.Load <Texture2D>(path);
            }

            font = content.Load <SpriteFont>(fontName);

            Vector2 dimensions = Vector2.Zero;

            if (texture != null)
            {
                dimensions.X = texture.Width;
            }
            dimensions.X += font.MeasureString(text).X;

            if (texture != null)
            {
                dimensions.Y = Math.Max(texture.Height, font.MeasureString(text).Y);
            }
            else
            {
                dimensions.Y = font.MeasureString(text).Y;
            }

            if (sourceRect == Rectangle.Empty)
            {
                sourceRect = new Rectangle(0, 0, (int)dimensions.X, (int)dimensions.Y);
            }

            renderTarget = new RenderTarget2D(ScreenManager.Instance.graphicsDevice,
                                              (int)dimensions.X, (int)dimensions.Y);

            ScreenManager.Instance.graphicsDevice.SetRenderTarget(renderTarget);
            ScreenManager.Instance.graphicsDevice.Clear(Color.Transparent);

            ScreenManager.Instance.spriteBatch.Begin();
            if (texture != null)
            {
                ScreenManager.Instance.spriteBatch.Draw(texture, Vector2.Zero, Color.White);
            }
            ScreenManager.Instance.spriteBatch.DrawString(font, text, Vector2.Zero, colorText);
            ScreenManager.Instance.spriteBatch.End();

            texture = renderTarget;

            ScreenManager.Instance.graphicsDevice.SetRenderTarget(null);

            SetEffect <FadeEffect>(ref fadeEffect);

            if (effects != string.Empty)
            {
                string[] split = effects.Split(':');
                foreach (string item in split)
                {
                    ActivateEffect(item);
                }
            }
        }
示例#37
0
        private void Rebuild(string fIn, string fOut)
        {
            // Check Args
            FileInfo fiIn = new FileInfo(fIn);

            if (!fiIn.Exists)
            {
                Console.WriteLine("File Does Not Exist");
                return;
            }
            FileInfo fiOut = new FileInfo(fOut);

            if (!fiOut.Directory.Exists)
            {
                Console.WriteLine("Output Directory Does Not Exist");
                return;
            }

            // Read Model
            Stream s = File.OpenRead(fiIn.FullName);

            VertexPositionNormalTexture[] verts;
            int[] inds;
            if (!ObjParser.TryParse(s, out verts, out inds, ParsingFlags.ConversionOpenGL))
            {
                s.Dispose();
                Console.WriteLine("Could Not Read Model");
                return;
            }
            s.Dispose();

            // Compute The AABB Of The Terrain
            BoundingBox aabb = ComputeAABB(verts);
            Vector3     mid  = aabb.Max + aabb.Min;
            Vector3     dif  = aabb.Max - aabb.Min;
            Vector3     top  = new Vector3(mid.X, aabb.Max.Y, mid.Z);

            mid          *= 0.5f;
            fx.FogStart   = 1f;
            fx.FogEnd     = aabb.Max.Y - aabb.Min.Y + 1f;
            fx.World      = Matrix.Identity;
            fx.View       = Matrix.CreateLookAt(top + Vector3.UnitY, mid, -Vector3.UnitZ);
            fx.Projection = Matrix.CreateOrthographic(dif.X, dif.Z, 0, dif.Y + 2f);

            // Append A Plane At The Bottom
            int vc = verts.Length, ic = inds.Length;

            Array.Resize(ref verts, verts.Length + 4);
            Array.Resize(ref inds, inds.Length + 6);
            inds[ic++]  = vc + 0;
            inds[ic++]  = vc + 1;
            inds[ic++]  = vc + 2;
            inds[ic++]  = vc + 2;
            inds[ic++]  = vc + 1;
            inds[ic++]  = vc + 3;
            verts[vc++] = new VertexPositionNormalTexture(
                new Vector3(aabb.Min.X, aabb.Min.Y, aabb.Min.Z),
                Vector3.UnitY, Vector2.Zero
                );
            verts[vc++] = new VertexPositionNormalTexture(
                new Vector3(aabb.Max.X, aabb.Min.Y, aabb.Min.Z),
                Vector3.UnitY, Vector2.UnitX
                );
            verts[vc++] = new VertexPositionNormalTexture(
                new Vector3(aabb.Min.X, aabb.Min.Y, aabb.Max.Z),
                Vector3.UnitY, Vector2.UnitY
                );
            verts[vc++] = new VertexPositionNormalTexture(
                new Vector3(aabb.Max.X, aabb.Min.Y, aabb.Max.Z),
                Vector3.UnitY, Vector2.One
                );

            // Create Model
            VertexBuffer vb = new VertexBuffer(G, VertexPositionNormalTexture.VertexDeclaration, verts.Length, BufferUsage.WriteOnly);

            vb.SetData(verts);
            IndexBuffer ib = new IndexBuffer(G, IndexElementSize.ThirtyTwoBits, inds.Length, BufferUsage.WriteOnly);

            ib.SetData(inds);

            // Render The Height
            if (rtHeight != null)
            {
                rtHeight.Dispose();
            }
            rtHeight = new RenderTarget2D(G, 4096, 4096, false, SurfaceFormat.Color, DepthFormat.Depth24);
            G.SetRenderTarget(rtHeight);
            G.SetVertexBuffer(vb);
            G.Indices = ib;
            fx.CurrentTechnique.Passes[0].Apply();
            G.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vb.VertexCount, 0, ib.IndexCount / 3);

            // Dispose Of Buffers
            G.SetRenderTarget(null);
            G.Clear(Color.Black);
            G.SetVertexBuffer(null);
            G.Indices = null;
            vb.Dispose();
            ib.Dispose();

            // Save The Image
            using (Stream os = File.Create(fiOut.FullName)) {
                rtHeight.SaveAsPng(os, rtHeight.Width, rtHeight.Height);
            }

            ShouldRebuild = false;
        }
示例#38
0
 public override void Removed()
 {
     Target?.Dispose();
     Target = null;
     base.Removed();
 }
示例#39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="srcDst">source and destination target</param>
        /// <param name="temporary">temporaru target for two pass filter</param>
        /*public void GaussBlur3x3( RenderTarget2D srcDst, RenderTarget2D temporary )
        {
            SetDefaultRenderStates();

            using( new PixEvent() ) {
                srcDst.SetViewport();
                rs.PixelShaderSamplers[0] = SamplerState.LinearPointClamp;

                rs.PipelineState			=	factory[ (int)ShaderFlags.GAUSS_BLUR_3x3 ];
                shaders.SetPixelShader( (int)(ShaderFlags.GAUSS_BLUR_3x3) );
                shaders.SetVertexShader( (int)(ShaderFlags.GAUSS_BLUR_3x3) );

                rs.SetTargets( null, temporary );
                rs.VertexShaderResources[0] = srcDst;
                rs.PixelShaderResources[0] = srcDst;

                rs.Draw( Primitive.TriangleList, 3, 0 );

                shaders.SetPixelShader( (int)(ShaderFlags.GAUSS_BLUR_3x3 | ShaderFlags.PASS2) );
                shaders.SetVertexShader( (int)(ShaderFlags.GAUSS_BLUR_3x3 | ShaderFlags.PASS2) );

                rs.SetTargets( null, srcDst );
                rs.VertexShaderResources[0] = temporary;
                rs.PixelShaderResources[0] = temporary;

                rs.Draw( Primitive.TriangleList, 3, 0 );
            }
            rs.ResetStates();
        }	*/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="srcDst"></param>
        /// <param name="temporary"></param>
        /// <param name="sigma"></param>
        /// <param name="kernelSize"></param>
        public void GaussBlur( RenderTarget2D srcDst, RenderTarget2D temporary, float sigma, int mipLevel )
        {
            var taps = GetGaussWeightsBuffer( sigma, mipLevel );

            SetDefaultRenderStates();

            gaussWeightsCB.SetData( taps );

            using( new PixEvent() ) {

                SetViewport(temporary.GetSurface(mipLevel));
                rs.SetTargets( null, temporary.GetSurface(mipLevel) );

                rs.PipelineState			=	factory[ (int)(ShaderFlags.GAUSS_BLUR | ShaderFlags.PASS1) ];
                rs.VertexShaderResources[0]	=	srcDst;
                rs.PixelShaderResources[0]	=	srcDst;
                rs.PixelShaderConstants[0]	=	gaussWeightsCB;

                rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;

                rs.Draw( 3, 0 );

                rs.VertexShaderResources[0] =	null;
                rs.PixelShaderResources[0]	=	null;

                SetViewport(srcDst.GetSurface(mipLevel));
                rs.SetTargets( null, srcDst.GetSurface(mipLevel) );

                rs.PipelineState			=	factory[ (int)(ShaderFlags.GAUSS_BLUR | ShaderFlags.PASS2) ];
                rs.VertexShaderResources[0] =	temporary;
                rs.PixelShaderResources[0]	=	temporary;
                rs.PixelShaderConstants[0]	=	gaussWeightsCB;

                rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;

                rs.Draw( 3, 0 );
            }
            rs.ResetStates();
        }
示例#40
0
 public void InitProjectorRT()
 {
     lightProjectorRT_?.Dispose();
     lightProjectorRT_ = new RenderTarget2D(Graphics.Device, Core.mainCam.MainRenderTarget.Width / System.shadowsQuality, Core.mainCam.MainRenderTarget.Height / System.shadowsQuality);
 }
示例#41
0
        public void StretchRect4x4( RenderTargetSurface dst, RenderTarget2D src, SamplerState filter = null )
        {
            SetDefaultRenderStates();

            using( new PixEvent() ) {

                rs.SetTargets( null, dst );
                SetViewport(dst);

                rs.PipelineState			=	factory[ (int)ShaderFlags.DOWNSAMPLE_2_4x4 ];
                rs.VertexShaderResources[0] =	src;
                rs.PixelShaderResources[0]	=	src;
                rs.PixelShaderSamplers[0]	=	filter ?? SamplerState.LinearPointClamp;

                rs.Draw( 3, 0 );
            }
            rs.ResetStates();
        }
示例#42
0
 public override void Initialize(ContentManager content)
 {
     m_Effect            = content.Load <Effect>("Shaders/PostProcessing/FXAA");
     m_SceneRenderTarget = GetRenderTarget();
 }
示例#43
0
		/// <summary>
		/// Load stuff here
		/// </summary>
		protected override void Initialize ()
		{
			base.Initialize();

			LoadContent();

			rt			=	new RenderTarget2D( GraphicsDevice, ColorFormat.Rgba8, 256,256, 1 );
			rtMS		=	new RenderTarget2D( GraphicsDevice, ColorFormat.Rgba8, 256,256, 4 );
			dsMS		=	new DepthStencil2D( GraphicsDevice, DepthFormat.D24S8, 256,256, 4 );

			dynamicTexture	=	new Texture2D( GraphicsDevice, 64,64, ColorFormat.Rgba8, false );

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

			InputDevice.KeyDown += InputDevice_KeyDown;
		}
示例#44
0
		public void DownSample4( RenderTarget2D dst, RenderTarget2D src )
		{
			SetDefaultRenderStates();

			using( new PixEvent("DownSample4") ) {

				dst.SetViewport();
				rs.SetTargets( null, dst );

				rs.PipelineState			=	factory[ (int)ShaderFlags.DOWNSAMPLE_4 ];
				rs.VertexShaderResources[0] =	src;
				rs.PixelShaderResources[0]	=	src;
				rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;

				rs.Draw( 3, 0 );
			}
			rs.ResetStates();
		}
示例#45
0
		public void Free ( RenderTarget2D target )
		{
			throw new NotImplementedException();
		}
示例#46
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="srcDst"></param>
		/// <param name="temporary"></param>
		/// <param name="?"></param>
		/// <param name="depthData"></param>
		/// <param name="normalData"></param>
		/// <param name="sigma"></param>
		/// <param name="mipLevel"></param>
		public void GaussBlurBilateral ( RenderTarget2D srcDst, RenderTarget2D temporary, ShaderResource depthData, ShaderResource normalData, float sigma, float sharpness, int mipLevel )
		{
			GaussBlurInternal( srcDst, temporary, sigma, sharpness, mipLevel, depthData, normalData );
		}
示例#47
0
        /// <summary>
        /// Creates GBuffer
        /// </summary>
        void CreateGBuffer()
        {
            SafeDispose( ref depthBuffer	 );
            SafeDispose( ref diffuseBuffer	 );
            SafeDispose( ref specularBuffer	 );
            SafeDispose( ref normalMapBuffer );
            SafeDispose( ref lightAccumBuffer );

            var vp		=	Game.GraphicsDevice.DisplayBounds;

            depthBuffer			=	new DepthStencil2D( Game.GraphicsDevice, DepthFormat.D24S8,		vp.Width, vp.Height );
            diffuseBuffer		=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba8,		vp.Width, vp.Height );
            specularBuffer		=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba8,		vp.Width, vp.Height );
            normalMapBuffer		=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgb10A2,	vp.Width, vp.Height );
            lightAccumBuffer	=	new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba16F,	vp.Width, vp.Height, true );
        }
示例#48
0
        /// <summary>
        /// Loads the background into the BGTiles rendertargets.
        /// </summary>
        /// <param name="bgMainNode"></param>
        public void Load(XElement bgMainNode)
        {
            // Get number of BGTiles per x and y
            BGTilesCnt = new Point((int)Math.Ceiling(Level.Instance.LevelSize.X / (float)MAX_TEX_SIZE), (int)Math.Ceiling(Level.Instance.LevelSize.Y / (float)MAX_TEX_SIZE));

            // Create the BGTiles
            BGTiles = new List <BGTile>();
            for (int y = 0; y < BGTilesCnt.Y; y++)
            {
                for (int x = 0; x < BGTilesCnt.X; x++)
                {
                    BGTiles.Add(new BGTile(new Rectangle(x * MAX_TEX_SIZE, y * MAX_TEX_SIZE, MAX_TEX_SIZE, MAX_TEX_SIZE)));
                }
            }

            #region Fill the BGTiles with a single tile if applicable
            string strfillSheet = bgMainNode.Attribute("fillTileSheet").Value;
            if (!string.IsNullOrEmpty(strfillSheet))
            {
                Texture2D fillTextureSheet = GraphicsLib.Str2TexFromStream(Engine.Instance.Graphics.GraphicsDevice, "TileSheets/" + strfillSheet);
                Rectangle fillSourceRect   = Common.Str2Rectangle(bgMainNode.Attribute("fillTileSource").Value);
                Point     tilesPerSheet    = new Point((int)Math.Ceiling(MAX_TEX_SIZE / (float)fillSourceRect.Width), (int)Math.Ceiling(MAX_TEX_SIZE / (float)fillSourceRect.Height));

                RenderTarget2D fillTexRenderTarget = new RenderTarget2D(Engine.Instance.Graphics.GraphicsDevice, fillSourceRect.Width, fillSourceRect.Height);
                Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(fillTexRenderTarget);
                Engine.Instance.SpriteBatch.Begin();
                Engine.Instance.SpriteBatch.Draw(fillTextureSheet, Vector2.Zero, fillSourceRect, Color.White);
                Engine.Instance.SpriteBatch.End();

                foreach (BGTile bgTile in BGTiles)
                {
                    Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(bgTile.RenderTarget);
                    Engine.Instance.SpriteBatch.Begin();

                    for (int y = 0; y < tilesPerSheet.Y; y++)
                    {
                        for (int x = 0; x < tilesPerSheet.X; x++)
                        {
                            Engine.Instance.SpriteBatch.Draw(fillTexRenderTarget, new Vector2(x * fillSourceRect.Width, y * fillSourceRect.Height), Color.White);
                        }
                    }
                    Engine.Instance.SpriteBatch.End();
                }
                fillTexRenderTarget.Dispose();
                Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(null); // after this point the rendertarget must be recreated before it is ever used again.
                GC.Collect();                                                  // Not sure if this forced collect collects the disposed rendertarget(s). Normally Dispose() releases resources immediately.
            }
            #endregion

            #region Load the actual tiles
            XElement tilesMainNode = bgMainNode.Element("Tiles");
            if (tilesMainNode != null)
            {
                foreach (XElement spriteSheetNode in tilesMainNode.Elements())
                {
                    // Load the texture sheet
                    Texture2D sheetTex = GraphicsLib.Str2TexFromStream(Engine.Instance.Graphics.GraphicsDevice, "TileSheets/" + spriteSheetNode.Attribute("name").Value);

                    // Loop all nodes in the xml (each node represents a tile)
                    foreach (XElement tileNode in spriteSheetNode.Elements())
                    {
                        Vector2   tileDestLoc       = Common.Str2Vector(tileNode.Attribute("location").Value);
                        Rectangle tileSourceRect    = Common.Str2Rectangle(tileNode.Attribute("sourceRectangle").Value);
                        Rectangle tileDestRectangle = new Rectangle((int)tileDestLoc.X, (int)tileDestLoc.Y, tileSourceRect.Width, tileSourceRect.Height);

                        foreach (BGTile bgTile in BGTiles)
                        {
                            if (tileDestRectangle.Intersects(bgTile.AABB))
                            {
                                Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(bgTile.RenderTarget);
                                Engine.Instance.SpriteBatch.Begin();
                                Engine.Instance.SpriteBatch.Draw(sheetTex, new Vector2(tileDestLoc.X - bgTile.AABB.X, tileDestLoc.Y - bgTile.AABB.Y), tileSourceRect, Color.White);
                                Engine.Instance.SpriteBatch.End();
                                Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(null);
                                break; // Unlike a sprite a tile can only be placed on a single BGTile. So break out to safe a little CPU.
                            }
                        }
                    }
                    GC.Collect(); // Not sure if this forced collect collects the disposed rendertarget(s). Normally Dispose() releases resources immediately.
                }
            }
            #endregion

            #region Load the objects (they may have any valid size defined by sourceRect) if applicable.
            XElement objectsMainNode = bgMainNode.Element("Objects");
            if (objectsMainNode != null)
            {
                RenderTarget2D objectRTarget = new RenderTarget2D(Engine.Instance.Graphics.GraphicsDevice, MAX_TEX_SIZE, MAX_TEX_SIZE);
                foreach (XElement objectNode in objectsMainNode.Elements())
                {
                    Texture2D objTextureSheet = GraphicsLib.Str2TexFromStream(Engine.Instance.Graphics.GraphicsDevice, "TileSheets/" + objectNode.Attribute("sheet").Value);
                    Rectangle objSourceRect   = Common.Str2Rectangle(objectNode.Attribute("sourceRectangle").Value);
                    Vector2   objDestination  = Common.Str2Vector(objectNode.Attribute("location").Value);
                    Rectangle objDestRect     = new Rectangle(objDestination.Xi(), objDestination.Yi(), objSourceRect.Width, objSourceRect.Height);

                    foreach (BGTile bgTile in BGTiles)
                    {
                        if (bgTile.AABB.Intersects(objDestRect))
                        {
                            Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(bgTile.RenderTarget);
                            Engine.Instance.SpriteBatch.Begin();
                            Engine.Instance.SpriteBatch.Draw(objTextureSheet, objDestination - new Vector2(bgTile.DrawLoc.X * bgTile.Index.X, bgTile.DrawLoc.Y * bgTile.Index.Y), objSourceRect, Color.White);
                            Engine.Instance.SpriteBatch.End();
                        }
                    }
                    Engine.Instance.Graphics.GraphicsDevice.SetRenderTarget(null);
                }
                objectRTarget.Dispose();
                GC.Collect(); // Not sure if this forced collect collects the disposed rendertarget(s). Normally Dispose() releases resources immediately.
            }
            #endregion
        }
 public void SetRenderTarget(RenderTarget2D renderTarget)
 {
 }
示例#50
0
        void updateResolutionScaler()
        {
            var designSize        = _designResolutionSize;
            var screenSize        = new Point(Screen.backBufferWidth, Screen.backBufferHeight);
            var screenAspectRatio = (float)screenSize.X / (float)screenSize.Y;

            var renderTargetWidth  = screenSize.X;
            var renderTargetHeight = screenSize.Y;

            var resolutionScaleX = (float)screenSize.X / (float)designSize.X;
            var resolutionScaleY = (float)screenSize.Y / (float)designSize.Y;

            var rectCalculated = false;

            // calculate the scale used by the PixelPerfect variants
            pixelPerfectScale = 1;
            if (_resolutionPolicy != SceneResolutionPolicy.None)
            {
                if ((float)designSize.X / (float)designSize.Y > screenAspectRatio)
                {
                    pixelPerfectScale = screenSize.X / designSize.X;
                }
                else
                {
                    pixelPerfectScale = screenSize.Y / designSize.Y;
                }

                if (pixelPerfectScale == 0)
                {
                    pixelPerfectScale = 1;
                }
            }

            switch (_resolutionPolicy)
            {
            case SceneResolutionPolicy.None:
                _finalRenderDestinationRect.X      = _finalRenderDestinationRect.Y = 0;
                _finalRenderDestinationRect.Width  = screenSize.X;
                _finalRenderDestinationRect.Height = screenSize.Y;
                rectCalculated = true;
                break;

            case SceneResolutionPolicy.ExactFit:
                // exact design size render texture
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;
                break;

            case SceneResolutionPolicy.NoBorder:
                // exact design size render texture
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;

                resolutionScaleX = resolutionScaleY = Math.Max(resolutionScaleX, resolutionScaleY);
                break;

            case SceneResolutionPolicy.NoBorderPixelPerfect:
                // exact design size render texture
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;

                // we are going to do some cropping so we need to use floats for the scale then round up
                pixelPerfectScale = 1;
                if ((float)designSize.X / (float)designSize.Y < screenAspectRatio)
                {
                    var floatScale = (float)screenSize.X / (float)designSize.X;
                    pixelPerfectScale = Mathf.ceilToInt(floatScale);
                }
                else
                {
                    var floatScale = (float)screenSize.Y / (float)designSize.Y;
                    pixelPerfectScale = Mathf.ceilToInt(floatScale);
                }

                if (pixelPerfectScale == 0)
                {
                    pixelPerfectScale = 1;
                }

                _finalRenderDestinationRect.Width  = Mathf.ceilToInt(designSize.X * pixelPerfectScale);
                _finalRenderDestinationRect.Height = Mathf.ceilToInt(designSize.Y * pixelPerfectScale);
                _finalRenderDestinationRect.X      = (screenSize.X - _finalRenderDestinationRect.Width) / 2;
                _finalRenderDestinationRect.Y      = (screenSize.Y - _finalRenderDestinationRect.Height) / 2;
                rectCalculated = true;

                break;

            case SceneResolutionPolicy.ShowAll:
                resolutionScaleX = resolutionScaleY = Math.Min(resolutionScaleX, resolutionScaleY);

                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;
                break;

            case SceneResolutionPolicy.ShowAllPixelPerfect:
                // exact design size render texture
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;

                _finalRenderDestinationRect.Width  = Mathf.ceilToInt(designSize.X * pixelPerfectScale);
                _finalRenderDestinationRect.Height = Mathf.ceilToInt(designSize.Y * pixelPerfectScale);
                _finalRenderDestinationRect.X      = (screenSize.X - _finalRenderDestinationRect.Width) / 2;
                _finalRenderDestinationRect.Y      = (screenSize.Y - _finalRenderDestinationRect.Height) / 2;
                rectCalculated = true;

                break;

            case SceneResolutionPolicy.FixedHeight:
                resolutionScaleX = resolutionScaleY;
                designSize.X     = Mathf.ceilToInt(screenSize.X / resolutionScaleX);

                // exact design size render texture for height but not width
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;
                break;

            case SceneResolutionPolicy.FixedHeightPixelPerfect:
                // start with exact design size render texture height. the width may change
                renderTargetHeight = designSize.Y;

                _finalRenderDestinationRect.Width  = Mathf.ceilToInt(designSize.X * resolutionScaleX);
                _finalRenderDestinationRect.Height = Mathf.ceilToInt(designSize.Y * pixelPerfectScale);
                _finalRenderDestinationRect.X      = (screenSize.X - _finalRenderDestinationRect.Width) / 2;
                _finalRenderDestinationRect.Y      = (screenSize.Y - _finalRenderDestinationRect.Height) / 2;
                rectCalculated = true;

                renderTargetWidth = (int)(designSize.X * resolutionScaleX / pixelPerfectScale);
                break;

            case SceneResolutionPolicy.FixedWidth:
                resolutionScaleY = resolutionScaleX;
                designSize.Y     = Mathf.ceilToInt(screenSize.Y / resolutionScaleY);

                // exact design size render texture for width but not height
                renderTargetWidth  = designSize.X;
                renderTargetHeight = designSize.Y;
                break;

            case SceneResolutionPolicy.FixedWidthPixelPerfect:
                // start with exact design size render texture width. the height may change
                renderTargetWidth = designSize.X;

                _finalRenderDestinationRect.Width  = Mathf.ceilToInt(designSize.X * pixelPerfectScale);
                _finalRenderDestinationRect.Height = Mathf.ceilToInt(designSize.Y * resolutionScaleY);
                _finalRenderDestinationRect.X      = (screenSize.X - _finalRenderDestinationRect.Width) / 2;
                _finalRenderDestinationRect.Y      = (screenSize.Y - _finalRenderDestinationRect.Height) / 2;
                rectCalculated = true;

                renderTargetHeight = (int)(designSize.Y * resolutionScaleY / pixelPerfectScale);

                break;
            }

            // if we didnt already calculate a rect (None and all pixel perfect variants calculate it themselves) calculate it now
            if (!rectCalculated)
            {
                // calculate the display rect of the RenderTarget
                var renderWidth  = designSize.X * resolutionScaleX;
                var renderHeight = designSize.Y * resolutionScaleY;

                _finalRenderDestinationRect = RectangleExt.fromFloats((screenSize.X - renderWidth) / 2, (screenSize.Y - renderHeight) / 2, renderWidth, renderHeight);
            }


            // set some values in the Input class to translate mouse position to our scaled resolution
            var scaleX = renderTargetWidth / (float)_finalRenderDestinationRect.Width;
            var scaleY = renderTargetHeight / (float)_finalRenderDestinationRect.Height;

            Input._resolutionScale  = new Vector2(scaleX, scaleY);
            Input._resolutionOffset = _finalRenderDestinationRect.Location;

            // resize our RenderTargets
            if (_sceneRenderTarget != null)
            {
                _sceneRenderTarget.Dispose();
            }
            _sceneRenderTarget = RenderTarget.create(renderTargetWidth, renderTargetHeight);

            // only create the destinationRenderTarget if it already exists, which would indicate we have PostProcessors
            if (_destinationRenderTarget != null)
            {
                _destinationRenderTarget.Dispose();
                _destinationRenderTarget = RenderTarget.create(renderTargetWidth, renderTargetHeight);
            }

            // notify the Renderers, PostProcessors and FinalRenderDelegate of the change in render texture size
            for (var i = 0; i < _renderers.Count; i++)
            {
                _renderers[i].onSceneBackBufferSizeChanged(renderTargetWidth, renderTargetHeight);
            }

            for (var i = 0; i < _afterPostProcessorRenderers.Count; i++)
            {
                _afterPostProcessorRenderers[i].onSceneBackBufferSizeChanged(renderTargetWidth, renderTargetHeight);
            }

            for (var i = 0; i < _postProcessors.Count; i++)
            {
                _postProcessors[i].onSceneBackBufferSizeChanged(renderTargetWidth, renderTargetHeight);
            }

            if (_finalRenderDelegate != null)
            {
                _finalRenderDelegate.onSceneBackBufferSizeChanged(renderTargetWidth, renderTargetHeight);
            }

            camera.onSceneRenderTargetSizeChanged(renderTargetWidth, renderTargetHeight);
        }
示例#51
0
        public SceneControl(ScreenComponent manager, string style = "")
            : base(manager, style)
        {
            player = manager.Player;
            camera = manager.Camera;
            assets = manager.Game.Assets;

            Manager = manager;

            simpleShader = manager.Game.Content.Load<Effect>("simple");
            sunTexture = assets.LoadTexture(typeof(ScreenComponent), "sun");

            //List<Bitmap> bitmaps = new List<Bitmap>();
            var definitions = DefinitionManager.Instance.GetBlockDefinitions();
            int textureCount = 0;
            foreach (var definition in definitions)
            {
                textureCount += definition.Textures.Length;
            }
            int bitmapSize = 128;
            blockTextures = new Texture2DArray(manager.GraphicsDevice, 1, bitmapSize, bitmapSize, textureCount);
            int layer = 0;
            foreach (var definition in definitions)
            {
                foreach (var bitmap in definition.Textures)
                {
                    System.Drawing.Bitmap texture = manager.Game.Assets.LoadBitmap(definition.GetType(), bitmap);

                    var scaled = texture;//new Bitmap(bitmap, new System.Drawing.Size(bitmapSize, bitmapSize));
                    int[] data = new int[scaled.Width * scaled.Height];
                    var bitmapData = scaled.LockBits(new System.Drawing.Rectangle(0, 0, scaled.Width, scaled.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, data, 0, data.Length);
                    blockTextures.SetData(data, layer);
                    scaled.UnlockBits(bitmapData);
                    layer++;
                }
            }

            /*int size = (int)Math.Ceiling(Math.Sqrt(bitmaps.Count));
            Bitmap blocks = new Bitmap(size * TEXTURESIZE, size * TEXTURESIZE);
            using (Graphics g = Graphics.FromImage(blocks))
            {
                int counter = 0;
                foreach (var bitmap in bitmaps)
                {
                    int x = counter % size;
                    int y = (int)(counter / size);
                    g.DrawImage(bitmap, new System.Drawing.Rectangle(TEXTURESIZE * x, TEXTURESIZE * y, TEXTURESIZE, TEXTURESIZE));
                    counter++;
                }
            }

            using (MemoryStream stream = new MemoryStream())
            {
                blocks.Save(stream, ImageFormat.Png);
                stream.Seek(0, SeekOrigin.Begin);
                blockTextures = Texture2D.FromStream(manager.GraphicsDevice, stream);
            }*/

            planet = ResourceManager.Instance.GetPlanet(0);

            // TODO: evtl. Cache-Size (Dimensions) VIEWRANGE + 1

            int range = ((int)Math.Pow(2, VIEWRANGE) - 2) / 2;
            localChunkCache = new LocalChunkCache(ResourceManager.Instance.GlobalChunkCache, VIEWRANGE, range);

            chunkRenderer = new ChunkRenderer[
                (int)Math.Pow(2, VIEWRANGE) * (int)Math.Pow(2, VIEWRANGE),
                planet.Size.Z];
            orderedChunkRenderer = new List<ChunkRenderer>(
                (int)Math.Pow(2, VIEWRANGE) * (int)Math.Pow(2, VIEWRANGE) * planet.Size.Z);

            for (int i = 0; i < chunkRenderer.GetLength(0); i++)
            {
                for (int j = 0; j < chunkRenderer.GetLength(1); j++)
                {
                    ChunkRenderer renderer = new ChunkRenderer(simpleShader, manager.GraphicsDevice, camera.Projection, blockTextures);
                    chunkRenderer[i, j] = renderer;
                    orderedChunkRenderer.Add(renderer);
                }
            }

            backgroundThread = new Thread(BackgroundLoop);
            backgroundThread.Priority = ThreadPriority.Lowest;
            backgroundThread.IsBackground = true;
            backgroundThread.Start();

            var selectionVertices = new[]
            {
                new VertexPositionColor(new Vector3(-0.001f, +1.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, +1.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, -0.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, -0.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, +1.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, +1.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, -0.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, -0.001f, -0.001f), Color.Black * 0.5f),
            };

            var billboardVertices = new[]
            {
                new VertexPositionTexture(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)),
                new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(0.5f, -0.5f, 0), new Vector2(1, 1)),
                new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)),
            };

            var selectionIndices = new short[]
            {
                0, 1, 0, 2, 1, 3, 2, 3,
                4, 5, 4, 6, 5, 7, 6, 7,
                0, 4, 1, 5, 2, 6, 3, 7
            };

            selectionLines = new VertexBuffer(manager.GraphicsDevice, VertexPositionColor.VertexDeclaration, selectionVertices.Length);
            selectionLines.SetData(selectionVertices);

            selectionIndexBuffer = new IndexBuffer(manager.GraphicsDevice, DrawElementsType.UnsignedShort, selectionIndices.Length);
            selectionIndexBuffer.SetData(selectionIndices);

            billboardVertexbuffer = new VertexBuffer(manager.GraphicsDevice, VertexPositionTexture.VertexDeclaration, billboardVertices.Length);
            billboardVertexbuffer.SetData(billboardVertices);

            sunEffect = new BasicEffect(manager.GraphicsDevice);
            sunEffect.TextureEnabled = true;

            selectionEffect = new BasicEffect(manager.GraphicsDevice);
            selectionEffect.VertexColorEnabled = true;

            MiniMapTexture = new RenderTarget2D(manager.GraphicsDevice, 128, 128, PixelInternalFormat.Rgb8); // , false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.PreserveContents);
            miniMapProjectionMatrix = Matrix.CreateOrthographic(128, 128, 1, 10000);
        }
 public void DrawTexture(RenderTarget2D texture, Rectangle rectangle, Color color, float layerDepth = 0)
 {
     _entities.Add(new TextureEntity2D(texture, rectangle, color, layerDepth));
 }
 protected override void BeginDraw()
 {
     base.BeginDraw();
     RenderTarget2D.BeginDraw();
 }
示例#54
0
        public void LoadContent()
        {
            content = new ContentManager(ScreenManager.Instance.Content.ServiceProvider, "Content");
            if (Path != String.Empty)
            {
                Texture = content.Load <Texture2D>(Path);
            }
            if (Name == "Counter")
            {
                font = content.Load <SpriteFont>("Font/counter");
            }
            else
            {
                font = content.Load <SpriteFont>(FontName);
            }
            Vector2 dimensionsTexture = Vector2.Zero;
            Vector2 dimensionsText    = Vector2.Zero;

            if (text.Count != 0)
            {
                for (int i = 0; i < text.Count; i++)
                {
                    this.listText.Add(Tuple.Create <string, Vector2, Color>(text[i], Vector2.Zero, Color.White));
                }
            }

            if (textPos.Count != 0)
            {
                for (int i = 0; i < textPos.Count; i++)
                {
                    listText[i] = Tuple.Create <string, Vector2, Color>(listText[i].Item1, textPos[i], Color.White);
                }
            }

            if (tColor.Count != 0)
            {
                for (int i = 0; i < tColor.Count; i++)
                {
                    Color          curColor        = new Color();
                    bool           found           = false;
                    PropertyInfo[] colorProperties = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public);
                    foreach (PropertyInfo info in colorProperties)
                    {
                        if (info.Name == tColor[i])
                        {
                            curColor = (Color)info.GetValue(null, null);
                            found    = true;
                            break;
                        }
                    }
                    if (found == true)
                    {
                        listText[i] = Tuple.Create <string, Vector2, Color>(listText[i].Item1, textPos[i], curColor);
                    }
                }
            }

            if (Texture != null)
            {
                dimensionsTexture.X += Texture.Width;
                dimensionsTexture.Y += Texture.Height;
                if (SourceRect == Rectangle.Empty)
                {
                    SourceRect = new Rectangle(0, 0, (int)dimensionsTexture.X, (int)dimensionsTexture.Y);
                }

                renderTarget = new RenderTarget2D(ScreenManager.Instance.GraphicsDevice, (int)dimensionsTexture.X, (int)dimensionsTexture.Y);
                ScreenManager.Instance.GraphicsDevice.SetRenderTarget(renderTarget);
                ScreenManager.Instance.GraphicsDevice.Clear(Color.Transparent);
                ScreenManager.Instance.SpriteBatch.Begin();
                ScreenManager.Instance.SpriteBatch.Draw(Texture, Vector2.Zero, Color.White);
                ScreenManager.Instance.SpriteBatch.End();
                Texture = renderTarget;
                ScreenManager.Instance.GraphicsDevice.SetRenderTarget(null);
            }

            // Effect
            setEffect <Effect.Fade>(ref fadeEffect);
            setEffect <Effect.SpriteSheetEffect>(ref SpriteSheetEffect);
            setEffect <Effect.SpriteSheetEffectEnemy>(ref SpriteSheetEffectEnemy);

            if (Effects != null && Effects != string.Empty)
            {
                string[] split = Effects.Split(':');
                foreach (string item in split)
                {
                    activateEffect(item);
                    IsActice = true;
                }
            }
        }
示例#55
0
		public void StretchRect4x4( RenderTargetSurface dst, RenderTarget2D src, SamplerState filter = null, bool flipToCubeFace = false )
		{
			SetDefaultRenderStates();

			using( new PixEvent("StretchRect4x4") ) {

				rs.SetTargets( null, dst );
				SetViewport(dst);
				
				if (flipToCubeFace) {
					rs.PipelineState		=	factory[ (int)(ShaderFlags.DOWNSAMPLE_2_4x4|ShaderFlags.TO_CUBE_FACE) ];
				} else {
					rs.PipelineState		=	factory[ (int)ShaderFlags.DOWNSAMPLE_2_4x4 ];
				}
				rs.VertexShaderResources[0] =	src;
				rs.PixelShaderResources[0]	=	src;
				rs.PixelShaderSamplers[0]	=	filter ?? SamplerState.LinearPointClamp;

				rs.Draw( 3, 0 );
			}
			rs.ResetStates();
		}
 protected override void EndDraw()
 {
     RenderTarget2D.EndDraw();
     base.EndDraw();
 }
示例#57
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="srcDst">source and destination target</param>
		/// <param name="temporary">temporaru target for two pass filter</param>
		/*public void GaussBlur3x3( RenderTarget2D srcDst, RenderTarget2D temporary )
		{
			SetDefaultRenderStates();

			using( new PixEvent() ) {
				srcDst.SetViewport();
				rs.PixelShaderSamplers[0] = SamplerState.LinearPointClamp;

				rs.PipelineState			=	factory[ (int)ShaderFlags.GAUSS_BLUR_3x3 ];
                shaders.SetPixelShader( (int)(ShaderFlags.GAUSS_BLUR_3x3) );
                shaders.SetVertexShader( (int)(ShaderFlags.GAUSS_BLUR_3x3) );

                rs.SetTargets( null, temporary );
				rs.VertexShaderResources[0] = srcDst;
				rs.PixelShaderResources[0] = srcDst;
                
				rs.Draw( Primitive.TriangleList, 3, 0 );

                shaders.SetPixelShader( (int)(ShaderFlags.GAUSS_BLUR_3x3 | ShaderFlags.PASS2) );
                shaders.SetVertexShader( (int)(ShaderFlags.GAUSS_BLUR_3x3 | ShaderFlags.PASS2) );

                rs.SetTargets( null, srcDst );
				rs.VertexShaderResources[0] = temporary;
				rs.PixelShaderResources[0] = temporary;

                rs.Draw( Primitive.TriangleList, 3, 0 );
			}
			rs.ResetStates();
		}	*/

		

		/// <summary>
		/// 
		/// </summary>
		/// <param name="srcDst"></param>
		/// <param name="temporary"></param>
		/// <param name="sigma"></param>
		/// <param name="mipLevel"></param>
		public void GaussBlur ( RenderTarget2D srcDst, RenderTarget2D temporary, float sigma, int mipLevel )
		{
			GaussBlurInternal( srcDst, temporary, sigma, 0f, mipLevel, null, null );
		}
示例#58
0
        private void Capture(GameTime gameTime)
        {
            if (this.mapData == null)
            {
                return;
            }

            var oldTarget = GraphicsDevice.GetRenderTargets();

            //检查显卡支持纹理大小
            var maxTextureWidth  = 4096;
            var maxTextureHeight = 4096;

            Rectangle oldRect = this.renderEnv.Camera.WorldRect;
            int       width   = Math.Min(oldRect.Width, maxTextureWidth);
            int       height  = Math.Min(oldRect.Height, maxTextureHeight);

            this.renderEnv.Camera.UseWorldRect = true;

            var target2d = new RenderTarget2D(this.GraphicsDevice, width, height, false, SurfaceFormat.Bgra32, DepthFormat.None);

            //计算一组截图区
            int horizonBlock  = (int)Math.Ceiling(1.0 * oldRect.Width / width);
            int verticalBlock = (int)Math.Ceiling(1.0 * oldRect.Height / height);

            byte[, ][] picBlocks = new byte[horizonBlock, verticalBlock][];
            for (int j = 0; j < verticalBlock; j++)
            {
                for (int i = 0; i < horizonBlock; i++)
                {
                    //计算镜头区域
                    this.renderEnv.Camera.WorldRect = new Rectangle(
                        oldRect.X + i * width,
                        oldRect.Y + j * height,
                        width,
                        height);

                    //绘制
                    GraphicsDevice.SetRenderTarget(target2d);
                    GraphicsDevice.Clear(Color.Black);
                    DrawScene(gameTime);
                    GraphicsDevice.SetRenderTarget(null);
                    //保存
                    Texture2D t2d  = target2d;
                    byte[]    data = new byte[target2d.Width * target2d.Height * 4];
                    t2d.GetData(data);
                    picBlocks[i, j] = data;
                }
            }
            target2d.Dispose();

            this.renderEnv.Camera.WorldRect    = oldRect;
            this.renderEnv.Camera.UseWorldRect = false;

            GraphicsDevice.SetRenderTargets(oldTarget);
            prepareCapture = false;

            captureTask = Task.Factory.StartNew(() =>
                                                SaveTexture(picBlocks, oldRect.Width, oldRect.Height, target2d.Width, target2d.Height)
                                                );
        }
示例#59
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="srcDst"></param>
		/// <param name="temporary"></param>
		/// <param name="sigma"></param>
		/// <param name="kernelSize"></param>
		void GaussBlurInternal ( RenderTarget2D srcDst, RenderTarget2D temporary, float sigma, float sharpness, int mipLevel, ShaderResource depthData, ShaderResource normalData )
		{
			var taps = GetGaussWeightsBuffer( sigma, mipLevel );

			SetDefaultRenderStates();

			gaussWeightsCB.SetData( taps );


			int combination	=	(int)ShaderFlags.GAUSS_BLUR;

			if (depthData!=null && normalData!=null) {
				combination |=	(int)ShaderFlags.BILATERAL;
			}



			using( new PixEvent("GaussBlur") ) {

				SetViewport(temporary.GetSurface(mipLevel));
				rs.SetTargets( null, temporary.GetSurface(mipLevel) );

				rs.PipelineState			=	factory[ combination|(int)ShaderFlags.PASS1 ];
				rs.VertexShaderResources[0]	=	srcDst;
				rs.PixelShaderResources[0]	=	srcDst;
				rs.PixelShaderResources[1]	=	depthData;
				rs.PixelShaderResources[2]	=	normalData;

				rs.PixelShaderConstants[0]	=	gaussWeightsCB;
				
				rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;
				rs.PixelShaderSamplers[1]	=	SamplerState.PointClamp;

				rs.Draw( 3, 0 );



				rs.VertexShaderResources[0] =	null;
				rs.PixelShaderResources[0]	=	null;

				SetViewport(srcDst.GetSurface(mipLevel));
				rs.SetTargets( null, srcDst.GetSurface(mipLevel) );

				rs.PipelineState			=	factory[ combination|(int)ShaderFlags.PASS2 ];
				rs.VertexShaderResources[0] =	temporary;
				rs.PixelShaderResources[0]	=	temporary;
				rs.PixelShaderResources[1]	=	depthData;
				rs.PixelShaderResources[2]	=	normalData;

				rs.PixelShaderConstants[0]	=	gaussWeightsCB;

				rs.PixelShaderSamplers[0]	=	SamplerState.LinearPointClamp;
				rs.PixelShaderSamplers[1]	=	SamplerState.PointClamp;

				rs.Draw( 3, 0 );
			}
			rs.ResetStates();
		}
示例#60
0
 public void Filter(RenderTarget2D source, Texture2D normalDepthMap)
 {
     Filter(source, normalDepthMap, source);
 }