public static bool AddNewLevelBlock(Level level, Vector3 coordinate, Texture2D heightMap, Texture2D alphaMap, string[] detailTextureNames, Vector2[] uvOffsets, Vector2[] uvScales) { if (level.Contains(coordinate)) { return false; } Color[] heightColors = new Color[HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_VERTICES]; if (heightMap.Width != HeightMapMesh.NUM_SIDE_VERTICES || heightMap.Height != HeightMapMesh.NUM_SIDE_VERTICES) { RenderTarget2D resizedHeightMap = new RenderTarget2D(GraphicsManager.Device, HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES); GraphicsManager.Device.SetRenderTarget(resizedHeightMap); GraphicsManager.SpriteBatch.Begin(); GraphicsManager.SpriteBatch.Draw(heightMap, new Rectangle(0, 0, HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES), Color.White); GraphicsManager.SpriteBatch.End(); GraphicsManager.Device.SetRenderTarget(null); resizedHeightMap.GetData(heightColors); } else { heightMap.GetData(heightColors); } float[,] heights = new float[HeightMapMesh.NUM_SIDE_VERTICES, HeightMapMesh.NUM_SIDE_VERTICES]; for (int i = 0; i < heightColors.Length; i++) { heights[i % HeightMapMesh.NUM_SIDE_VERTICES, i / HeightMapMesh.NUM_SIDE_VERTICES] = ConvertColorToFloat(heightColors[i]); } if (alphaMap.Height != HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD || alphaMap.Width != HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD) { RenderTarget2D resizedAlphaMap = new RenderTarget2D(GraphicsManager.Device, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD); GraphicsManager.Device.SetRenderTarget(resizedAlphaMap); GraphicsManager.SpriteBatch.Begin(); GraphicsManager.SpriteBatch.Draw(alphaMap, new Rectangle(0, 0, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD, HeightMapMesh.NUM_SIDE_VERTICES * HeightMapMesh.NUM_SIDE_TEXELS_PER_QUAD), Color.White); GraphicsManager.SpriteBatch.End(); GraphicsManager.Device.SetRenderTarget(null); alphaMap = resizedAlphaMap; } HeightMapMesh heightMapMesh = new HeightMapMesh(heights, alphaMap, detailTextureNames, uvOffsets, uvScales); AssetLibrary.AddHeightMap(level.Name + coordinate.ToString(), heightMapMesh); level.AddNewBlock(coordinate); return true; }
public static void PreMultiplyAlpha(this Texture2D texture) { //Setup a render target to hold our final texture which will have premulitplied color values var result = new RenderTarget2D(texture.GraphicsDevice, texture.Width, texture.Height); texture.GraphicsDevice.SetRenderTarget(result); texture.GraphicsDevice.Clear(Color.Black); // Using default blending function // (source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha) // Destination is zero so the reduces to // (source × Blend.SourceAlpha) // So this multiplies our color values by the alpha value and draws it to the RenderTarget var blendColor = new BlendState { ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue, AlphaDestinationBlend = Blend.Zero, ColorDestinationBlend = Blend.Zero, AlphaSourceBlend = Blend.SourceAlpha, ColorSourceBlend = Blend.SourceAlpha }; var spriteBatch = new SpriteBatch(texture.GraphicsDevice); spriteBatch.Begin(SpriteSortMode.Immediate, blendColor); spriteBatch.Draw(texture, texture.Bounds, Color.White); spriteBatch.End(); // Simply copy over the alpha channel var blendAlpha = new BlendState { ColorWriteChannels = ColorWriteChannels.Alpha, AlphaDestinationBlend = Blend.Zero, ColorDestinationBlend = Blend.Zero, AlphaSourceBlend = Blend.One, ColorSourceBlend = Blend.One }; spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha); spriteBatch.Draw(texture, texture.Bounds, Color.White); spriteBatch.End(); texture.GraphicsDevice.SetRenderTarget(null); var t = new Color[result.Width * result.Height]; result.GetData(t); texture.SetData(t); }
// TODO: Record at certain framerate! (possibly every nth frame) public void RecordFrame(RenderTarget2D rt, Matrix view) { if (!IsRecording()) return; rt.GetData<Vector4>(tmpBufferRT); for (int i = 0; i < 640 * 480; i++) { float depth = tmpBufferRT[i].X; unsafe { int idepth = *((int*)&depth); // little endian tmpBufferDepth[4 * i + 0] = (byte)((idepth >> 0) & 255); tmpBufferDepth[4 * i + 1] = (byte)((idepth >> 8) & 255); tmpBufferDepth[4 * i + 2] = (byte)((idepth >> 16) & 255); tmpBufferDepth[4 * i + 3] = (byte)((idepth >> 24) & 255); } } bw.Write(view.M11); bw.Write(view.M12); bw.Write(view.M13); bw.Write(view.M14); bw.Write(view.M21); bw.Write(view.M22); bw.Write(view.M23); bw.Write(view.M24); bw.Write(view.M31); bw.Write(view.M32); bw.Write(view.M33); bw.Write(view.M34); bw.Write(view.M41); bw.Write(view.M42); bw.Write(view.M43); bw.Write(view.M44); bw.Write(tmpBufferDepth); frameCount++; }
public void TextureToJpg(RenderTarget2D texture, Stream stream) { texture.GetData<byte>(textureData); byte blue; for (int i = 0; i < textureData.Length; i += 4) { blue = textureData[i]; textureData[i] = textureData[i+2]; textureData[i + 2] = blue; } bitmapData = bmp.LockBits( rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); safePtr = bitmapData.Scan0; System.Runtime.InteropServices.Marshal.Copy(textureData, 0, safePtr, textureData.Length); bmp.UnlockBits(bitmapData); bmp.Save(stream, imageFormat); }
// 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 LightningTexture(GraphicsDevice device, int width, int height) : base(device, width, height) { anim = new AnimatedLightning(Vector2.Zero, new Vector2(width, height), 45, MathHelper.ToRadians(45), 0.7f, 5, 1, 10); var sb = new SpriteBatch(device); var target = new RenderTarget2D(GraphicsDevice, 50, 100, false , GraphicsDevice.PresentationParameters.BackBufferFormat , GraphicsDevice.PresentationParameters.DepthStencilFormat); var oldTargets = GraphicsDevice.GetRenderTargets(); GraphicsDevice.SetRenderTarget(target); sb.Begin(); foreach (var segment in anim.Segments) { sb.DrawLine(segment.From, segment.To, segment.Color); } sb.End(); GraphicsDevice.SetRenderTargets(oldTargets); Color[] data = new Color[target.Width * target.Height]; target.GetData<Color>(data); this.SetData<Color>(data); }
public static void InvertGradient(RenderTarget2D textureInput, ref RenderTarget2D textureOutput, float state, Color c1, Color c2) { if (textureInput.Width != textureOutput.Width || textureInput.Height != textureOutput.Height) throw new Exception("Textures must be the same size!"); Color[] c = new Color[textureInput.Width * textureInput.Height]; textureInput.GetData<Color>(c); float cr = (float)(c1.R + c2.R) / 2 / 255; float cg = (float)(c1.G + c2.G) / 2 / 255; float cb = (float)(c1.B + c2.B) / 2 / 255; float dr = (float)(c1.R - c2.R) / 255; float dg = (float)(c1.G - c2.G) / 255; float db = (float)(c1.B - c2.B) / 255; float tr, tg, tb; for (int i = 0; i < c.Length && c[i].A != 0; i++) { tr = (float)c[i].R / 255; tg = (float)c[i].G / 255; tb = (float)c[i].B / 255; tr = tr - (tr - cr) * 2 * state; tg = tg - (tg - cg) * 2 * state; tb = tb - (tb - cb) * 2 * state; c[i].R = (byte)(tr * 255); c[i].G = (byte)(tg * 255); c[i].B = (byte)(tb * 255); } textureOutput.SetData<Color>(c); }
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 static void GrabScreenshot(RenderTarget2D rendertarget) { Color[] data = new Color[(rendertarget.Width * rendertarget.Height) * 3]; //OpenTK.Graphics.ES11.GL.ReadPixels(0, 0, rendertarget.Width, rendertarget.Height, OpenTK.Graphics.ES11.All.Rgb, OpenTK.Graphics.ES11.All.UnsignedByte, ref data); rendertarget.GetData<Color>(data); }
/// <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; }
/// <summary> /// Uses GPU to do premultiply calcs. Fast, however had problems. /// </summary> /// <param name="stream"></param> /// <param name="preMultiplyAlpha"></param> /// <returns></returns> public Texture2D FromStreamFast(Stream stream, bool preMultiplyAlpha = true) { Texture2D texture; if (_needsBmp) { // Load image using GDI because Texture2D.FromStream doesn't support BMP using (Image image = Image.FromStream(stream)) { // Now create a MemoryStream which will be passed to Texture2D after converting to PNG internally using (MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); texture = Texture2D.FromStream(_graphicsDevice, ms); } } } else { texture = Texture2D.FromStream(_graphicsDevice, stream); } if (preMultiplyAlpha) { // Setup a render target to hold our final texture which will have premulitplied alpha values using (RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, texture.Width, texture.Height)) { Viewport viewportBackup = _graphicsDevice.Viewport; _graphicsDevice.SetRenderTarget(renderTarget); _graphicsDevice.Clear(Color.Black); // Multiply each color by the source alpha, and write in just the color values into the final texture _spriteBatch.Begin(SpriteSortMode.Immediate, BlendColorBlendState); _spriteBatch.Draw(texture, texture.Bounds, Color.White); _spriteBatch.End(); // Now copy over the alpha values from the source texture to the final one, without multiplying them _spriteBatch.Begin(SpriteSortMode.Immediate, BlendAlphaBlendState); _spriteBatch.Draw(texture, texture.Bounds, Color.White); _spriteBatch.End(); // Release the GPU back to drawing to the screen _graphicsDevice.SetRenderTarget(null); _graphicsDevice.Viewport = viewportBackup; // Store data from render target because the RenderTarget2D is volatile Color[] data = new Color[texture.Width * texture.Height]; renderTarget.GetData(data); // Unset texture from graphic device and set modified data back to it _graphicsDevice.Textures[0] = null; texture.SetData(data); } } return texture; }
/// <summary> /// Save an RenderTarget2D as an PNG. MonoGame hasn't implemented this yet. /// I stole the code from https://github.com/mono/MonoGame/blob/29378026d803a8bbce61abd08b8dba2ebb6b2096/MonoGame.Framework/Graphics/Texture2D.OpenGL.cs#L559 /// </summary> /// <param name="stream">The stream to save the file to</param> /// <param name="width">The width of the image</param> /// <param name="height">The height of the image</param> /// <param name="target">The RenderTarget to save</param> public void SaveRenderTargetAsPng(Stream stream, int width, int height, RenderTarget2D target) { byte[] data = null; GCHandle? handle = null; System.Drawing.Bitmap bitmap = null; try { data = new byte[width * height * 4]; handle = GCHandle.Alloc(data, GCHandleType.Pinned); target.GetData(data); // internal structure is BGR while bitmap expects RGB for (int i = 0; i < data.Length; i += 4) { byte temp = data[i + 0]; data[i + 0] = data[i + 2]; data[i + 2] = temp; } bitmap = new System.Drawing.Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, handle.Value.AddrOfPinnedObject()); bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); } finally { if (bitmap != null) { bitmap.Dispose(); } if (handle.HasValue) { handle.Value.Free(); } if (data != null) { data = null; } } }
public Texture2D XuatAnhKyTu(string chuoi, int rongkhung, int daikhung, int dancachchu, int dancachdong, int canle, int candong, Rectangle bovien, Color maunen, Color mauchu) { //sao chep lai cac thong tin truoc khi xu ly scchuoi = chuoi; scrongkhung = rongkhung; scdaikhung = daikhung; scdancachchu = dancachchu; scdancachdong = dancachdong; sccanle = canle; sccandong = candong; scbovien = bovien; scmaunen = maunen; scmauchu = mauchu; baotran = false; //bat dau tien xu ly if (bonenvunganh != null) bonenvunganh.Dispose(); int kieutudongrong = 0, kieutudongdai = 0; if (rongkhung <= 0) { rongkhung = 640; kieutudongrong = 1; } if (daikhung <= 0) { daikhung = 480; kieutudongdai = 1; } //bat dau thuc hien ghep chuoi ky tu int vitrighepx = 0, vitrighepy = 0, demdong = 0; int sldong = (int)(daikhung / (dodaikytu + dancachdong)); if (sldong == 0) sldong = 1; int[] mangdorongdong = new int[sldong];//khai bao mang do rong cua cac dong int[] demkytu = new int[sldong];//dem so luong ky tu tren moi dong int[,] matranvanban = new int[cmax, dmax];//ma tran van ban co do lon co the chua cmax x dmax ky tu anh con for (int i = 0; i < chuoi.Length; i++) { for (int j = 0; j < giatrikytu.Length; j++) { if (chuoi.Substring(i, 1) == giatrikytu[j]) { if (chuoi.Substring(i, 1) == " ") { int vitricach = i; for (int l = i + 1; l < chuoi.Length; l++) { vitricach = l; if ((chuoi.Substring(l, 1) == " ") | (chuoi.Substring(l, 1) == "|")) break; } int tucuoi = vitricach; if ((chuoi.Substring(vitricach, 1) == " ") | (chuoi.Substring(vitricach, 1) == " ")) tucuoi = vitricach - 1; int dodaitumoi = 0; for (int l = i + 1; l <= tucuoi; l++) { for (int k = 0; k < giatrikytu.Length; k++) { if (chuoi.Substring(l, 1) == giatrikytu[k]) { dodaitumoi += dorongkytu[k] + dancachchu; break; } } } if (vitrighepx + dodaitumoi + 3 * dorongkytucham > rongkhung)//neu la tu cuoi { if (vitrighepy + 2 * dodaikytu + dancachdong > daikhung)//neu la dong cuoi { int dorongdongcuoi = 0; int dorongdongcuoimax = vitrighepx + dorongkytu[j] + 3 * dorongkytucham; if (dorongdongcuoimax < rongkhung) dorongdongcuoi = dorongdongcuoimax; else dorongdongcuoi = rongkhung; mangdorongdong[demdong] = dorongdongcuoi; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; demdong++; baotran = true; } else//neu khong phai dong cuoi { mangdorongdong[demdong] = vitrighepx; demdong = demdong + 1; vitrighepx = 0; vitrighepy += dodaikytu + dancachdong; matranvanban[demkytu[demdong], demdong] = j; demkytu[demdong]++; } } else//neu khong phai tu cuoi { vitrighepx += dorongkytu[j] + dancachchu; mangdorongdong[demdong] = vitrighepx; matranvanban[demkytu[demdong], demdong] = j; demkytu[demdong]++; } } else if (chuoi.Substring(i, 1) == "|")//ky tu xuong dong { if (vitrighepy + 2 * dodaikytu + dancachdong > daikhung)//neu la dong cuoi { int dorongdongcuoi = 0; int dorongdongcuoimax = vitrighepx + dorongkytu[j] + 3 * dorongkytucham; if (dorongdongcuoimax < rongkhung) dorongdongcuoi = dorongdongcuoimax; else dorongdongcuoi = rongkhung; mangdorongdong[demdong] = dorongdongcuoi; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; matranvanban[demkytu[demdong], demdong] = -1; demkytu[demdong]++; demdong++; baotran = true; } else//neu khong phai dong cuoi { mangdorongdong[demdong] = vitrighepx; demdong = demdong + 1; vitrighepx = 0; vitrighepy += dodaikytu + dancachdong; matranvanban[demkytu[demdong], demdong] = j; demkytu[demdong]++; } } else//neu la cac ky tu binh thuong { vitrighepx += dorongkytu[j] + dancachchu; mangdorongdong[demdong] = vitrighepx; matranvanban[demkytu[demdong], demdong] = j; demkytu[demdong]++; } break; } } if (baotran) break; } if (baotran == false) { demdong = demdong + 1; if (kieutudongdai == 1) daikhung = demdong * (dodaikytu + dancachdong) + Math.Abs(dancachdong); if (kieutudongrong == 1) { rongkhung = mangdorongdong[0]; for (int i = 0; i < mangdorongdong.Length; i++) { if (mangdorongdong[i] > rongkhung) rongkhung = mangdorongdong[i]; } } } //thuc hien can le va can dong bonenvunganh = new RenderTarget2D(thietbidohoa, rongkhung + bovien.X + bovien.Width, daikhung + bovien.Y + bovien.Height); thietbidohoa.SetRenderTarget(bonenvunganh); thietbidohoa.Clear(maunen); nenve.Begin(); int dodaitoanbochu = demdong * (dodaikytu + dancachdong) - dancachdong; int giasocandong = 0; if (candong == 3) giasocandong = daikhung - dodaitoanbochu; else if (candong == 2) giasocandong = (int)((daikhung - dodaitoanbochu) / 2); vitrighepx = bovien.X; vitrighepy = giasocandong + bovien.Y; if (canle == 3) { for (int i = 0; i < demdong; i++) { vitrighepx = rongkhung - mangdorongdong[i] + bovien.X; vitrighepy = i * (dodaikytu + dancachdong) + giasocandong + bovien.Y; for (int j = 0; j < demkytu[i]; j++) { if (matranvanban[j, i] == -1) { nenve.Draw(anhkytucham, new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytucham + dancachchu; } else { if ((j == 0) & ((giatrikytu[matranvanban[j, i]] == " ") | (giatrikytu[matranvanban[j, i]] == "|"))) continue; nenve.Draw(anhkytu[matranvanban[j, i]], new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytu[matranvanban[j, i]] + dancachchu; } } } } else if (canle == 2) { for (int i = 0; i < demdong; i++) { vitrighepx = (int)((rongkhung - mangdorongdong[i]) / 2) + bovien.X; vitrighepy = i * (dodaikytu + dancachdong) + giasocandong + bovien.Y; for (int j = 0; j < demkytu[i]; j++) { if (matranvanban[j, i] == -1) { nenve.Draw(anhkytucham, new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytucham + dancachchu; } else { if ((j == 0) & ((giatrikytu[matranvanban[j, i]] == " ") | (giatrikytu[matranvanban[j, i]] == "|"))) continue; nenve.Draw(anhkytu[matranvanban[j, i]], new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytu[matranvanban[j, i]] + dancachchu; } } } } else { for (int i = 0; i < demdong; i++) { vitrighepx = bovien.X; vitrighepy = i * (dodaikytu + dancachdong) + giasocandong + bovien.Y; for (int j = 0; j < demkytu[i]; j++) { if (matranvanban[j, i] == -1) { nenve.Draw(anhkytucham, new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytucham + dancachchu; } else { if ((j == 0) & ((giatrikytu[matranvanban[j, i]] == " ") | (giatrikytu[matranvanban[j, i]] == "|"))) continue; nenve.Draw(anhkytu[matranvanban[j, i]], new Vector2(vitrighepx, vitrighepy), Color.White); vitrighepx += dorongkytu[matranvanban[j, i]] + dancachchu; } } } } nenve.End(); thietbidohoa.SetRenderTarget(null); if (mauchu != Color.White) { Color[] dulieumau = new Color[bonenvunganh.Width * bonenvunganh.Height]; bonenvunganh.GetData(dulieumau); for (int x = 0; x < bonenvunganh.Width; x++) { for (int y = 0; y < bonenvunganh.Height; y++) { int vitri = x + y * bonenvunganh.Width; if (dulieumau[vitri].R > 126) { dulieumau[vitri] = mauchu; } } } bonenvunganh.SetData(dulieumau); } return bonenvunganh; }
public XnaColor GetPixel( int x, int y ) { var target = new RenderTarget2D( GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.None ); GraphicsDevice.SetRenderTarget( target ); HandleDeviceReset(); Draw(_spriteBatch); GraphicsDevice.SetRenderTarget( null ); var data = new XnaColor[ GraphicsDevice.Viewport.Width * GraphicsDevice.Viewport.Height ]; target.GetData( data ); return data[ GraphicsDevice.Viewport.Width * y + x ]; }
public virtual void HandleCollision(BaseCharacter entity) { //if (this.Bounds.Intersects(entity.Bounds)) //{ // entity.m_tintColor = Color.Red; //} //else //{ // entity.m_tintColor = Color.White; //} Player CroPlayer = null; if (this.Name == "Cro") { CroPlayer = EntityManager.m_croPlayer; } if (CroPlayer != null) { // Check to see if the bounding rectangles of both entities are intersecting with the bottom animation. if (this.Bounds.Intersects(entity.Bounds)) { // Creating a Spritebatch and RenderTarget2D to facilitate perpixel collision for the animation. SpriteBatch spriteBatch = EntityManager.m_spriteBatch; RenderTarget2D theRenderTargetBottom = null; RenderTarget2D theRenderTargetTop = null; theRenderTargetBottom = new RenderTarget2D(EntityManager.m_graphics, CroPlayer.BottomAnimation.Animation.FrameWidth, CroPlayer.BottomAnimation.Animation.FrameHeight); theRenderTargetTop = new RenderTarget2D(EntityManager.m_graphics, CroPlayer.TopAnimation.Animation.FrameWidth, CroPlayer.TopAnimation.Animation.FrameHeight); EntityManager.m_graphics.SetRenderTarget(theRenderTargetBottom); EntityManager.m_graphics.SetRenderTarget(theRenderTargetTop); EntityManager.m_graphics.Clear(Color.Transparent); spriteBatch.Begin(); Rectangle source = new Rectangle(CroPlayer.BottomAnimation.FrameIndex * CroPlayer.BottomAnimation.Animation.FrameWidth, 0, CroPlayer.BottomAnimation.Animation.FrameWidth, CroPlayer.BottomAnimation.Animation.Texture.Height); spriteBatch.Draw(CroPlayer.BottomAnimation.Animation.Texture, Vector2.Zero, source, Color.White, 0.0f, Vector2.Zero, 1.0f, CroPlayer.Flip, 0.0f); spriteBatch.Draw(CroPlayer.TopAnimation.Animation.Texture, Vector2.Zero, source, Color.White, 0.0f, Vector2.Zero, 1.0f, CroPlayer.Flip, 0.0f); spriteBatch.End(); EntityManager.m_graphics.SetRenderTarget(null); // Take the texture data for both entities and put them into colour arrays. Color[] entityData = new Color[theRenderTargetBottom.Width * theRenderTargetBottom.Height]; theRenderTargetBottom.GetData(entityData); Color[] entityData2 = new Color[entity.Texture.Width * entity.Texture.Height]; entity.Texture.GetData(entityData2); // Pass in the texture data and bounds of both entites in collision. if (IntersectPixels(this.Bounds, entityData, entity.Bounds, entityData2) == true) { // Change colour to red if there is a hit. entity.m_tintColor = Color.Red; } else { // Leave it as/change it back to white if there is no collision. entity.m_tintColor = Color.White; } } } }
// 不要在任何的Draw函数里面调用这个函数 public Texture2D RenderToTexture(System.Action drawCall ) { RenderTarget2D rt = new RenderTarget2D( Device, Device.Viewport.Width, Device.Viewport.Height);//, true, SurfaceFormat.Color, DepthFormat.Depth16); Device.SetRenderTarget(rt); bool oldDrawBegin = IsDrawBegin; if (!oldDrawBegin) DrawBegin(); drawCall(); if (!oldDrawBegin) DrawEnd(); Device.SetRenderTarget(null); Color[] c = new Color[1]; rt.GetData(0, new Rectangle(100, 100, 1, 1), c, 0, 1); Console.WriteLine(c[0].ToString()); return rt; }
public Texture2D FromStream(Stream stream, bool preMultiplyAlpha = true) { var texture = Texture2D.FromStream(graphicsDevice, stream); if (preMultiplyAlpha) { // Setup a render target to hold our final texture which will have premulitplied alpha values using (var renderTarget = new RenderTarget2D(graphicsDevice, texture.Width, texture.Height)) { var viewportBackup = graphicsDevice.Viewport; graphicsDevice.SetRenderTarget(renderTarget); graphicsDevice.Clear(Color.Black); // Multiply each color by the source alpha, and write in just the color values into the final texture spriteBatch.Begin(SpriteSortMode.Immediate, blendColorBlendState); spriteBatch.Draw(texture, texture.Bounds, Color.White); spriteBatch.End(); // Now copy over the alpha values from the source texture to the final one, without multiplying them spriteBatch.Begin(SpriteSortMode.Immediate, blendAlphaBlendState); spriteBatch.Draw(texture, texture.Bounds, Color.White); spriteBatch.End(); // Release the GPU back to drawing to the screen graphicsDevice.SetRenderTarget(null); graphicsDevice.Viewport = viewportBackup; // Store data from render target because the RenderTarget2D is volatile var data = new Color[texture.Width * texture.Height]; renderTarget.GetData(data); // Unset texture from graphic device and set modified data back to it graphicsDevice.Textures[0] = null; texture.SetData(data); } } return texture; }
// Render polygon public Texture2D renderPolygon(VertexPositionColorTexture[] _vertices, int primitiveCount) { Vector2 topLeft = new Vector2(_vertices[0].Position.X, _vertices[0].Position.Y); Vector2 bottomRight = topLeft; for (int i = 0; i < primitiveCount * 3; i++) { Vector2 vertex = new Vector2(_vertices[i].Position.X, _vertices[i].Position.Y); topLeft = Vector2.Min(topLeft, vertex); bottomRight = Vector2.Max(bottomRight, vertex); } int width = (int)Math.Ceiling((bottomRight.X - topLeft.X) * LevelController.ORIGINAL_SCALE); int height = (int)Math.Ceiling((bottomRight.Y - topLeft.Y) * LevelController.ORIGINAL_SCALE); RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, width, height); GraphicsDevice.SetRenderTarget(renderTarget); GraphicsDevice.Clear(Color.Transparent); Matrix viewMatrix = Matrix.CreateTranslation(new Vector3(-topLeft, 0)) * Matrix.CreateScale(new Vector3(LevelController.ORIGINAL_SCALE, -LevelController.ORIGINAL_SCALE, 1f)) * Matrix.CreateTranslation(new Vector3(-width, height, 0) / 2f); Matrix projectionMatrix = Matrix.CreateOrthographic(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1); _primitivesEffect.Parameters["world"].SetValue(Matrix.Identity); _primitivesEffect.Parameters["view"].SetValue(viewMatrix); _primitivesEffect.Parameters["projection"].SetValue(projectionMatrix); _primitivesEffect.CurrentTechnique.Passes["primitives"].Apply(); GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, _vertices, 0, primitiveCount, VertexPositionColorTexture.VertexDeclaration); GraphicsDevice.SetRenderTarget(null); Texture2D texture = new Texture2D(GraphicsDevice, width, height); Color[] data = new Color[width * height]; renderTarget.GetData<Color>(data); texture.SetData<Color>(data); return texture; }
//The CheckColisionMap public bool checkColisionMap(Vector2 nextPos) { //So first we create a new Render Target, this var is used to render the next game state without actually doing it in the player screen RenderTarget2D nextRender = new RenderTarget2D(SideScroller.graphics.GraphicsDevice, source.Width,source.Height); //We create this rectangle so we can check only an certain area of the texture Rectangle testArea = new Rectangle((int)nextPos.X, (int)nextPos.Y, source.Width, source.Height); //I just created this vars to simplify my life GraphicsDevice gDev = SideScroller.graphics.GraphicsDevice; SpriteBatch sBatch = SideScroller.spriteBatch; //This var defines the number of pixels that we are going to analyze int numberPixels = source.Width * source.Height; //Here we change the current render target of the game (probably it's null) gDev.SetRenderTarget(nextRender); //Now we clear the current render gDev.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0); //Here we just start the spritebatch so we can draw sBatch.Begin(); //Here we draw what would be the test area of the map texture sBatch.Draw(SideScroller.mapTexture, Vector2.Zero,testArea, Color.White); sBatch.End(); //Here we set the render target to the default render gDev.SetRenderTarget(null); //This var will store the colors from each pixel of the test area Color[] colorTexture = new Color[numberPixels]; //This method gets all the colors of the test area and put them in the colorTexture var nextRender.GetData<Color>(colorTexture); //Now we pass through each color extracted from the test area foreach (Color colorT in colorTexture) { //If the color is not white we define that there were a collision if (colorT != Color.White) { return true; } } //If there were no collision we return the false statement return false; }
/** Extensions to make it easy to create a CCTexture2D object from a string of text. Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). */ ///<summary> /// Initializes a texture from a string with dimensions, alignment, font name and font size /// </summary> public bool initWithString(string text, CCSize dimensions, CCTextAlignment alignment, string fontName, float fontSize) { if (dimensions.width < 0 || dimensions.height < 0) { return false; } if (string.IsNullOrEmpty(text)) { return false; } SpriteFont font = CCApplication.sharedApplication().content.Load<SpriteFont>(@"fonts/" + fontName); if (CCSize.CCSizeEqualToSize(dimensions, new CCSize())) { Vector2 temp = font.MeasureString(text); dimensions.width = temp.X; dimensions.height = temp.Y; } Vector2 origin; if (CCTextAlignment.CCTextAlignmentRight == alignment) { origin = new Vector2(-(dimensions.width - font.MeasureString(text).X), 0); } else if (CCTextAlignment.CCTextAlignmentCenter == alignment) { origin = new Vector2(-(dimensions.width - font.MeasureString(text).X) / 2.0f, 0); } else { origin = new Vector2(0, 0); } float scale = 1.0f;//need refer fontSize; CCApplication app = CCApplication.sharedApplication(); //* for render to texture RenderTarget2D renderTarget = new RenderTarget2D(app.graphics.GraphicsDevice, (int)dimensions.width, (int)dimensions.height); app.graphics.GraphicsDevice.SetRenderTarget(renderTarget); app.graphics.GraphicsDevice.Clear(new Color(0, 0, 0, 0)); app.spriteBatch.Begin(); app.spriteBatch.DrawString(font, text, new Vector2(0, 0), Color.YellowGreen, 0.0f, origin, scale, SpriteEffects.None, 0.0f); app.spriteBatch.End(); app.graphics.GraphicsDevice.SetRenderTarget(null); // to copy the rendered target data to a plain texture(to the memory) Color[] colors1D = new Color[renderTarget.Width * renderTarget.Height]; renderTarget.GetData(colors1D); texture2D = new Texture2D(app.GraphicsDevice, renderTarget.Width, renderTarget.Height); texture2D.SetData(colors1D); return initWithTexture(texture2D); }
protected override void Draw(GameTime gameTime) { Vector2 fms; switch(GameState) { case GameStates.MainMenu: GraphicsDevice.Clear(Color.Black); spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); spriteBatch.Draw( menu, Helpers.Scale(new Rectangle(0,0,(int)roomSize.X,(int)roomSize.Y), scale), Color.White); for(int i = 0;i<4;i++) { fms = font.MeasureString(menu_choices[i]); fms*=6; spriteBatch.DrawString( font, menu_choices[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+160)+new Vector2(1,1)*scale, Color.Black, 0, Vector2.Zero, scale, SpriteEffects.None, 0); spriteBatch.DrawString( font, menu_choices[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+160), i==menu_choice?Color.White:Color.Red, 0, Vector2.Zero, scale, SpriteEffects.None, 0); } spriteBatch.End(); break; case GameStates.HelpMenu: GraphicsDevice.Clear(Color.Black); spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); spriteBatch.Draw( menutex_help, Helpers.Scale(new Rectangle(0,0,(int)roomSize.X,(int)roomSize.Y), scale), Color.White); for(int i = 0;i<5;i++) { fms = font.MeasureString(menu_help[i]); fms*=6; spriteBatch.DrawString( font, menu_help[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+40)+new Vector2(1,1)*scale, Color.Black, 0, Vector2.Zero, scale, SpriteEffects.None, 0); spriteBatch.DrawString( font, menu_help[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+40), Color.White, 0, Vector2.Zero, scale, SpriteEffects.None, 0); } spriteBatch.End(); break; case GameStates.OptionsMenu: GraphicsDevice.Clear(Color.Black); spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); spriteBatch.Draw( menu_options, Helpers.Scale(new Rectangle(0,0,(int)roomSize.X,(int)roomSize.Y), scale), Color.White); for(int i = 0;i<4;i++) { fms = font.MeasureString(menu_difficulties[i]); fms*=scale; spriteBatch.DrawString( font, menu_difficulties[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+160)+new Vector2(1,1)*scale, Color.Black, 0, Vector2.Zero, scale, SpriteEffects.None, 0); spriteBatch.DrawString( font, menu_difficulties[i], new Vector2((roomSize.X*scale/2), roomSize.Y*scale/2)+new Vector2(-fms.X/2, -fms.Y*2+i*(fms.Y-46)+160), i==menu_choice?Color.White:Color.Red, 0, Vector2.Zero, scale, SpriteEffects.None, 0); } spriteBatch.Draw( dpad, Helpers.Scale(new Rectangle((int)roomSize.X/2-8, 16, 16, 16), scale), Color.White); string str = "Music: "+Math.Round(MusicVolume*100)+"%"; fms = font.MeasureString(str); spriteBatch.DrawString( font, str, new Vector2(roomSize.X/2-fms.X/2-12, 16+fms.Y/8)*scale, Color.White, 0, Vector2.Zero, scale/2, SpriteEffects.None, 0); str = "Sound: "+Math.Round(EffectVolume*100)+"%"; fms = font.MeasureString(str); spriteBatch.DrawString( font, str, new Vector2(roomSize.X/2+12, 16+fms.Y/8)*scale, Color.White, 0, Vector2.Zero, scale/2, SpriteEffects.None, 0); spriteBatch.End(); break; case GameStates.Game: RenderTarget2D rt = new RenderTarget2D(graphics.GraphicsDevice, (int)(roomSize.X*scale), (int)(roomSize.Y*scale)); graphics.GraphicsDevice.SetRenderTarget(rt); spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); spriteBatch.Draw( texture_background, Helpers.Scale(new Rectangle(-backgroundScroll,0,(int)roomSize.X,(int)roomSize.Y), scale), Color.White); //background spriteBatch.Draw( texture_background, Helpers.Scale(new Rectangle((int)roomSize.X-backgroundScroll,0,(int)roomSize.X,(int)roomSize.Y), scale), Color.White); //background (again, for scroll seam) foreach(Particle p in particles) { p.Draw(spriteBatch); } player.Draw(spriteBatch); foreach(Enemy e in enemies) { e.Draw(spriteBatch); } foreach(Bullet b in bullets) { b.Draw(spriteBatch); } foreach(Asteroid a in asteroids) { a.Draw(spriteBatch); } spriteBatch.End(); graphics.GraphicsDevice.SetRenderTarget(null); Color[] data = new Color[(int)((roomSize.X*scale)*(roomSize.Y*scale))]; for(int x = 0;x<roomSize.X*scale;x++) { data[x+(int)(roomSize.Y)] = new Color(1,0,0); } rt.GetData(data); Texture2D render = new Texture2D(graphics.GraphicsDevice, (int)(roomSize.X*scale), (int)(roomSize.Y*scale)); render.SetData(data); GraphicsDevice.Clear(Color.Black); spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); spriteBatch.Draw( render, Helpers.Scale(new Rectangle( (int)(-shake/2+(shake*random.NextDouble())), (int)(-shake/2+(shake*random.NextDouble())), (int)roomSize.X, (int)roomSize.Y), scale), new Rectangle(0,0,(int)((roomSize.X*scale)/1), (int)((roomSize.Y*scale)/1)), Color.White); string stars = ""; switch(Difficulty) { case Difficulties.Recruit: stars = "*";break; case Difficulties.Veteran: stars = "**";break; case Difficulties.General: stars = "***";break; case Difficulties.SpaceAce: stars = "****";break; } str = "Score - "+(score).ToString()+" (high - "+highscores[Difficulty]+")\nMultiplier - "+(multiplier/10f).ToString().Replace(',','.'); str+="\nDifficulty - "+stars; if(!player.shielded) { str += "\nShield restored in "+(killsToReg-killsSinceLeak).ToString()+" kills."; } spriteBatch.DrawString(ingame, str, new Vector2(6,4), Color.White, 0, Vector2.Zero, scale/3, SpriteEffects.None, 0); spriteBatch.End(); break; } spriteBatch.Begin(); spriteBatch.Draw(particle, Helpers.Scale( new Rectangle(0,0,(int)roomSize.X,(int)roomSize.Y),scale), new Color(0f,0f,0f,(float)blackFadeTimer/blackFadeTimerFreq)); spriteBatch.End(); base.Draw(gameTime); }
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); }
internal string Screenshot(int captureWidth = 0, int captureHeight = 0) { RenderTarget2D renderTarget = new RenderTarget2D( SceneManager.GraphicsDevice, (captureWidth == 0 ? SceneManager.GraphicsDevice.PresentationParameters.BackBufferWidth : captureWidth), (captureHeight == 0 ? SceneManager.GraphicsDevice.PresentationParameters.BackBufferHeight : captureHeight)); SceneManager.GraphicsDevice.SetRenderTarget(renderTarget); Draw(new GameTime()); SceneManager.GraphicsDevice.SetRenderTarget(null); if (!Directory.Exists("Screenshots")) Directory.CreateDirectory("Screenshots"); var path = AppDomain.CurrentDomain.BaseDirectory + "Screenshots\\screenshot " + DateTime.Now.ToString("yy-MM-dd H_mm_ss") + ".png"; using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { int width = renderTarget.Width; int height = renderTarget.Height; byte[] data = null; GCHandle? handle = null; System.Drawing.Bitmap bitmap = null; try { data = new byte[width * height * 4]; handle = GCHandle.Alloc(data, GCHandleType.Pinned); renderTarget.GetData(data); // internal structure is BGR while bitmap expects RGB for (int i = 0; i < data.Length; i += 4) { byte temp = data[i + 0]; data[i + 0] = data[i + 2]; data[i + 2] = temp; } bitmap = new System.Drawing.Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppRgb, handle.Value.AddrOfPinnedObject()); // System.Drawing.Imaging.PixelFormat.Format32bppArgb // does not save alpha properly bitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Png); } catch (Exception) { return string.Empty; } finally { if (bitmap != null) { bitmap.Dispose(); } if (handle.HasValue) { handle.Value.Free(); } if (data != null) { data = null; } } } return path; }
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"); } }
///<summary> /// Initializes a texture from a string with dimensions, alignment, font name and font size /// </summary> public bool initWithString(string text, CCSize dimensions, CCTextAlignment alignment, string fontName, float fontSize, Color fgColor, Color bgColor) { if (dimensions.width < 0 || dimensions.height < 0) { return false; } if (string.IsNullOrEmpty(text)) { return false; } SpriteFont font = null; try { font = CCApplication.sharedApplication().content.Load<SpriteFont>(@"fonts/" + fontName); } catch (Exception) { if (fontName.EndsWith(".spritefont", StringComparison.OrdinalIgnoreCase)) { fontName = fontName.Substring(0, fontName.Length - 11); font = CCApplication.sharedApplication().content.Load<SpriteFont>(@"fonts/" + fontName); } } if (CCSize.CCSizeEqualToSize(dimensions, new CCSize())) { Vector2 temp = font.MeasureString(text); dimensions.width = temp.X; dimensions.height = temp.Y; } Vector2 origin; if (CCTextAlignment.CCTextAlignmentRight == alignment) { origin = new Vector2(-(dimensions.width - font.MeasureString(text).X), 0); } else if (CCTextAlignment.CCTextAlignmentCenter == alignment) { origin = new Vector2(-(dimensions.width - font.MeasureString(text).X) / 2.0f, 0); } else { origin = new Vector2(0, 0); } float scale = 1.0f;//need refer fontSize; try { CCApplication app = CCApplication.sharedApplication(); //* for render to texture RenderTarget2D renderTarget = new RenderTarget2D(app.graphics.GraphicsDevice, (int)dimensions.width, (int)dimensions.height); app.graphics.GraphicsDevice.SetRenderTarget(renderTarget); app.graphics.GraphicsDevice.Clear(bgColor); app.spriteBatch.Begin(); app.spriteBatch.DrawString(font, text, new Vector2(0, 0), fgColor, 0.0f, origin, scale, SpriteEffects.None, 0.0f); app.spriteBatch.End(); app.graphics.GraphicsDevice.SetRenderTarget(null); // to copy the rendered target data to a plain texture(to the memory) Color[] colors1D = new Color[renderTarget.Width * renderTarget.Height]; renderTarget.GetData(colors1D); texture2D = new Texture2D(app.GraphicsDevice, renderTarget.Width, renderTarget.Height); texture2D.SetData(colors1D); return initWithTexture(texture2D); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } return (false); }
void initializeMinimap() { // set minimap fields and create rectangle object minimapPosX = minimapBorderSize; minimapPosY = uiViewport.Height - minimapSize - minimapBorderSize; minimapToMapRatioX = (float)minimapSize / (map.Width * map.TileSize); minimapToMapRatioY = (float)minimapSize / (map.Height * map.TileSize); minimapToScreenRatioX = (float)minimapSize / worldViewport.Width; minimapToScreenRatioY = (float)minimapSize / worldViewport.Height; minimap = new Rectangle(minimapPosX, minimapPosY, minimapSize, minimapSize); minimapScreenIndicatorBox = new BaseObject(new Rectangle(0, 0, (int)(worldViewport.Width * minimapToMapRatioX), (int)(worldViewport.Height * minimapToMapRatioY))); //minimapTexture = new Texture2D(GraphicsDevice, map.Width * Map.TILESIZE, map.Height * Map.TILESIZE); //minimapTexture = new RenderTarget2D(GraphicsDevice, map.Width * Map.TILESIZE, map.Height * Map.TILESIZE); // create minimap texture from map tiles RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, map.Width * map.TileSize, map.Height * map.TileSize); GraphicsDevice.SetRenderTarget(renderTarget); GraphicsDevice.Clear(Color.Gray); SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice); spriteBatch.Begin(); for (int x = 0; x < map.Width; x++) { for (int y = 0; y < map.Height; y++) { MapTile tile = map.Tiles[y, x]; if (tile.Type == 0) spriteBatch.Draw(ColorTexture.Gray, tile.Rectangle, Color.White); else if (tile.Type == 1) spriteBatch.Draw(boulder1Texture, tile.Rectangle, Color.White); else if (tile.Type == 2) spriteBatch.Draw(tree1Texture, tile.Rectangle, Color.White); } } spriteBatch.End(); GraphicsDevice.SetRenderTarget(null); //minimapTexture = (Texture2D)renderTarget; minimapTexture = new Texture2D(GraphicsDevice, map.Width * map.TileSize, map.Height * map.TileSize); Color[] textureData = new Color[(map.Width * map.TileSize) * (map.Height * map.TileSize)]; renderTarget.GetData<Color>(textureData); minimapTexture.SetData<Color>(textureData); renderTarget = null; GC.Collect(); }
private void CreateTexture() { Vector2 textSize = spriteFont.MeasureString(text); int textureWidth = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.X, 2))); int textureHeight = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.Y, 2))); fontTexture = new Texture2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight); RenderTarget2D target = new RenderTarget2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight); BasicEffect effect = new BasicEffect(spriteBatch.GraphicsDevice); effect.TextureEnabled = true; effect.VertexColorEnabled = true; effect.CurrentTechnique.Passes[0].Apply(); spriteBatch.GraphicsDevice.SetRenderTarget(target); spriteBatch.GraphicsDevice.Clear(Color.Transparent); spriteBatch.Begin(); spriteBatch.DrawString(spriteFont, text, Vector2.Zero, Color.Black); spriteBatch.End(); spriteBatch.GraphicsDevice.SetRenderTarget(null); target.SaveAsPng(new FileStream("testText.png", FileMode.Create), textureWidth, textureHeight); Color[] textureData = new Color[textureWidth * textureHeight]; target.GetData<Color>(textureData); fontTexture.SetData<Color>(textureData); effect.TextureEnabled = true; effect.Texture = fontTexture; //screenPoints[0].TextureCoordinate = new Vector2(0, 0); //screenPoints[1].TextureCoordinate = new Vector2(1, 0); //screenPoints[2].TextureCoordinate = new Vector2(1, 1); //screenPoints[3].TextureCoordinate = new Vector2(0, 1); screenPoints[0].TextureCoordinate = new Vector2(0, 0); screenPoints[1].TextureCoordinate = new Vector2(textSize.X / textureWidth, 0); screenPoints[2].TextureCoordinate = new Vector2(textSize.X / textureWidth, textSize.Y / textureHeight); screenPoints[3].TextureCoordinate = new Vector2(0, textSize.Y / textureHeight); }
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(); }
public XnaColor GetPixel(int x, int y) { RenderTarget2D target = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.None); GraphicsDevice.SetRenderTarget(target); HandleDeviceReset(); Draw(); GraphicsDevice.SetRenderTarget(null); #if false XnaColor[] data = new XnaColor[1]; target.GetData(0, new Rectangle(x, y, 1, 1), data, 0, data.Length); return data[0]; #else XnaColor[] data = new XnaColor[GraphicsDevice.Viewport.Width * GraphicsDevice.Viewport.Height]; target.GetData(data); return data[GraphicsDevice.Viewport.Width * y + x]; #endif }
/// <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(); }