protected Dispose ( bool disposing ) : void | ||
disposing | bool | |
리턴 | void |
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; }
protected override void Draw() { base.Draw(); var spriteBatch = new SpriteBatch(GraphicsDevice); _rendererCollection.Render(spriteBatch, GraphicsDevice.Viewport.Bounds, _textureContent); spriteBatch.Dispose(); }
/// <summary> /// Draw the screen /// </summary> /// <param name="gameTime">GameTime for this draw</param> public override void Draw(GameTime gameTime) { GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Red, 1.0f, 0); SpriteBatch batch = new SpriteBatch(GraphicsDevice); batch.Begin(); { batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White); } batch.End(); batch.Dispose(); }
public void Dispose() { if (batch != null) { batch.Dispose(); } isClose = true; rectLazy.Clear(); fillRectLazy.Clear(); lineLazy.Clear(); circleLazy.Clear(); polyLazy.Clear(); }
/// <summary> /// Draw the background image, the player's score, and a string indicating how to leave the screen. /// </summary> /// <param name="gameTime">GameTime for this update</param> public override void Draw(GameTime gameTime) { GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Red, 1.0f, 0); SpriteBatch batch = new SpriteBatch(GraphicsDevice); batch.Begin(); { batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White); batch.DrawString(font, "Your score is...", new Vector2(100, 25), Color.White); batch.DrawString(font, pointsString, new Vector2(50, 60), Color.White); batch.DrawString(font, "Press " + SnailsPace.inputManager.getKeyBinding("MenuToggle") + " to continue...", new Vector2(250, 500), Color.White); } batch.End(); batch.Dispose(); }
/// <summary> /// Draw the background image, the player's score, and a string indicating how to leave the screen. /// </summary> /// <param name="gameTime">GameTime for this update</param> public override void Draw(GameTime gameTime) { GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Red, 1.0f, 0); SpriteBatch batch = new SpriteBatch(GraphicsDevice); batch.Begin(); { batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White); batch.DrawString(font, mapName, new Vector2(100, 25), Color.White); List<Score> pointsScores; SnailsPace.highScoreList.pointsScores.TryGetValue(mapName, out pointsScores); List<Score> accuracyScores; SnailsPace.highScoreList.pointsScores.TryGetValue(mapName, out accuracyScores); List<Score>.Enumerator pointEnumerator = pointsScores.GetEnumerator(); List<Score>.Enumerator accuracyEnumerator = accuracyScores.GetEnumerator(); for (int i = 0; i < pointsScores.Count; i++) { pointEnumerator.MoveNext(); batch.DrawString(font, pointEnumerator.Current.score + " " + pointEnumerator.Current.name, new Vector2(50, 50 + (25 * i)), Color.White); } } batch.End(); batch.Dispose(); }
public void GenerateAssets() { SpriteBatch spriteBatch = new SpriteBatch(m_GraphicsDevice); ClearOldData(); GenerateCityMesh(m_GraphicsDevice); //generates the city mesh CreateTextureAtlas(spriteBatch); //generates the many atlases used when rendering the city. CreateTransparencyAtlas(spriteBatch); RoadAtlas = CreateRoadAtlas(m_Roads, spriteBatch); RoadCAtlas = CreateRoadAtlas(m_RoadCorners, spriteBatch); spriteBatch.Dispose(); RegenData = false; //don't do this again next frame... }
private void DrawSprites(float HB, float VB) { SpriteBatch spriteBatch = new SpriteBatch(m_GraphicsDevice); spriteBatch.Begin(); if (!m_Zoomed && m_HandleMouse) { //draw rectangle to indicate zoom position DrawLine(m_WhiteLine, new Vector2(m_MouseState.X - 15, m_MouseState.Y - 11), new Vector2(m_MouseState.X - 15, m_MouseState.Y + 11), spriteBatch, 2, 1); DrawLine(m_WhiteLine, new Vector2(m_MouseState.X - 16, m_MouseState.Y + 10), new Vector2(m_MouseState.X + 16, m_MouseState.Y + 10), spriteBatch, 2, 1); DrawLine(m_WhiteLine, new Vector2(m_MouseState.X + 15, m_MouseState.Y + 11), new Vector2(m_MouseState.X + 15, m_MouseState.Y - 11), spriteBatch, 2, 1); DrawLine(m_WhiteLine, new Vector2(m_MouseState.X + 16, m_MouseState.Y - 10), new Vector2(m_MouseState.X - 16, m_MouseState.Y - 10), spriteBatch, 2, 1); } else if (m_Zoomed && m_HandleMouse) { if (m_LotCost != 0) { float X = GetHoverSquare()[0]; float Y = GetHoverSquare()[1]; //TODO: Should this have opacity? Might have to change this to render only when hovering over a lot. DrawTooltip(spriteBatch, m_LotCost.ToString() + "§", new Vector2(X, Y), 0f); } else { if (m_CurrentLot != null) { float X = GetHoverSquare()[0]; float Y = GetHoverSquare()[1]; bool Online = ProtoHelpers.GetBit(m_CurrentLot.flags, 0); string OnlineStr = (Online == true) ? "Online" : "Offline"; //TODO: Should this have opacity? Might have to change this to render only when hovering over a lot. DrawTooltip(spriteBatch, GameFacade.Strings.GetString("215", "3", new string[]{m_CurrentLot.name}) + "\n" + OnlineStr, new Vector2(X, Y), 0f); } } } if (m_ZoomProgress < 0.5) { spriteBatch.End(); spriteBatch.Dispose(); return; } float iScale = (float)m_ScrWidth / (HB * 2); float treeWidth = (float)(Math.Sqrt(2)*(128.0/144.0)); float treeHeight = treeWidth*(80/128); Vector2 mid = CalculateR(new Vector2(m_ViewOffX, -m_ViewOffY)); //determine approximate tile position at center of screen mid.X -= 6; mid.Y += 6; float[] bounds = new float[] { (float)Math.Round(mid.X - 19), (float)Math.Round(mid.Y - 19), (float)Math.Round(mid.X + 19), (float)Math.Round(mid.Y + 19) }; Texture2D img = m_Forest; float fade = Math.Max(0, Math.Min(1, (m_ZoomProgress - 0.4f) * 2)); DrawTileBorders(iScale, spriteBatch); for (short y = (short)bounds[1]; y < bounds[3]; y++) //iterate over tiles close to the approximate tile position at the center of the screen and draw any trees/houses on them { if (y < 0 || y > 511) continue; for(short x = (short)bounds[0]; x < bounds[2]; x++) { if (x < 0 || x > 511) continue; float elev = (m_ElevationData[(y * 512 + x) * 4] + m_ElevationData[(y * 512 + Math.Min(x + 1, 511)) * 4] + m_ElevationData[(Math.Min(y + 1, 511) * 512 + Math.Min(x + 1, 511)) * 4] + m_ElevationData[(Math.Min(y + 1, 511) * 512 + x) * 4]) / 4; //elevation of sprite is the average elevation of the 4 vertices of the tile var xy = transformSpr(iScale, new Vector3((float)(x + 0.5), elev / 12.0f, (float)(y + 0.5))); if (xy.X > -64 && xy.X < m_ScrWidth + 64 && xy.Y > -40 && xy.Y < m_ScrHeight + 40) //is inside screen { Vector2 loc = new Vector2( x, y ); LotTileEntry house; if (m_CityLookup.ContainsKey(loc)) { house = m_CityLookup[loc]; } else { house = null; } if (house != null) //if there is a house here, draw it { if ((house.flags & 1) > 0) { PathTile(x, y, iScale, (float)(0.3+Math.Sin(4*Math.PI*(m_SpotOsc%1))*0.15)); } double scale = treeWidth * iScale / 128.0; if (!m_HouseGraphics.ContainsKey(house.lotid)) { //no house graphic found - request one! m_HouseGraphics[house.lotid] = m_DefaultHouse; m_CityData.RetrieveHouseGFX(house.lotid, m_HouseGraphics, m_GraphicsDevice); } Texture2D lotImg = m_HouseGraphics[house.lotid]; spriteBatch.Draw(lotImg, new Rectangle((int)(xy.X - 64.0 * scale), (int)(xy.Y - 32.0 * scale), (int)(scale * 128), (int)(scale * 64)), m_TintColor); } else //if there is no house, draw the forest that's meant to be here. { double fType = m_ForestTypes[m_ForestTypeData[(y * 512 + x)]]; double fDens = Math.Round((double)(m_ForestDensityData[(y * 512 + x) * 4] * 4 / 255)); if (!(fType == -1 || fDens == 0)) { double scale = treeWidth * iScale / 128.0; spriteBatch.Draw(m_Forest, new Rectangle((int)(xy.X - 64.0 * scale), (int)(xy.Y - 56.0 * scale), (int)(scale * 128), (int)(scale * 80)), new Rectangle((int)(128 * (fDens - 1)), (int)(80 * fType), 128, 80), m_TintColor); //draw correct forest from forest atlas } } } } } Draw2DPoly(); //fill the tiles below online houses BEFORE actually drawing the houses and trees! spriteBatch.End(); spriteBatch.Dispose(); }
/// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref SpriteBatch someObject) { if (someObject != null) someObject.Dispose(); someObject = null; }
/// <summary> /// Render the scene. /// </summary> /// <param name="objects">All GameObjects to be rendered.</param> /// <param name="strings">Strings of text to render.</param> /// <param name="gameTime">The current time.</param> public void render(List<Objects.GameObject> objects, List<Objects.Text> strings, GameTime gameTime) { SnailsPace.getInstance().GraphicsDevice.RenderState.CullMode = CullMode.None; SnailsPace.getInstance().GraphicsDevice.RenderState.DepthBufferEnable = true; SnailsPace.getInstance().GraphicsDevice.RenderState.DepthBufferWriteEnable = true; SnailsPace.getInstance().GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0); Vector3 cameraTargetPosition = getCameraTargetPosition(); cameraTargetPosition.Z = cameraTargetPosition.Z * debugZoom; if (!cameraPosition.Equals(cameraTargetPosition)) { // If the camera is not at it's target position, move the camera toward the target. float elapsedTime = (float)Math.Min(gameTime.ElapsedRealTime.TotalSeconds, 1); Vector3 cameraDifference = cameraTargetPosition - cameraPosition; Vector3 cameraPositionMovement = Vector3.Zero; cameraPositionMovement.X = calculateCameraMovement(cameraDifference.X, elapsedTime); cameraPositionMovement.Y = calculateCameraMovement(cameraDifference.Y, elapsedTime); cameraPositionMovement.Z = calculateCameraMovement(cameraDifference.Z, elapsedTime); cameraPosition = cameraPosition + cameraPositionMovement; // Keep the camera inside the level's specified bounds. float cameraStopXDistance = (float)(1000 * Math.Tan(45 / 2.0)); float cameraStopYDistance = (float)(1000 * Math.Tan(MathHelper.PiOver4 / 2.0)); for (int i = 1; i < cameraBounds.Length; i++) { if (cameraBounds[i].X == cameraBounds[i - 1].X) { // This is a vertical bounding line, check the camera position to the left and right. if ((cameraBounds[i].X < 0) && (cameraPosition.X - cameraStopXDistance < cameraBounds[i].X)) cameraPosition.X = cameraBounds[i].X + cameraStopXDistance; else if ((cameraBounds[i].X > 0) && (cameraPosition.X + cameraStopXDistance > cameraBounds[i].X)) cameraPosition.X = cameraBounds[i].X - cameraStopXDistance; } else if (cameraBounds[i].Y == cameraBounds[i - 1].Y) { // This is a horizontal bounding line, check the camera position on top and bottom. if ((cameraBounds[i].Y > 0) && (cameraPosition.Y + cameraStopYDistance > cameraBounds[i].Y)) cameraPosition.Y = cameraBounds[i].Y - cameraStopYDistance; else if ((cameraBounds[i].Y < 0) && (cameraPosition.Y - cameraStopYDistance < cameraBounds[i].Y)) cameraPosition.Y = cameraBounds[i].Y + cameraStopYDistance; } } } Viewport viewport = SnailsPace.getInstance().GraphicsDevice.Viewport; float aspectRatio = (float)viewport.Width / (float)viewport.Height; cameraProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip); cameraView = Matrix.CreateLookAt(cameraPosition, cameraPosition + Vector3.Forward, Vector3.Up); BoundingFrustum viewFrustum = new BoundingFrustum(cameraView * cameraProjection); #if DEBUG // If debugging bounding boxes, make sure the list exists. if (boundingBoxVertices == null) { boundingBoxVertices = new List<VertexPositionColorTexture[]>(); } else { boundingBoxVertices.Clear(); } #endif if (objects != null) { List<Objects.GameObject>.Enumerator objectEnumerator = objects.GetEnumerator(); SnailsPace.getInstance().GraphicsDevice.VertexDeclaration = new VertexDeclaration(SnailsPace.getInstance().GraphicsDevice, VertexPositionColorTexture.VertexElements); while (objectEnumerator.MoveNext()) { // Iterate over each GameObject and draw it. drawObject(objectEnumerator.Current, viewFrustum); #if DEBUG if (SnailsPace.debugBoundingBoxes && objectEnumerator.Current.collidable) { // Draw a bounding box if we are debugging bounding boxes and this object has one. Objects.GameObjectBounds boundingBox = objectEnumerator.Current.bounds; Vector2[] boxVertices = boundingBox.Points; VertexPositionColorTexture[] visualBoxVertices = new VertexPositionColorTexture[boxVertices.Length + 2]; visualBoxVertices[0].Color = boundingBoxCenterColor; visualBoxVertices[0].Position = new Vector3(objectEnumerator.Current.position, 1); visualBoxVertices[visualBoxVertices.Length - 1].Position = new Vector3(boxVertices[0], 1); visualBoxVertices[visualBoxVertices.Length - 1].Color = boundingBoxColor; for (int boxVertexIndex = 0; boxVertexIndex < boxVertices.Length; boxVertexIndex++) { visualBoxVertices[boxVertexIndex + 1].Position = new Vector3(boxVertices[boxVertexIndex], 1); visualBoxVertices[boxVertexIndex + 1].Color = boundingBoxColor; } boundingBoxVertices.Add(visualBoxVertices); } #endif } objectEnumerator.Dispose(); #if DEBUG if (SnailsPace.debugTriggers) { // Draw a trigger box if we are debugging triggers. List<Objects.Trigger>.Enumerator triggers = Engine.map.triggers.GetEnumerator(); while (triggers.MoveNext()) { // For each trigger, draw a box and add it to the list with the bounding boxes. Objects.GameObjectBounds boundingBox = triggers.Current.bounds; Vector2[] boxVertices = boundingBox.Points; VertexPositionColorTexture[] visualBoxVertices = new VertexPositionColorTexture[boxVertices.Length + 2]; visualBoxVertices[0].Color = triggerBoxCenterColor; visualBoxVertices[0].Position = new Vector3(triggers.Current.position, 1); visualBoxVertices[visualBoxVertices.Length - 1].Position = new Vector3(boxVertices[0], 10); visualBoxVertices[visualBoxVertices.Length - 1].Color = triggerBoxColor; for (int boxVertexIndex = 0; boxVertexIndex < boxVertices.Length; boxVertexIndex++) { visualBoxVertices[boxVertexIndex + 1].Position = new Vector3(boxVertices[boxVertexIndex], 1); visualBoxVertices[boxVertexIndex + 1].Color = triggerBoxColor; } boundingBoxVertices.Add(visualBoxVertices); } triggers.Dispose(); } // TODO: this probably isn't how we want to do this if we end up using more than one effect Effect effect = getOrCreateEffect("Resources/Effects/effects"); effect.CurrentTechnique = effect.Techniques["Colored"]; effect.Parameters["xView"].SetValue(cameraView); effect.Parameters["xProjection"].SetValue(cameraProjection); effect.Parameters["xWorld"].SetValue(Matrix.Identity); effect.Begin(); // Draw all the bounding and trigger boxes. List<VertexPositionColorTexture[]>.Enumerator boundingBoxEnumerator = boundingBoxVertices.GetEnumerator(); while (boundingBoxEnumerator.MoveNext()) { IEnumerator<EffectPass> effectPassEnumerator = effect.CurrentTechnique.Passes.GetEnumerator(); while (effectPassEnumerator.MoveNext()) { effectPassEnumerator.Current.Begin(); // The vertex declaration needs to be set before it gets here or it will fail. SnailsPace.getInstance().GraphicsDevice.DrawUserPrimitives<VertexPositionColorTexture>(PrimitiveType.TriangleFan, boundingBoxEnumerator.Current, 0, boundingBoxEnumerator.Current.Length - 2); effectPassEnumerator.Current.End(); } effectPassEnumerator.Dispose(); } boundingBoxEnumerator.Dispose(); effect.End(); #endif } if (strings == null) { strings = new List<Objects.Text>(); } SpriteBatch batch = new SpriteBatch(SnailsPace.getInstance().GraphicsDevice); batch.Begin(); // Draw HUD { batch.Draw(Engine.healthIcon, new Rectangle(0, 0, 32, 32), Color.White); batch.Draw(Engine.healthBar, new Rectangle(32, 8, (int)((Player.helix.health / (float)Player.helix.maxHealth) * 300), 16), Color.White); batch.Draw(Engine.fuelIcon, new Rectangle(0, 24, 32, 32), Color.White); batch.Draw(Engine.fuelBar, new Rectangle(32, 32, (int)((Player.helix.fuel / Player.helix.maxFuel) * 300), 16), Color.White); // If we're fighting a boss, draw them a health bar. if (Engine.boss != null) { int screenWidth = SnailsPace.videoConfig.getInt("width"); int screenHeight = SnailsPace.videoConfig.getInt("height"); int barWidth = 600, barHeight = 60, barMarginX = 18, barMarginY = 20; int barx = (screenWidth - barWidth) / 2; int bary = (screenHeight - barHeight) - 14; batch.Draw(Engine.bossHealthShadow, new Rectangle(barx, bary, barWidth, barHeight), Color.White); batch.Draw(Engine.bossHealthBar, new Rectangle(barx + barMarginX, bary + barMarginY, (int)((Engine.boss.health / (float)Engine.boss.maxHealth) * barWidth - 2 * barMarginX), barMarginY), Color.White); } } // Draw the Inventory { Texture2D weaponTable = SnailsPace.getInstance().Content.Load<Texture2D>("Resources/Textures/WeaponTable"); Texture2D separator = SnailsPace.getInstance().Content.Load<Texture2D>("Resources/Textures/PauseScreen"); SpriteFont font = SnailsPace.getInstance().Content.Load<SpriteFont>("Resources/Fonts/Score"); int y = 64; int bigSize = 32; int smallSize = 24; Objects.Weapon currentWeapon = Player.helix.weapon; for(int i = 0; i < Player.helix.inventory.Length; i++) { // Draw each item in the player's inventory. batch.Draw(separator, new Rectangle(8, y++, 32, 1), new Rectangle(1, 0, 1, 1), Color.White); Objects.Weapon weapon = Player.helix.inventory[i]; if (weapon == null) { y += 8; continue; } int tx = weapon.sprite.animationStart % 4, ty = weapon.sprite.animationStart / 4; Rectangle spot, source; if (currentWeapon == weapon) { // If this is the weapon we're using, make it pop out by displaying it bigger and with white text. Color textColor = Color.White; spot = new Rectangle(0, y, bigSize * 2, bigSize); strings.Add(new Objects.Text(weapon.name, font, new Vector2(bigSize * 2, y), new Vector2(0.5f, 0.5f), textColor)); strings.Add(new Objects.Text((weapon.ammunition != -1 ? weapon.ammunition.ToString() : "Inf"), font, new Vector2(bigSize * 2, y + bigSize / 2.25f), new Vector2(0.5f, 0.5f), textColor)); y += bigSize; } else { // This isn't the weapon we're using, give it a smaller icon and gray text. Color textColor = Color.LightGray; spot = new Rectangle(0, y, smallSize * 2, smallSize); strings.Add(new Objects.Text(weapon.name, font, new Vector2(smallSize * 2, y), new Vector2(0.4f, 0.4f), textColor)); strings.Add(new Objects.Text((weapon.ammunition != -1 ? weapon.ammunition.ToString() : "Inf"), font, new Vector2(smallSize * 2, y + smallSize / 2.25f), new Vector2(0.4f, 0.4f), textColor)); y += smallSize; } source = new Rectangle(tx * 128, ty * 64, 128, 64); batch.Draw(weaponTable, spot, source, Color.White); } batch.Draw(separator, new Rectangle(8, y++, 32, 1), new Rectangle(0, 0, 1, 1), Color.White); } // Draw text strings List<Objects.Text>.Enumerator textEnumerator = strings.GetEnumerator(); while (textEnumerator.MoveNext()) { batch.DrawString(textEnumerator.Current.font, textEnumerator.Current.content, textEnumerator.Current.position, textEnumerator.Current.color, textEnumerator.Current.rotation, Vector2.Zero, textEnumerator.Current.scale, SpriteEffects.None, 0); } textEnumerator.Dispose(); batch.End(); batch.Dispose(); }
protected override void Draw(IXnaGameTime gameTime) { gameTime.ThrowIfNull("gameTime"); var spriteBatch = new SpriteBatch(GraphicsDevice); _rendererCollection.Render(spriteBatch, gameTime, _fontContent, _textureContent); spriteBatch.Dispose(); }
/// <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 static Texture2D Stretch(this Texture2D texture, Size size) { RenderTarget2D target = new RenderTarget2D(texture.GraphicsDevice, size.Width, size.Height); SpriteBatch sb = new SpriteBatch(texture.GraphicsDevice); texture.GraphicsDevice.SetRenderTarget(target); texture.GraphicsDevice.Clear(Color.Transparent); sb.Begin(); sb.Draw(texture, new Rectangle(0, 0, size.Width, size.Height), Color.White); sb.End(); texture.GraphicsDevice.SetRenderTarget(null); Texture2D result = new Texture2D(texture.GraphicsDevice, size.Width, size.Height); result.SetData(target.GetColorData()); target.Dispose(); sb.Dispose(); return result; }
public static Texture2D RenderOnto(this Texture2D texture, Size size, Vector2 position = default(Vector2), float rotation = 0, Vector2 scale = default(Vector2)) { RenderTarget2D target = new RenderTarget2D(texture.GraphicsDevice, size.Width, size.Height); SpriteBatch sb = new SpriteBatch(texture.GraphicsDevice); texture.GraphicsDevice.SetRenderTarget(target); texture.GraphicsDevice.Clear(Color.Transparent); sb.Begin(); sb.Draw(texture, position, null, Color.White, rotation, Vector2.Zero, scale == default(Vector2) ? Vector2.One : scale, SpriteEffects.None, 1f); sb.End(); texture.GraphicsDevice.SetRenderTarget(null); Texture2D result = new Texture2D(texture.GraphicsDevice, size.Width, size.Height); result.SetData(target.GetColorData()); target.Dispose(); sb.Dispose(); return result; }
static public 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); spriteBatch.Dispose(); file.Dispose(); #if IOS return result as Texture2D; #else // 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); result.Dispose(); // Dispose of the RenderTarget2D immediately. return resultTexture; #endif }