public BasicLightableScene(Graphics.Graphics graphics) { int width, height; width = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Width; height = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Height; Camera = new Camera2D(); LightScene = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); BaseScene = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); _Entities = new List<IAnimatedEntity>(); _StaticLights = new List<LightSource>(); if (!Minecraft2D.ScaleGame) { graphics.ResolutionChanged += (sender, e) => { Console.WriteLine("[BasicLightableScene] Destroying and recreating render targets."); width = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Width; height = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Height; LightScene.Dispose(); BaseScene.Dispose(); LightScene = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); BaseScene = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); }; } }
public static Texture2D FromText(string text, SpriteFont font, Color color, Size size, bool multiLine, int lineStart, GraphicsDevice device) { string[] drawAbleText = multiLine ? text.Split(new string[1] { "\n" }, StringSplitOptions.None) : new string[1] { text }; RenderTarget2D target = new RenderTarget2D(device, size.Width, size.Height); SpriteBatch sb = new SpriteBatch(device); device.SetRenderTarget(target); device.Clear(Color.Transparent); sb.Begin(); for (int i = lineStart; i < drawAbleText.Length; i++) { float y = 1 + (i - lineStart) * font.GetHeight(); sb.DrawString(font, drawAbleText[i], new Vector2(1, y), color, 0f, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f); } sb.End(); device.SetRenderTarget(null); Texture2D texture = new Texture2D(device, size.Width, size.Height); Color[] colorData = target.GetColorData(); texture.SetData(colorData); target.Dispose(); sb.Dispose(); return texture; }
void LeakRepro() { for (int i = 0; i < 50; i++) { var rt = new RenderTarget2D( GraphicsDevice, 800, 480, false, SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents); GraphicsDevice.SetRenderTarget(rt); GraphicsDevice.Clear(Color.Green); GraphicsDevice.SetRenderTarget(null); MemoryStream ms = new MemoryStream(); rt.SaveAsPng(ms, 800, 480); ms.Close(); rt.Dispose(); } GC.Collect(); List<string> buttons = new List<string>(); buttons.Add("Close"); var message = string.Format( "Total memory: {0}\n" + "Used memory: {1}\n", DeviceExtendedProperties.GetValue("DeviceTotalMemory").ToString(), DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage").ToString() ); IAsyncResult ar = Guide.BeginShowMessageBox("Info", message, buttons, 0, MessageBoxIcon.None, null, null); Guide.EndShowMessageBox(ar); }
public RenderTarget2D UpdateCustomRenderTarget(RenderTarget2D renderTarget, IGameContext gameContext, SurfaceFormat? surfaceFormat, DepthFormat? depthFormat, int? multiSampleCount) { if (IsCustomRenderTargetOutOfDate(renderTarget, gameContext, surfaceFormat, depthFormat, multiSampleCount)) { if (renderTarget != null) { renderTarget.Dispose(); } if (gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferWidth == 0 && gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferHeight == 0) { return null; } renderTarget = new RenderTarget2D( gameContext.Graphics.GraphicsDevice, gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferWidth, gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferHeight, false, surfaceFormat ?? gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferFormat, depthFormat ?? gameContext.Graphics.GraphicsDevice.PresentationParameters.DepthStencilFormat, multiSampleCount ?? gameContext.Graphics.GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.PreserveContents); } return renderTarget; }
// Get Bitmap screenshot of specified XNA device public static Bitmap BitmapFromDevice( GraphicsDevice device ) { PresentationParameters pp = device.PresentationParameters; // get texture out of XNA device first RenderTarget2D deviceTexture = new RenderTarget2D( device, device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight, false, device.PresentationParameters.BackBufferFormat, pp.DepthStencilFormat ); device.SetRenderTarget( deviceTexture ); // convert texture to bitmap Bitmap bitmap = BitmapFromTexture( deviceTexture ); deviceTexture.Dispose( ); return bitmap; }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here #region Set up screenshots if (isScreenshot) { Color[] screenData = new Color[GraphicsDevice.PresentationParameters.BackBufferWidth * GraphicsDevice.PresentationParameters.BackBufferHeight]; screenShot = new RenderTarget2D(GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight); GraphicsDevice.SetRenderTarget(screenShot); map.Draw(spriteBatch); base.Draw(gameTime); GraphicsDevice.SetRenderTarget(null); //save to disk string fileName = DateTime.Now.ToString(); fileName = fileName.Replace('/', '-'); fileName = fileName.Replace(':', '-'); Stream stream = File.OpenWrite("\\Screens\\" + fileName + ".jpg"); screenShot.SaveAsJpeg(stream, 1280, 720); stream.Dispose(); screenShot.Dispose(); //reset the screenshot flag isScreenshot = false; } #endregion map.Draw(spriteBatch); base.Draw(gameTime); }
public RenderTarget2D UpdateRenderTarget(RenderTarget2D renderTarget, IGameContext gameContext) { if (IsRenderTargetOutOfDate(renderTarget, gameContext)) { if (renderTarget != null) { renderTarget.Dispose(); } renderTarget = new RenderTarget2D( gameContext.Graphics.GraphicsDevice, gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferWidth, gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferHeight, false, gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferFormat, gameContext.Graphics.GraphicsDevice.PresentationParameters.DepthStencilFormat); } return renderTarget; }
// We get the destinations of our particles by drawing our font to a render target and // reading back which pixels were set. List<Vector2> GetParticlePositions(GraphicsDevice device, SpriteFont font, string text) { Vector2 size = font.MeasureString(text) + new Vector2(0.5f); int width = (int)size.X; int height = (int)size.Y; // Create a temporary render target and draw the font on it. RenderTarget2D target = new RenderTarget2D(device, width, height); device.SetRenderTarget(target); device.Clear(Color.Black); SpriteBatch spriteBatch = new SpriteBatch(device); spriteBatch.Begin(); spriteBatch.DrawString(font, text, Vector2.Zero, Color.White); spriteBatch.End(); device.SetRenderTarget(null); // unset the render target // read back the pixels from the render target Color[] data = new Color[width * height]; target.GetData<Color>(data); target.Dispose(); // Return a list of points corresponding to pixels drawn by the font. The font size will affect the number of // points and the quality of the text. List<Vector2> points = new List<Vector2>(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Add all points that are lighter than 50% grey. The text is white, but due to anti-aliasing pixels // on the border may be shades of grey. if (data[width * y + x].R > 128) points.Add(new Vector2(x, y)); } } return points; }
public void SaveScreenshot(string filename) { Color[] screenData = new Color[GraphicsDevice.PresentationParameters.BackBufferWidth * GraphicsDevice.PresentationParameters.BackBufferHeight]; RenderTarget2D screenShot = new RenderTarget2D(GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight); GraphicsDevice.SetRenderTarget(screenShot); Draw(new GameTime()); GraphicsDevice.SetRenderTarget(null); int index = 0; string name = string.Concat(filename, "_", index, ".jpg"); while (File.Exists(name)) { index++; name = string.Concat(filename, "_", index, ".jpg"); } using (FileStream stream = new FileStream(name, FileMode.CreateNew)) { screenShot.SaveAsJpeg(stream, screenShot.Width, screenShot.Height); screenShot.Dispose(); } }
public static void GenerateTextureObjectFromPopText(out TextureObject output,int num, Color? color = null) { TextureAtlas atlas = EquestriEngine.AssetManager.GetTexture("{pop_text}") as TextureAtlas; string temp = "" + num; int width = 0, height = 0; for (int i = 0; i < temp.Length; i++) { var rect = atlas["num_" + temp[i]]; width += rect.Width; if (rect.Height > height) height = rect.Height; } RenderTarget2D _textTarget = new RenderTarget2D(Device_Ref,width,height); Device_Ref.SetRenderTarget(_textTarget); Device_Ref.Clear(color == null ? Color.Black : color.Value); Equestribatch batch = new Equestribatch(Device_Ref); batch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); int lastWidth = 0; for (int i = 0; i < temp.Length; i++) { batch.Draw(atlas.Texture, new Vector2(lastWidth, 0), atlas["num_" + temp[i]], Color.White); lastWidth += atlas["num_" + temp[i]].Width; } batch.End(); Device_Ref.SetRenderTarget(null); output = EquestriEngine.AssetManager.CreateTextureObjectFromTarget("{"+temp+"}", _textTarget); _textTarget.Dispose(); }
// Texture pass public Texture2D texturePass(Texture2D current, Texture2D texture, LayerBlendType blendType, float scale, float multiplier, Color baseColor) { // Initialize render targets and textures RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, current.Width, current.Height); Texture2D result = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); Color[] data = new Color[renderTarget.Width * renderTarget.Height]; for (int i = 0; i < (renderTarget.Width * renderTarget.Height); i++) data[i] = Color.Transparent; result.SetData<Color>(data); // Handle missing texture if (texture == null) { texture = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); texture.SetData<Color>(data); } // Initialize shader switch (blendType) { case LayerBlendType.Opaque: _textureEffect.CurrentTechnique = _textureEffect.Techniques["opaque"]; break; case LayerBlendType.Additive: _textureEffect.CurrentTechnique = _textureEffect.Techniques["additive"]; break; case LayerBlendType.Overlay: _textureEffect.CurrentTechnique = _textureEffect.Techniques["overlay"]; break; } _textureEffect.Parameters["canvasSize"].SetValue(new Vector2(current.Width, current.Height)); _textureEffect.Parameters["textureSize"].SetValue(new Vector2(texture.Width, texture.Height)); _textureEffect.Parameters["scale"].SetValue(scale); _textureEffect.Parameters["multiplier"].SetValue(multiplier); // Draw _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Transparent); _graphicsDevice.Textures[1] = texture; _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, _textureEffect); _spriteBatch.Draw(current, current.Bounds, baseColor); _spriteBatch.End(); _graphicsDevice.SetRenderTarget(null); // Save base texture renderTarget.GetData<Color>(data); result.SetData<Color>(data); // Cleanup renderTarget.Dispose(); return result; }
/// <summary> /// loads map for use in game /// </summary> public void LoadAndInitialize() { try { #region load map data XDocument doc = XDocument.Load(Parameters.FileName); XElement root = doc.Element("MapFile"); if (root == null) return; //sectors XElement sectors = root.Element("Sectors"); if (sectors == null) return; foreach (XElement sector in sectors.Elements("Sector")) { try { Sectors.Add(new MapSector(sector.Attribute("name").Value, new Vector2(float.Parse(sector.Attribute("x").Value.Replace('.', ',')), float.Parse(sector.Attribute("y").Value.Replace('.', ','))), float.Parse(sector.Attribute("range").Value.Replace('.', ',')))); foreach (XElement item in sector.Elements()) { try { switch (item.Name.LocalName) { case "Edge": Sectors[Sectors.Count - 1].Edges.Add(item.Attribute("name").Value); break; case "Neighbour": Sectors[Sectors.Count - 1].Neighbours.Add(item.Attribute("name").Value); break; case "Spawn": Sectors[Sectors.Count - 1].SpawnPoints.Add(item.Attribute("name").Value); break; } } catch { } } } catch { } } //points XElement points = root.Element("Points"); if (points == null) return; foreach (XElement point in points.Elements("Point")) { try { Points.Add(new MapPoint(point.Attribute("name").Value, new Vector2(float.Parse(point.Attribute("x").Value.Replace('.', ',')), float.Parse(point.Attribute("y").Value.Replace('.', ','))))); } catch { } } //edges XElement edges = root.Element("Edges"); if (edges == null) return; foreach (XElement edge in edges.Elements("Edge")) { try { Edges.Add(new MapEdge(edge.Attribute("name").Value, Points.Find(p => p.Name == edge.Attribute("start").Value), Points.Find(p => p.Name == edge.Attribute("end").Value))); } catch { } } //spawn points XElement spawns = root.Element("Spawns"); if (spawns == null) return; foreach (XElement spawn in spawns.Elements("Spawn")) { try { SpawnPoints.Add(new MapSpawnPoint(spawn.Attribute("name").Value, new Vector2(float.Parse(spawn.Attribute("x").Value.Replace('.', ',')), float.Parse(spawn.Attribute("y").Value.Replace('.', ','))), float.Parse(spawn.Attribute("rot").Value.Replace('.', ',')), int.Parse(spawn.Attribute("team").Value))); SpawnInUse.Add(false); } catch { } } //rectangles XElement rects = root.Element("Rects"); if (rects == null) return; foreach (XElement rect in rects.Elements("Rect")) { try { Rects.Add(new MapRect(rect.Attribute("name").Value, new Rectangle(int.Parse(rect.Attribute("x").Value), int.Parse(rect.Attribute("y").Value), int.Parse(rect.Attribute("w").Value), int.Parse(rect.Attribute("h").Value)), float.Parse(rect.Attribute("rot").Value.Replace('.', ',')), int.Parse(rect.Attribute("originX").Value), int.Parse(rect.Attribute("originY").Value))); } catch { } } //clean up //erase edges not assigned to any sector for (int i = 0; i < Edges.Count; ) { if (Sectors.FindIndex(s => s.Edges.FindIndex(e => Edges[i].Name == e) != -1) == -1) Edges.RemoveAt(i); else i++; } //erase spawns outside of every sector (spawn need to be inside of some sector for motor initialization) for (int i = 0; i < SpawnPoints.Count; ) { if (Sectors.FindIndex(s => s.IsInSector(SpawnPoints[i].Coords)) == -1) SpawnPoints.RemoveAt(i); else i++; } #endregion #region draw map and slice it //draw to memory Texture = UIParent.defaultTextures; RenderTarget2D mappicture = new RenderTarget2D(game.GraphicsDevice, (int)Parameters.Size.X, (int)Parameters.Size.Y, false, SurfaceFormat.Color, DepthFormat.None, 1, RenderTargetUsage.PreserveContents); SpriteBatch sb = new SpriteBatch(game.GraphicsDevice); game.GraphicsDevice.SetRenderTarget(mappicture); game.GraphicsDevice.Clear(Parameters.BackColor); sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); for (int x = 0; x < (int)(Parameters.Size.X / BackCrateTexture.Width + (Parameters.Size.X % BackCrateTexture.Width != 0 ? 1 : 0)); x++) for (int y = 0; y < (int)(Parameters.Size.Y / BackCrateTexture.Height + (Parameters.Size.Y % BackCrateTexture.Height != 0 ? 1 : 0)); y++) sb.Draw(Texture, new Vector2(x * BackCrateTexture.Width, y * BackCrateTexture.Height), BackCrateTexture, Parameters.BackCrateColor); for (int i = 0; i < Rects.Count; i++) Rects[i].Draw(ref sb, Parameters.BlockingColor); sb.End(); //slice map for (int x = 0; x < Slices.GetLength(0); x++) for (int y = 0; y < Slices.GetLength(1); y++) { Slices[x, y] = new MapSlice(game, new Rectangle((int)(x * Parameters.Slicing.X), (int)(y * Parameters.Slicing.Y), (int)Parameters.Slicing.X, (int)Parameters.Slicing.Y)); game.GraphicsDevice.SetRenderTarget(Slices[x, y].picture); game.GraphicsDevice.Clear(Color.Transparent); sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque); sb.Draw(mappicture, Vector2.Zero, Slices[x, y].PositionAndSize, Color.White); sb.End(); } game.GraphicsDevice.SetRenderTarget(null); mappicture.Dispose(); sb.Dispose(); Rects.Clear(); #endregion } catch { } }
public void applyShader(SpriteBatch batch, RenderTarget2D target, Effect effect) { RenderTarget2D bufferTarget = new RenderTarget2D(GraphicsDevice, target.Width, target.Height, false, GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24); GraphicsDevice.SetRenderTarget(bufferTarget); GraphicsDevice.Clear(Color.Transparent); batch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, effect); batch.Draw(target, Vector2.Zero, Color.White); batch.End(); Texture2D bufferTargetTex = bufferTarget; GraphicsDevice.SetRenderTarget(target); GraphicsDevice.Clear(Color.Black); batch.Begin(); batch.Draw(bufferTargetTex, Vector2.Zero, Color.White); batch.End(); GraphicsDevice.SetRenderTarget(null); bufferTarget.Dispose(); }
protected override void Update(GameTime gameTime) { IM.NewState(); currentScreen.Update(); if (currentScreen.CanTakePhoto && RM.IsDown(InputAction.AltFire) && RM.IsPressed(InputAction.Fire)) { int scale = 2; RenderTarget2D screenshot = new RenderTarget2D(GraphicsDevice, 800 * scale, 600 * scale, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); GraphicsDevice.Clear(Color.Black); GraphicsDevice.SetRenderTarget(screenshot); GraphicsDevice.Clear(Color.CornflowerBlue); currentScreen.Draw(); GraphicsDevice.SetRenderTarget(null); Color[] data = new Color[320 * 240 * scale * scale]; screenshot.GetData<Color>(0, new Rectangle(240 * scale, 180 * scale, 320 * scale, 240 * scale), data, 0, data.Length); Texture2D shot = new Texture2D(GraphicsDevice, 320 * scale, 240 * scale); shot.SetData<Color>(data); Photograph pg = new Photograph(shot); photos.Add(pg); screenshot.Dispose(); currentScreen.AddPhotoData(pg); } base.Update(gameTime); }
/// <summary> /// Uses <see cref="GraphicsDevice"/>, so call only during <see cref="Draw"/>. /// </summary> private void RefreshArenaRadarSilhouette() { if (Game.DataEngine.Arena == null) throw new InvalidOperationException("No active arena"); Dispose(); // Draw arena walls in one color in a radar-sized texture. var gfx = Game.GraphicsDeviceService.GraphicsDevice; var oldViewport = gfx.Viewport; int targetWidth = (int)_arenaDimensionsOnRadar.X; int targetHeight = (int)_arenaDimensionsOnRadar.Y; var gfxAdapter = gfx.Adapter; SurfaceFormat selectedFormat; DepthFormat selectedDepthFormat; int selectedMultiSampleCount; gfxAdapter.QueryRenderTargetFormat(GraphicsProfile.Reach, SurfaceFormat.Color, DepthFormat.None, 1, out selectedFormat, out selectedDepthFormat, out selectedMultiSampleCount); var maskTarget = new RenderTarget2D(gfx, targetWidth, targetHeight, false, selectedFormat, selectedDepthFormat); // Set up draw matrices. var view = Matrix.CreateLookAt(new Vector3(0, 0, 500), Vector3.Zero, Vector3.Up); var projection = Matrix.CreateOrthographicOffCenter(0, Game.DataEngine.Arena.Dimensions.X, 0, Game.DataEngine.Arena.Dimensions.Y, 10, 1000); // Set and clear our own render target. gfx.SetRenderTarget(maskTarget); gfx.Clear(ClearOptions.Target, Color.Transparent, 0, 0); // Draw the arena's walls. Game.GraphicsEngine.GameContent.RadarSilhouetteSpriteBatch.Begin(); foreach (var wall in Game.DataEngine.Arena.GobsInRelevantLayers.OfType<AW2.Game.Gobs.Wall>()) wall.DrawSilhouette(view, projection, Game.GraphicsEngine.GameContent.RadarSilhouetteSpriteBatch); Game.GraphicsEngine.GameContent.RadarSilhouetteSpriteBatch.End(); // Restore render target so what we can extract drawn pixels. // Create a copy of the texture in local memory so that a graphics device // reset (e.g. when changing resolution) doesn't lose the texture. gfx.SetRenderTarget(null); gfx.Viewport = oldViewport; var textureData = new Color[targetHeight * targetWidth]; maskTarget.GetData(textureData); ArenaRadarSilhouette = new Texture2D(gfx, targetWidth, targetHeight, false, SurfaceFormat.Color); ArenaRadarSilhouette.SetData(textureData); maskTarget.Dispose(); }
/// <summary> /// Creates a transparency atlas with which to texture the terrain. /// </summary> /// <param name="spriteBatch">A spritebatch to draw with.</param> public void CreateTransparencyAtlas(SpriteBatch spriteBatch) { DepthStencilBuffer OldDSBuffer = m_GraphicsDevice.DepthStencilBuffer; RenderTarget2D RTarget = new RenderTarget2D(m_GraphicsDevice, 1024, 256, 0, SurfaceFormat.Color, RenderTargetUsage.PreserveContents); DepthStencilBuffer DSBuffer = new DepthStencilBuffer(m_GraphicsDevice, 1024, 256, OldDSBuffer.Format); m_GraphicsDevice.DepthStencilBuffer = DSBuffer; m_GraphicsDevice.SetRenderTarget(0, RTarget); m_GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); for (int i = 0; i < 30; i = i + 2) { spriteBatch.Draw(m_TransA[i], new Rectangle(i*32, 0, m_TransA[i].Width, m_TransA[i].Height), Color.White); spriteBatch.Draw(m_TransA[i + 1], new Rectangle(i*32, 64, m_TransA[i + 1].Width, m_TransA[i + 1].Height), Color.White); } for (int i = 0; i < 30; i = i + 2) { spriteBatch.Draw(TransB[i], new Rectangle(i*32, 128, m_TransA[i].Width, m_TransA[i].Height), Color.White); spriteBatch.Draw(TransB[i + 1], new Rectangle(i*32, 192, m_TransA[i + 1].Width, m_TransA[i + 1].Height), Color.White); } Texture2D black = new Texture2D(m_GraphicsDevice, 1, 1); black.SetData<Color>(new Color[] { Color.Black }); spriteBatch.Draw(black, new Rectangle(1024-64, 0, 64, 256), Color.Black); //fill far end with black to cause no blend if adjacency bitmask is "0000" spriteBatch.End(); m_GraphicsDevice.SetRenderTarget(0, null); m_GraphicsDevice.DepthStencilBuffer = OldDSBuffer; TransAtlas = RTarget.GetTexture(); RTarget.Dispose(); //free up memory used by render target, as we have moved the data to a texture. }
// Radial scatter pass public Texture2D radialScatterPass( Texture2D current, float growthFactor, List<string> textureUIDs, bool scaleWithGrowthFactor, float a, float b, float intersections, float maxRadius, int arms, bool twinArms, bool flipArms, bool useAbsoluteTextureAngle, float absoluteTextureAngle, float relativeTextureAngle, float textureAngleJitter, float jitter, float centerJitter, Vector2 centerOffset, Color baseColor, float minTextureScale, float maxTextureScale, int randomRed, int randomGreen, int randomBlue, int randomAlpha) { Random rng = new Random(); // Initialize render targets and textures RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, current.Width, current.Height); Texture2D result = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); Color[] data = new Color[renderTarget.Width * renderTarget.Height]; // Load and validate textures List<Texture2D> textures = new List<Texture2D>(); foreach (string textureUID in textureUIDs) { Texture2D texture = ResourceManager.getTexture(textureUID); if (texture == null) return result; textures.Add(texture); } if (textures.Count == 0) return current; // Modify parameters based on growth factor (r is modified later) intersections *= growthFactor * growthFactor * growthFactor; arms = (int)Math.Ceiling(arms * growthFactor * growthFactor); maxRadius *= growthFactor; jitter *= Math.Max(growthFactor, 0.1f); centerJitter *= growthFactor; centerOffset *= growthFactor; // Draw _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Transparent); _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); _spriteBatch.Draw(current, current.Bounds, Color.White); float thetaIncrement = StasisMathHelper.pi * 2 / intersections; float armRotationIncrement = StasisMathHelper.pi * 2 / (float)arms; Vector2 center = centerOffset + new Vector2(current.Width, current.Height) / 2 + new Vector2((float)(rng.NextDouble() * 2 - 1), (float)(rng.NextDouble() * 2 - 1)) * centerJitter; for (int i = 0; i < arms; i++) { float theta = 0; float r = 0; while (r < maxRadius) { r = a * (float)Math.Pow(StasisMathHelper.phi, b * (2f / StasisMathHelper.pi) * theta) * growthFactor; if (r < maxRadius) { float textureScale = StasisMathHelper.floatBetween(minTextureScale, maxTextureScale, rng); float modifiedTheta = (theta + armRotationIncrement * i) * (flipArms ? -1f : 1f); float randomAngleValue = textureAngleJitter == 0 ? 0 : StasisMathHelper.floatBetween(-textureAngleJitter, textureAngleJitter, rng); float textureAngle; if (useAbsoluteTextureAngle) { textureAngle = absoluteTextureAngle + randomAngleValue; } else { textureAngle = relativeTextureAngle + modifiedTheta + randomAngleValue; } Vector2 j = new Vector2((float)(rng.NextDouble() * 2 - 1) * jitter, (float)(rng.NextDouble() * 2 - 1) * jitter); Texture2D texture = textures[rng.Next(textures.Count)]; Color actualColor = getRandomColor(baseColor, randomRed, randomGreen, randomBlue, randomAlpha, rng); //float textureScale = scaleWithGrowthFactor ? growthFactor : 1f; _spriteBatch.Draw(texture, new Vector2(r * (float)Math.Cos(modifiedTheta), r * (float)Math.Sin(modifiedTheta)) + j + center, texture.Bounds, actualColor, textureAngle, new Vector2(texture.Width, texture.Height) / 2, textureScale, SpriteEffects.None, 0); if (twinArms) { j = new Vector2((float)(rng.NextDouble() * 2 - 1) * jitter, (float)(rng.NextDouble() * 2 - 1) * jitter); _spriteBatch.Draw(texture, new Vector2(r * (float)Math.Cos(-modifiedTheta), r * (float)Math.Sin(-modifiedTheta)) + j + center, texture.Bounds, actualColor, -textureAngle, new Vector2(texture.Width, texture.Height) / 2, textureScale, SpriteEffects.None, 0); } } theta += thetaIncrement; } } _spriteBatch.End(); _graphicsDevice.SetRenderTarget(null); // Save render target into texture renderTarget.GetData<Color>(data); result.SetData<Color>(data); // Cleanup renderTarget.Dispose(); return result; }
// Leaves pass public Texture2D leavesPass( Texture2D current, float growthFactor, List<string> textureUids, Color baseColor ) { // Initialize render targets and textures RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, current.Width, current.Height); Texture2D result = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); Color[] data = new Color[renderTarget.Width * renderTarget.Height]; Random rng = new Random(); // Load and validate textures List<Texture2D> textures = new List<Texture2D>(); foreach (string textureUID in textureUids) { Texture2D texture = ResourceManager.getTexture(textureUID); if (texture == null) return result; textures.Add(texture); } if (textures.Count == 0) return current; float maxTextureSize = 256; float size = maxTextureSize * growthFactor; float maxRadius = (size / 2f) * 0.85f; float lowTint = 0.3f; if (size < 48f) { return current; } // Draw _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Transparent); _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); _spriteBatch.Draw(current, current.Bounds, Color.White); for (float tint = lowTint; tint < 1f; tint += 0.1f) { float radius = maxRadius * (1f - tint + lowTint); int leafCount = (int)((radius / 2f) * (size / maxTextureSize)); //Console.WriteLine("maxTextureSize: {0}, size: {1}, maxRadius: {2}, radius: {3}, tint: {4}, leafCount: {5}", maxTextureSize, size, maxRadius, radius, tint, leafCount); for (int n = 0; n < leafCount; n++) { // Calculate random position Texture2D leafTexture = textures[rng.Next(textures.Count)]; Vector2 position = new Vector2(StasisMathHelper.floatBetween(-1f, 1f, rng), StasisMathHelper.floatBetween(-1f, 1f, rng)) * radius; position += new Vector2(current.Width, current.Height) / 2; // Calculate shadow value //float shadowValue = Math.Max(metamer.budQuality, 0.5f); // Calculate color value float r = StasisMathHelper.floatBetween(0.9f, 1.2f, rng); float g = StasisMathHelper.floatBetween(0.9f, 1.1f, rng); float b = StasisMathHelper.floatBetween(0.9f, 1f, rng); Color finalColor = new Color(tint * r * (baseColor.R / 255f), tint * g * (baseColor.G / 255f), tint * b * (baseColor.B / 255f)); float angle = (float)(rng.NextDouble() * Math.PI * 2); float scale = StasisMathHelper.floatBetween(0.25f, 1f, rng); _spriteBatch.Draw(leafTexture, position, leafTexture.Bounds, finalColor, angle, new Vector2(leafTexture.Width, leafTexture.Height) / 2, scale, SpriteEffects.None, 0); } } _spriteBatch.End(); _graphicsDevice.SetRenderTarget(null); // Save render target into texture renderTarget.GetData<Color>(data); result.SetData<Color>(data); // Cleanup renderTarget.Dispose(); return result; }
public LightingTest(Graphics.Graphics graphics) { int width, height; width = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Width; height = graphics.GetGraphicsDeviceManager().GraphicsDevice.Viewport.Height; FullyLitWorld = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); Lightpass = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); Lights = new List<QuadLightSource>(); graphics.ResolutionChanged += (sender, e) => { width = e.Width; height = e.Height; Console.WriteLine("Destroying lighting test textures."); FullyLitWorld.Dispose(); FullyLitWorld = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); Lightpass.Dispose(); Lightpass = new RenderTarget2D(graphics.GetGraphicsDeviceManager().GraphicsDevice, width, height); }; }
public Texture2D CreateRoadAtlas(Texture2D[] input, SpriteBatch spriteBatch) { DepthStencilBuffer OldDSBuffer = m_GraphicsDevice.DepthStencilBuffer; RenderTarget2D RTarget = new RenderTarget2D(m_GraphicsDevice, 512, 512, 0, SurfaceFormat.Color, RenderTargetUsage.PreserveContents); DepthStencilBuffer DSBuffer = new DepthStencilBuffer(m_GraphicsDevice, 512, 512, OldDSBuffer.Format); m_GraphicsDevice.DepthStencilBuffer = DSBuffer; m_GraphicsDevice.SetRenderTarget(0, RTarget); m_GraphicsDevice.Clear(Color.TransparentBlack); spriteBatch.Begin(); for (int i = 0; i < 16; i++) { spriteBatch.Draw(input[i], new Rectangle((i%4) * 128, (int)(i/4.0)*128, 128, 128), Color.White); } spriteBatch.End(); m_GraphicsDevice.SetRenderTarget(0, null); m_GraphicsDevice.DepthStencilBuffer = OldDSBuffer; Texture2D Ret = RTarget.GetTexture(); RTarget.Dispose(); //free up memory used by render target, as we have moved the data to a texture. return Ret; }
public override void CopyContentsToMemory( PixelBox dst, FrameBuffer buffer ) { if ( ( dst.Left < 0 ) || ( dst.Right > Width ) || ( dst.Top < 0 ) || ( dst.Bottom > Height ) || ( dst.Front != 0 ) || ( dst.Back != 1 ) ) { throw new Exception( "Invalid box." ); } XFG.GraphicsDevice device = Driver.XnaDevice; //in 3.1, this was XFG.ResolveTexture2D, an actual RenderTarget provides the exact same //functionality, especially seeing as RenderTarget2D is a texture now. //the difference is surface is actually set on the device -DoubleA XFG.RenderTarget2D surface; byte[] data = new byte[ dst.ConsecutiveSize ]; int pitch = 0; if ( buffer == RenderTarget.FrameBuffer.Auto ) { buffer = RenderTarget.FrameBuffer.Front; } XFG.DisplayMode mode = device.DisplayMode; surface = new XFG.RenderTarget2D(device, mode.Width, mode.Height, false, XFG.SurfaceFormat.Rgba64, XFG.DepthFormat.Depth24Stencil8); //XFG.ResolveTexture2D( device, mode.Width, mode.Height, 0, XFG.SurfaceFormat.Rgba32 ); if ( buffer == RenderTarget.FrameBuffer.Front ) { // get the entire front buffer. This is SLOW!! device.SetRenderTarget(surface); if ( IsFullScreen ) { if ( ( dst.Left == 0 ) && ( dst.Right == Width ) && ( dst.Top == 0 ) && ( dst.Bottom == Height ) ) { surface.GetData<byte>( data ); } else { Rectangle rect = new Rectangle(); rect.Left = dst.Left; rect.Right = dst.Right; rect.Top = dst.Top; rect.Bottom = dst.Bottom; surface.GetData<byte>( 0, XnaHelper.ToRectangle( rect ), data, 0, 255 ); } } #if !( XBOX || XBOX360 ) else { Rectangle srcRect = new Rectangle(); srcRect.Left = dst.Left; srcRect.Right = dst.Right; srcRect.Top = dst.Top; srcRect.Bottom = dst.Bottom; // Adjust Rectangle for Window Menu and Chrome System.Drawing.Point point = new System.Drawing.Point(); point.X = (int)srcRect.Left; point.Y = (int)srcRect.Top; SWF.Control control = SWF.Control.FromHandle( _windowHandle ); point = control.PointToScreen( point ); srcRect.Top = point.Y; srcRect.Left = point.X; srcRect.Bottom += point.Y; srcRect.Right += point.X; surface.GetData<byte>( 0, XnaHelper.ToRectangle( srcRect ), data, 0, 255 ); } #endif } else { device.SetRenderTarget( surface ); if ( ( dst.Left == 0 ) && ( dst.Right == Width ) && ( dst.Top == 0 ) && ( dst.Bottom == Height ) ) { surface.GetData<byte>( data ); } else { Rectangle rect = new Rectangle(); rect.Left = dst.Left; rect.Right = dst.Right; rect.Top = dst.Top; rect.Bottom = dst.Bottom; surface.GetData<byte>( 0, XnaHelper.ToRectangle( rect ), data, 0, 255 ); } } PixelFormat format = XnaHelper.Convert( surface.Format ); if ( format == PixelFormat.Unknown ) { throw new Exception( "Unsupported format" ); } IntPtr dataPtr = Memory.PinObject( data ); PixelBox src = new PixelBox( dst.Width, dst.Height, 1, format, dataPtr ); src.RowPitch = pitch / PixelUtil.GetNumElemBytes( format ); src.SlicePitch = surface.Height * src.RowPitch; PixelConverter.BulkPixelConversion( src, dst ); Memory.UnpinObject( data ); surface.Dispose(); }
// Uniform scatter pass public Texture2D uniformScatterPass( Texture2D current, List<string> textureUIDs, float horizontalSpacing, float verticalSpacing, float jitter, Color baseColor, int randomRed, int randomGreen, int randomBlue, int randomAlpha) { Random rng = new Random(); // Initialize render targets and textures RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, current.Width, current.Height); Texture2D result = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); Color[] data = new Color[renderTarget.Width * renderTarget.Height]; // Load and validate textures List<Texture2D> textures = new List<Texture2D>(); foreach (string textureUID in textureUIDs) { Texture2D texture = ResourceManager.getTexture(textureUID); if (texture == null) return result; textures.Add(texture); } if (textures.Count == 0) return current; // Draw _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Transparent); _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); _spriteBatch.Draw(current, current.Bounds, Color.White); for (float i = 0; i <= current.Width; i += horizontalSpacing) { for (float j = 0; j <= current.Height; j += verticalSpacing) { Vector2 position = new Vector2(i, j) + new Vector2(StasisMathHelper.floatBetween(0, jitter, rng), StasisMathHelper.floatBetween(0, jitter, rng)); float angle = StasisMathHelper.floatBetween(-3.14f, 3.14f, rng); Texture2D texture = textures[rng.Next(0, textures.Count)]; Color actualColor = getRandomColor(baseColor, randomRed, randomGreen, randomBlue, randomAlpha, rng); _spriteBatch.Draw(texture, position, texture.Bounds, actualColor, angle, new Vector2(texture.Width, texture.Height) / 2, 1f, SpriteEffects.None, 0); } } _spriteBatch.End(); _graphicsDevice.SetRenderTarget(null); // Save render target into texture renderTarget.GetData<Color>(data); result.SetData<Color>(data); // Cleanup renderTarget.Dispose(); return result; }
/// <summary> /// Takes a capture and sends it to the clipboard /// </summary> protected Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[] CaptureArea(GridRectangle Rect, float Downsample) { Debug.Assert((Rect.Width / Downsample) < 4096 && (Rect.Height / Downsample) < 4096); Debug.Assert(this.PaintCallRefCount == 0); // Vector3 OriginalCameraLookAt = this.Camera.LookAt; //float OriginalCameraDistance = this.CameraDistance; // Rectangle OriginalVisibleRect = this.VisibleScreenRect; int Width = (int)Math.Round(Rect.Width / Downsample); int Height = (int)Math.Round(Rect.Height / Downsample); Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[] data = new Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[Width * Height]; try { // Initialize our RenderTarget ScreenshotRenderTarget = new RenderTarget2D(Device, Width, Height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); Device.SetRenderTarget(ScreenshotRenderTarget); bool OldAsynchTextureLoad = AsynchTextureLoad; AsynchTextureLoad = false; // Draw(Downsample); AsynchTextureLoad = OldAsynchTextureLoad; Device.SetRenderTarget(null); data = new Microsoft.Xna.Framework.Graphics.PackedVector.Byte4[ScreenshotRenderTarget.Width * ScreenshotRenderTarget.Height]; ScreenshotRenderTarget.GetData<Microsoft.Xna.Framework.Graphics.PackedVector.Byte4>(data); // Draw(); } finally { Device.SetRenderTarget(null); if (ScreenshotRenderTarget != null) { ScreenshotRenderTarget.Dispose(); ScreenshotRenderTarget = null; } // this.CameraLookAt = OriginalCameraLookAt; // this.CameraDistance = OriginalCameraDistance; } return data; }
// Edge scatter pass public Texture2D edgeScatterPass( Texture2D current, List<Vector2> polygonPoints, List<string> textureUIDs, Vector2 direction, float threshold, bool hardCutoff, float spacing, bool useAbsoluteAngle, float absoluteAngle, float relativeAngle, float angleJitter, float jitter, float scale, float scaleJitter, Color baseColor, int randomRed, int randomGreen, int randomBlue, int randomAlpha) { Random rng = new Random(); // Initialize render targets and textures RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, current.Width, current.Height); Texture2D result = new Texture2D(_graphicsDevice, renderTarget.Width, renderTarget.Height); Color[] data = new Color[renderTarget.Width * renderTarget.Height]; // Load and validate textures List<Texture2D> textures = new List<Texture2D>(); foreach (string textureUID in textureUIDs) { Texture2D texture = ResourceManager.getTexture(textureUID); if (texture == null) return result; textures.Add(texture); } if (textures.Count == 0) return current; // Validate polygon points if (polygonPoints == null || polygonPoints.Count < 3) return current; // Validate parameters spacing = Math.Max(0.05f, spacing); // Calculate half-texture offset Vector2 topLeft = polygonPoints[0]; Vector2 bottomRight = polygonPoints[0]; for (int i = 0; i < polygonPoints.Count; i++) { topLeft = Vector2.Min(polygonPoints[i], topLeft); bottomRight = Vector2.Max(polygonPoints[i], bottomRight); } // Draw _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Transparent); _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); _spriteBatch.Draw(current, current.Bounds, Color.White); bool hasDirection = direction.X != 0 || direction.Y != 0; for (int i = 0; i < polygonPoints.Count; i++) { Vector2 pointA = polygonPoints[i]; Vector2 pointB = polygonPoints[i == polygonPoints.Count - 1 ? 0 : i + 1]; Vector2 relative = pointB - pointA; Vector2 normal = relative; float perpDot = 0; normal.Normalize(); if (hasDirection) { direction.Normalize(); perpDot = direction.X * normal.Y - direction.Y * normal.X; } if (!hasDirection || perpDot > -threshold) { float relativeLength = relative.Length(); float currentPosition = 0f; while (currentPosition < relativeLength) { float angle = 0; Vector2 j = new Vector2((float)rng.NextDouble() * 2 - 1, (float)rng.NextDouble() * 2 - 1) * jitter; Vector2 position = pointA + normal * currentPosition + j; Texture2D texture = textures[rng.Next(textures.Count)]; Color actualColor = getRandomColor(baseColor, randomRed, randomGreen, randomBlue, randomAlpha, rng); float textureScale = StasisMathHelper.floatBetween(scale - scaleJitter, scale + scaleJitter, rng); if (useAbsoluteAngle) angle = absoluteAngle + StasisMathHelper.floatBetween(-angleJitter, angleJitter, rng); else angle = (float)Math.Atan2(relative.Y, relative.X) + relativeAngle + StasisMathHelper.floatBetween(-angleJitter, angleJitter, rng); _spriteBatch.Draw(texture, (position - topLeft) * Settings.BASE_SCALE, texture.Bounds, actualColor, angle, new Vector2(texture.Width, texture.Height) / 2, textureScale, SpriteEffects.None, 0); currentPosition += spacing; } } } _spriteBatch.End(); _graphicsDevice.SetRenderTarget(null); // Save render target into texture renderTarget.GetData<Color>(data); result.SetData<Color>(data); // Cleanup renderTarget.Dispose(); return result; }
public static Texture2D LoadTexture(GraphicsDevice device, Stream input) { Texture2D file = Texture2D.FromStream(device, input); // Setup a render target to hold our final texture which will have premulitplied alpha values RenderTarget2D result = new RenderTarget2D(device, file.Width, file.Height); device.SetRenderTarget(result); device.Clear(Color.Black); // Multiply each color by the source alpha, and write in just the color values into the final texture BlendState blendColor = new BlendState(); blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue; blendColor.AlphaDestinationBlend = Blend.Zero; blendColor.ColorDestinationBlend = Blend.Zero; blendColor.AlphaSourceBlend = Blend.SourceAlpha; blendColor.ColorSourceBlend = Blend.SourceAlpha; SpriteBatch spriteBatch = new SpriteBatch(device); spriteBatch.Begin(SpriteSortMode.Immediate, blendColor); spriteBatch.Draw(file, file.Bounds, Color.White); spriteBatch.End(); // Now copy over the alpha values from the PNG source texture to the final one, without multiplying them BlendState blendAlpha = new BlendState(); blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha; blendAlpha.AlphaDestinationBlend = Blend.Zero; blendAlpha.ColorDestinationBlend = Blend.Zero; blendAlpha.AlphaSourceBlend = Blend.One; blendAlpha.ColorSourceBlend = Blend.One; spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha); spriteBatch.Draw(file, file.Bounds, Color.White); spriteBatch.End(); // Release the GPU back to drawing to the screen device.SetRenderTarget(null); // RenderTarget2D are volatile and will be lost on screen resolution changes. // So instead of using this directly, we create a non-voliate Texture2D. // This is computationally slower, but should be safe as long as it is done // on load. Texture2D resultTexture = new Texture2D(device, file.Width, file.Height); Color[] resultContent = new Color[Convert.ToInt32(file.Width * file.Height)]; result.GetData(resultContent); resultTexture.SetData(resultContent); // Dispose of the RenderTarget2D immediately. result.Dispose(); return resultTexture; }
public void SaveCameraAsImage() { //Get the path! SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "Save Level as Image..."; dialog.Filter = "PNG Image File|*.png"; dialog.InitialDirectory = Ogmo.Project.SavedDirectory; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.Cancel) return; //Draw the level! float scale = Math.Min(Math.Min(4096.0f / Ogmo.Project.CameraSize.Width, 1), Math.Min(4096.0f / Ogmo.Project.CameraSize.Height, 1)); int width = (int)(scale * Ogmo.Project.CameraSize.Width); int height = (int)(scale * Ogmo.Project.CameraSize.Height); Matrix cameraMatrix = Matrix.CreateScale(scale) * Matrix.CreateTranslation(-Level.CameraPosition.X, -Level.CameraPosition.Y, 0); RenderTarget2D texture = new RenderTarget2D(Ogmo.EditorDraw.GraphicsDevice, width, height); Ogmo.EditorDraw.GraphicsDevice.SetRenderTarget(texture); Ogmo.EditorDraw.GraphicsDevice.Clear(Ogmo.Project.BackgroundColor.ToXNA()); for (int i = 0; i < LayerEditors.Count; i++) { if (Ogmo.Project.LayerDefinitions[i].Visible) { Ogmo.EditorDraw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, RasterizerState.CullNone, null, LayerEditors[i].DrawMatrix * cameraMatrix); LayerEditors[i].DrawLocal(false, 1); Ogmo.EditorDraw.SpriteBatch.End(); } } Ogmo.EditorDraw.GraphicsDevice.SetRenderTarget(null); //Save it then dispose it Stream stream = dialog.OpenFile(); texture.SaveAsPng(stream, width, height); stream.Close(); texture.Dispose(); }
/*not supported anymore in xna drop 6 /// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref Surface someObject) { if (someObject != null) someObject.Dispose(); someObject = null; } // Dispose(someObject) */ /// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref RenderTarget2D someObject) { if (someObject != null) { try { someObject.Dispose(); } // try catch {} // ignore } // if (someObject) someObject = null; }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { RenderTarget2D t = new RenderTarget2D(graphics.GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); GraphicsDevice.SetRenderTarget(t); GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); //spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);//!!!! INTERMEDIATE. sonst keine shader //Draw Background GraphicsUtil.street.DrawFrame(spriteBatch, new Vector2(0, 580), false); //draw Gameparts gameSim.draw(spriteBatch); //draw Particles particleSimulator.draw(spriteBatch); spriteBatch.Draw(GraphicsUtil.getWreckage().myTexture, mousePos, null, Color.White); //Draw Player if (playerSkeleton != null) { kinectDrawer.drawBody(playerSkeleton, spriteBatch); } //red updaten //effect.CurrentTechnique.Passes[2].Apply(); //spriteBatch.Draw(t, Vector2.Zero, Color.White); // auf die gesammte erstellte textur den graufilter anwenden oder bloodfilter spriteBatch.End(); spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);//!!!! INTERMEDIATE. sonst keine shader GraphicsDevice.SetRenderTarget(null); effect.CurrentTechnique.Passes[2].Apply(); spriteBatch.Draw(t, Vector2.Zero, Color.White); t.Dispose(); spriteBatch.End(); t.Dispose();// wenn nichtz gerufen--> out of memory base.Draw(gameTime); }
private Texture2D RenderTexture(int width, int height, Texture2D material, List<VertexPositionColorTexture[]> verticesFill) { // Removed Parameter -> , VertexPositionColor[] verticesOutline Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0f); PresentationParameters pp = this.device.PresentationParameters; RenderTarget2D texture = null; RenderTarget2D tempTarget = null; try { tempTarget = new RenderTarget2D(this.device, width, height, false, SurfaceFormat.Color, DepthFormat.None, pp.MultiSampleCount, RenderTargetUsage.DiscardContents); this.device.RasterizerState = RasterizerState.CullNone; this.device.SamplerStates[0] = SamplerState.LinearWrap; this.device.SetRenderTarget(tempTarget); this.device.Clear(Color.Transparent); this.effect.Projection = Matrix.CreateOrthographic(width, -height, 0f, 1f); this.effect.View = halfPixelOffset; // render shape; this.effect.TextureEnabled = true; this.effect.Texture = material; this.effect.VertexColorEnabled = true; this.effect.Techniques[0].Passes[0].Apply(); for (int i = 0; i < verticesFill.Count; ++i) { this.device.DrawUserPrimitives(PrimitiveType.TriangleList, verticesFill[i], 0, verticesFill[i].Length / 3); } this.effect.TextureEnabled = false; this.effect.Techniques[0].Passes[0].Apply(); // render outline // this.device.DrawUserPrimitives(PrimitiveType.LineList, verticesOutline, 0, verticesOutline.Length / 2); this.device.SetRenderTarget(null); texture = tempTarget; tempTarget = null; } catch (InvalidOperationException) { texture = null; } finally { if (tempTarget != null) { tempTarget.Dispose(); } } return texture; }
private void RecreateRenderTarget(ref RenderTarget2D Target, bool Dispose = true) { if(Target != null && !Target.IsDisposed && Dispose) Target.Dispose(); Target = new RenderTarget2D(GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None); }