/// <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 (var image = System.Drawing.Image.FromStream(stream))
                {
                    // Now create a MemoryStream which will be passed to Texture2D after converting to PNG internally
                    using (var 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 (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);
        }
Example #2
0
        /// <summary>Premultiply a texture's alpha values to avoid transparency issues in the game. This is only possible if the game isn't currently drawing.</summary>
        /// <param name="texture">The texture to premultiply.</param>
        /// <returns>Returns a premultiplied texture.</returns>
        /// <remarks>Based on <a href="https://gist.github.com/Layoric/6255384">code by Layoric</a>.</remarks>
        private Texture2D PremultiplyTransparency(Texture2D texture)
        {
            // validate
            if (Context.IsInDrawLoop)
            {
                throw new NotSupportedException("Can't load a PNG file while the game is drawing to the screen. Make sure you load content outside the draw loop.");
            }

            // process texture
            SpriteBatch    spriteBatch = Game1.spriteBatch;
            GraphicsDevice gpu         = Game1.graphics.GraphicsDevice;

            using (RenderTarget2D renderTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height))
            {
                // create blank render target to premultiply
                gpu.SetRenderTarget(renderTarget);
                gpu.Clear(Color.Black);

                // multiply each color by the source alpha, and write just the color values into the final texture
                spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
                {
                    ColorDestinationBlend = Blend.Zero,
                    ColorWriteChannels    = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
                    AlphaDestinationBlend = Blend.Zero,
                    AlphaSourceBlend      = Blend.SourceAlpha,
                    ColorSourceBlend      = Blend.SourceAlpha
                });
                spriteBatch.Draw(texture, texture.Bounds, Color.White);
                spriteBatch.End();

                // copy the alpha values from the source texture into the final one without multiplying them
                spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
                {
                    ColorWriteChannels    = ColorWriteChannels.Alpha,
                    AlphaDestinationBlend = Blend.Zero,
                    ColorDestinationBlend = Blend.Zero,
                    AlphaSourceBlend      = Blend.One,
                    ColorSourceBlend      = Blend.One
                });
                spriteBatch.Draw(texture, texture.Bounds, Color.White);
                spriteBatch.End();

                // release GPU
                gpu.SetRenderTarget(null);

                // extract premultiplied data
                Color[] data = new Color[texture.Width * texture.Height];
                renderTarget.GetData(data);

                // unset texture from GPU to regain control
                gpu.Textures[0] = null;

                // update texture with premultiplied data
                texture.SetData(data);
            }

            return(texture);
        }
Example #3
0
        // 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);
        }
Example #4
0
        public static RenderTarget2D CopyRenderTarget(RenderTarget2D origin)
        {
            RenderTarget2D result = new RenderTarget2D(origin.GraphicsDevice, origin.Width, origin.Height);

            Color[] data = new Color[origin.Width * origin.Height];
            origin.GetData(data);
            result.SetData(data);
            return(result);
        }
Example #5
0
        public static Texture2D GetFromRT(RenderTarget2D In)
        {
            Texture2D Out = new Texture2D(Shell.PubGD, In.Width, In.Height);

            Color[] texdata = new Color[Out.Width * Out.Height];
            In.GetData(texdata);
            Out.SetData(texdata);
            return(Out);
        }
Example #6
0
        //-----------------------------------------------------------------
        public void Process(RenderTarget2D texture)
        {
            Copy(texture);
            input.GetData(data);

//            Draw();
            // DrawStreamline();
//            Debug();
        }
Example #7
0
        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
        }
Example #8
0
 public void End(GraphicsDevice device)
 {
     device.SetRenderTarget(null);
     if (colorBuffer == null)
     {
         colorBuffer = new Color[(device.Viewport.Width / Scale) * (device.Viewport.Height / Scale)];
     }
     Buffer.GetData(colorBuffer);
 }
Example #9
0
        /// <summary>
        /// Tries to get the contents of the back buffer.
        /// </summary>
        /// <typeparam name="T">The type of the elements in the array.</typeparam>
        /// <param name="data">The array of data.</param>
        /// <remarks>
        /// <see langword="true"/> if the content was copied successfully; otherwise,
        /// <see langword="false"/> if the back buffer was not available or empty.
        /// </remarks>
        public bool TryGetData <T>(T[] data) where T : struct
        {
            if (_renderTarget == null)
            {
                return(false);
            }

            _renderTarget.GetData(data);
            return(true);
        }
Example #10
0
        public static Texture2D CloneRenderTarget(this RenderTarget2D target, GraphicsDevice device)
        {
            var clone     = new Texture2D(device, target.Width, target.Height);
            var tempArray = new Color[target.Width * target.Height];

            target.GetData(tempArray);
            clone.SetData(tempArray);

            return(clone);
        }
Example #11
0
        /// <inheritdoc/>
        public override void SaveAsJpeg(RenderTarget2D renderTarget, Stream stream)
        {
            Contract.Require(renderTarget, "renderTarget");
            Contract.Require(stream, "stream");

            var data = new Color[renderTarget.Width * renderTarget.Height];

            renderTarget.GetData(data);

            Save(data, renderTarget.Width, renderTarget.Height, stream, asPng: false);
        }
Example #12
0
        private Texture2D GetStableTextureFromRenderTarget(RenderTarget2D renderTarget)
        {
            int width         = renderTarget.Width;
            int height        = renderTarget.Height;
            var scaledTexture = new Texture2D(device, width, height, mipmap: false, SurfaceFormat.Color);

            Color[] data = GetColorDataArray(width * height);
            renderTarget.GetData <Color>(data);
            scaledTexture.SetData(data);
            return(scaledTexture);
        }
Example #13
0
        public Texture2D RenderTextToTexture(string input, SpriteFont font, Color textColor, int outlineOffset)
        {
            StringBuilder temp = new StringBuilder();

            temp.Append(" ");
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == '\n')
                {
                    temp.Append(" \n ");
                }
                else
                {
                    temp.Append(input[i]);
                }
            }

            string  textToRender    = temp.ToString();
            Vector2 stringDimension = font.MeasureString(temp.ToString());
            Vector2 targetBounds    = new Vector2(stringDimension.X + outlineOffset * 4, stringDimension.Y + outlineOffset * 4);

            Texture2D texture = new Texture2D(graphics.GraphicsDevice, (int)targetBounds.X, (int)targetBounds.Y);

            RenderTarget2D target = new RenderTarget2D(
                graphics.GraphicsDevice,
                (int)targetBounds.X,
                (int)targetBounds.Y,
                false,
                graphics.GraphicsDevice.PresentationParameters.BackBufferFormat,
                DepthFormat.Depth24);

            Color[] data = new Color[(int)targetBounds.X * (int)targetBounds.Y];

            spriteBatch.GraphicsDevice.SetRenderTarget(target);
            spriteBatch.GraphicsDevice.DepthStencilState = new DepthStencilState()
            {
                DepthBufferEnable = true
            };

            spriteBatch.GraphicsDevice.Clear(Color.Transparent);
            spriteBatch.Begin(SpriteSortMode.BackToFront,
                              BlendState.AlphaBlend,
                              SamplerState.PointClamp,
                              null, null, null, null);

            spriteBatch.DrawString(font, textToRender, targetBounds / 2, textColor, 0f, stringDimension / 2, 1f, SpriteEffects.None, 0f);

            spriteBatch.End();
            target.GetData(data);
            texture.SetData(data);
            data = null;
            target.Dispose();
            return(texture);
        }
Example #14
0
 public static Texture2D Retrieve()
 {
     freedraw.GraphicsDevice.SetRenderTarget(null);
     Color[] col = new Color[Scren.Width * Scren.Height - 1];
     Scren.GetData(col);
     permGFX = new Texture2D(Universal.Graphics.GraphicsDevice, Scren.Width, Scren.Height);
     permGFX.SetData(col);
     Scren.Dispose();
     livedraw.Dispose();
     return(permGFX);
 }
        /// <inheritdoc/>
        public override void SaveAsJpeg(RenderTarget2D renderTarget, Stream stream)
        {
            Contract.Require(renderTarget, nameof(renderTarget));
            Contract.Require(stream, nameof(stream));

            var data = new Color[renderTarget.Width * renderTarget.Height];

            renderTarget.GetData(data);

            Save(data, renderTarget.Width, renderTarget.Height, stream, img => img.AsJPEG());
        }
        /// <summary>
        /// Повертає полотно з намальованими текстурами
        /// </summary>
        /// <returns>Повертає текстуру</returns>
        public Texture2D GetCanvas()
        {
            _spriteBatch.End();
            GraphicInstance.Device.SetRenderTarget(null);
            Texture2D texture = new Texture2D(GraphicInstance.Device, _map.Bounds.Width, _map.Bounds.Height);

            Color[] color = new Color[_map.Bounds.Width * _map.Bounds.Height];
            _map.GetData <Color>(color);
            texture.SetData <Color>(color);
            return(texture);
        }
Example #17
0
        public void DrawTick()
        {
            Monitor.Enter(_captureLock);
            if (_activeSettings == null)
            {
                return;
            }
            bool notRetro = Lighting.NotRetro;

            if (_renderQueue.Count > 0)
            {
                CaptureChunk captureChunk = _renderQueue.Dequeue();
                _graphics.SetRenderTarget(null);
                _graphics.Clear(Microsoft.Xna.Framework.Color.Transparent);
                Main.instance.TilesRenderer.PrepareForAreaDrawing(captureChunk.Area.Left, captureChunk.Area.Right, captureChunk.Area.Top, captureChunk.Area.Bottom, prepareLazily: false);
                Main.instance.TilePaintSystem.PrepareAllRequests();
                _graphics.SetRenderTarget(_frameBuffer);
                _graphics.Clear(Microsoft.Xna.Framework.Color.Transparent);
                if (notRetro)
                {
                    Microsoft.Xna.Framework.Color clearColor = _activeSettings.CaptureBackground ? Microsoft.Xna.Framework.Color.Black : Microsoft.Xna.Framework.Color.Transparent;
                    Filters.Scene.BeginCapture(_filterFrameBuffer1, clearColor);
                    Main.instance.DrawCapture(captureChunk.Area, _activeSettings);
                    Filters.Scene.EndCapture(_frameBuffer, _filterFrameBuffer1, _filterFrameBuffer2, clearColor);
                }
                else
                {
                    Main.instance.DrawCapture(captureChunk.Area, _activeSettings);
                }
                if (_activeSettings.UseScaling)
                {
                    _graphics.SetRenderTarget(_scaledFrameBuffer);
                    _graphics.Clear(Microsoft.Xna.Framework.Color.Transparent);
                    _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, _downscaleSampleState, DepthStencilState.Default, RasterizerState.CullNone);
                    _spriteBatch.Draw(_frameBuffer, new Microsoft.Xna.Framework.Rectangle(0, 0, _scaledFrameBuffer.Width, _scaledFrameBuffer.Height), Microsoft.Xna.Framework.Color.White);
                    _spriteBatch.End();
                    _graphics.SetRenderTarget(null);
                    _scaledFrameBuffer.GetData(_scaledFrameData, 0, _scaledFrameBuffer.Width * _scaledFrameBuffer.Height * 4);
                    DrawBytesToBuffer(_scaledFrameData, _outputData, _scaledFrameBuffer.Width, _outputImageSize.Width, captureChunk.ScaledArea);
                }
                else
                {
                    _graphics.SetRenderTarget(null);
                    SaveImage(_frameBuffer, captureChunk.ScaledArea.Width, captureChunk.ScaledArea.Height, ImageFormat.Png, _activeSettings.OutputName, captureChunk.Area.X + "-" + captureChunk.Area.Y + ".png");
                }
                _tilesProcessed += captureChunk.Area.Width * captureChunk.Area.Height;
            }
            if (_renderQueue.Count == 0)
            {
                FinishCapture();
            }
            Monitor.Exit(_captureLock);
        }
Example #18
0
 /// <summary>
 /// Returns the color of a certain pixel. Uses internal position of pixel.
 /// </summary>
 /// <returns>The color of the specified pixel.</returns>
 public Color this[int x, int y]
 {
     get
     {
         if (colorData == null)
         {
             colorData = new Color[renderTarget.Height * renderTarget.Width];
             renderTarget.GetData <Color>(colorData);
         }
         return(colorData[x + y * renderTarget.Width]);
     }
 }
Example #19
0
        }   // end of Hide()

        public void Update()
        {
            if (texture == null)
            {
                GraphicsDevice device = BokuGame.bokuGame.GraphicsDevice;
                RenderTarget2D rt     = UI2D.Shared.RenderTarget128_128;
                InGame.SetRenderTarget(rt);

                InGame.Clear(Color.Transparent);

                // Background.
                ScreenSpaceQuad quad       = ScreenSpaceQuad.GetInstance();
                Texture2D       background = BokuGame.Load <Texture2D>(BokuGame.Settings.MediaPath + @"Textures\GridElements\BlackSquare");
                quad.Render(background, Vector2.Zero, new Vector2(rt.Width, rt.Height), "TexturedRegularAlpha");

                // Y button
                Vector2 size = new Vector2(64, 64);
                quad.Render(ButtonTextures.BButton, new Vector2(44, 24), size, "TexturedRegularAlpha");

                // Text.
                Color               color    = Color.Yellow;
                SpriteBatch         batch    = UI2D.Shared.SpriteBatch;
                UI2D.Shared.GetFont Font     = UI2D.Shared.GetGameFont24Bold;
                Vector2             position = new Vector2(0, 120 - Font().LineSpacing);
                position.X = 64 - 0.5f * Font().MeasureString(Strings.Localize("editObjectParams.back")).X;
                batch.Begin();
                TextHelper.DrawString(Font, Strings.Localize("editObjectParams.back"), position, color);
                batch.End();

                InGame.RestoreRenderTarget();

                texture = new Texture2D(device, 128, 128, false, SurfaceFormat.Color);

                // Copy rendertarget result into texture.
                int[] data = new int[128 * 128];
                rt.GetData <int>(data);
                texture.SetData <int>(data);
            }

            double now = Time.WallClockTotalSeconds;

            if (now - showTime < delayTime || hide)
            {
                // Still in delay.
                alpha = 0.0f;
            }
            else
            {
                // Either in fade or in full view.
                float t = (float)(now - showTime - delayTime) / fadeTime;
                alpha = Math.Min(t, 1.0f);
            }
        }   // end of Update()
Example #20
0
        public override void Draw(GameTime gameTime)
        {
            if (!Enabled)
            {
                return;
            }

            GenerateFireMap(fireMap.Width, fireMap.Height);

            effect.Parameters["fireMap"].SetValue(fireMap);

            effect.Parameters["oxygen"].SetValue(oxygen);
            effect.Parameters["paletteMap"].SetValue(paletteTexture);
            effect.Parameters["width"].SetValue((float)Resolution.X);
            effect.Parameters["height"].SetValue((float)Resolution.Y);

            // Capture fireMap data.
            GraphicsDevice.SetRenderTarget(rt);
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

            effect.CurrentTechnique = effect.Techniques["UpdateFire"];
            effect.CurrentTechnique.Passes[0].Apply();

            spriteBatch.Draw(fireMap, new Rectangle(0, 0, Resolution.X, Resolution.Y), Color.White);
            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);

            // Get the data from the rt and pack it back into the map.
            rt.GetData <Color>(rtc);
            //GraphicsDevice.Textures[1] = null;
            fireMap.SetData <Color>(rtc);

            // Re draw with color passing in the firemap data
            GraphicsDevice.Clear(Color.Black);
            //spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.Default, RasterizerState.CullCounterClockwise);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);

            effect.CurrentTechnique = effect.Techniques["ColorFire"];
            effect.CurrentTechnique.Passes[0].Apply();

            spriteBatch.Draw(fireMap, new Rectangle(0, 0, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight), Color.White);

            spriteBatch.End();

            // Debug
            if (ShowDebug)
            {
                RenderDebugTextures(paletteTexture, fireMap);
            }
        }
Example #21
0
        public unsafe void Commit()
        {
            _renderTarget.GetData(_stagingTexture, _buffer);
            _writeableBitmap.Lock();

            fixed(byte *buffer = _buffer)
            {
                SharpDX.Utilities.CopyMemory(_writeableBitmap.BackBuffer, new IntPtr(buffer), _buffer.Length);
            }

            _writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, _renderTarget.Width, _renderTarget.Height));
            _writeableBitmap.Unlock();
        }
        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
        }
Example #23
0
        void initializeMapTexture()
        {
            // set minimap fields and create rectangle object
            minimapPosX = minimapBorderSize;
            minimapPosY = uiViewport.Height - minimapSize - minimapBorderSize;
            //minimapPosX = 0;
            //minimapPosY = 0;
            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);
            //minimap = new Rectangle(0, 0, minimapSize, minimapSize);
            minimapScreenIndicatorBox = new BaseObject(new Rectangle(0, 0, (int)(worldViewport.Width * minimapToMapRatioX), (int)(worldViewport.Height * minimapToMapRatioY)));
            //fullMapTexture = new Texture2D(GraphicsDevice, map.Width * Map.TILESIZE, map.Height * Map.TILESIZE);
            //fullMapTexture = new RenderTarget2D(GraphicsDevice, map.Width * Map.TILESIZE, map.Height * Map.TILESIZE);

            // create full map 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.Draw(tile.Texture, tile.Rectangle, Color.White);
                }
            }
            spriteBatch.End();
            GraphicsDevice.SetRenderTarget(null);
            //fullMapTexture = (Texture2D)renderTarget;
            fullMapTexture = 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);
            fullMapTexture.SetData <Color>(textureData);

            //renderTarget = null;
            //GC.Collect();
        }
        /// <summary>
        /// End of the drawing on the render target.
        /// </summary>
        public static void End()
        {
            Graphics.GraphicsDevice.SetRenderTarget(null);

            Color[] data = new Color[RenderTarget.Width * RenderTarget.Height];

            RenderTarget.GetData <Color>(data);

            Texture = new Texture2D(Graphics.GraphicsDevice, RenderTarget.Width, RenderTarget.Height);

            Texture.SetData <Color>(data);

            RenderTarget.Dispose();
        }
Example #25
0
        public override void Render(RenderTarget2D source, RenderTarget2D destination)
        {
            base.Render(source, destination);
            if (this.Action == null)
            {
                return;
            }

            var tex  = new Texture2D(Core.Instance.GraphicsDevice, source.Width, source.Height);
            var data = new int[tex.Bounds.Width * tex.Bounds.Height];

            source.GetData(data);
            tex.SetData(data);
            this.Action(tex);
        }
        }   // end of ThoughtBalloon Activate()

        public void RefreshTexture()
        {
            RenderTarget2D rt = UI2D.Shared.RenderTarget256_256;

            //
            // Render the frame and text to the rendertarget.
            //
            InGame.SetRenderTarget(rt);

            ScreenSpaceQuad ssquad = ScreenSpaceQuad.GetInstance();

            InGame.Clear(Color.Transparent);

            // Frame
            ssquad.Render(ThoughtBalloonManager.FrameTexture, Vector2.Zero, new Vector2(rt.Width, rt.Height), "TexturedRegularAlpha");

            int      width = 238;
            TextBlob blob  = new TextBlob(UI2D.Shared.GetGameFont30Bold, text, width);

            blob.Justification = Boku.UI2D.UIGridElement.Justification.Center;

            if (blob.NumLines > 3)
            {
                blob.Font = UI2D.Shared.GetGameFont24Bold;
                if (blob.NumLines > 3)
                {
                    blob.Font = UI2D.Shared.GetGameFont24Bold;
                }
            }

            duration = defaultDuration * blob.NumLines;

            int     margin      = 8;
            int     middle      = 76; // Vertical midpoint of space for text.
            int     lineSpacing = blob.Font().LineSpacing;
            int     numLines    = Math.Min(4, blob.NumLines);
            Vector2 pos         = new Vector2(margin, middle - (numLines * 0.5f) * lineSpacing);

            blob.RenderWithButtons(pos, Color.Black, maxLines: numLines);

            InGame.RestoreRenderTarget();

            //
            // Copy result to local texture.
            //
            rt.GetData <int>(_scratchData);
            contentTexture.SetData <int>(_scratchData);
        }   // end of ThoughtBalloon RefreshTexture()
Example #27
0
        public static Texture2D GetNovelTextureOfColour(Shell MyShell, Color Colour, Point Dims)
        {
            RenderTarget2D Output = new RenderTarget2D(MyShell.GraphicsDevice, Dims.X, Dims.Y, false,
                                                       MyShell.GraphicsDevice.PresentationParameters.BackBufferFormat,
                                                       DepthFormat.Depth24);

            MyShell.GraphicsDevice.SetRenderTarget(Output);
            MyShell.GraphicsDevice.Clear(Colour);
            MyShell.GraphicsDevice.SetRenderTarget(null);
            Color[] texdata = new Color[Output.Width * Output.Height];
            Output.GetData(texdata);
            Texture2D NOut = new Texture2D(MyShell.GraphicsDevice, Output.Width, Output.Height);

            NOut.SetData(texdata);
            return(NOut);
        }
Example #28
0
        static public 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);
        }
Example #29
0
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(tempRenderTarget);
            GraphicsDevice.Clear(new Color(95, 105, 122));

            spriteBatch.Begin();
            pon3.Draw(spriteBatch);
            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.WhiteSmoke);

            int     width  = tempRenderTarget.Width;
            int     height = tempRenderTarget.Height;
            Vector2 center = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);

            Color[] colors = new Color[width * height];
            tempRenderTarget.GetData <Color>(colors);
            double maxDistSQR = Math.Sqrt(Math.Pow(center.X, 2) + Math.Pow(center.Y, 2));

            for (int v = 0; v < height; v++)
            {
                for (int u = 0; u < width; u++)
                {
                    double distSQR    = Math.Sqrt(Math.Pow(u - center.X, 2) + Math.Pow(v - center.Y, 2));
                    int    blurAmount = (int)Math.Floor(20 * distSQR / maxDistSQR);

                    int currElement = u + (width * v);
                    int prevElement = currElement - blurAmount;
                    int nextElement = currElement + blurAmount;

                    if (((currElement - blurAmount) > 0) && ((currElement + blurAmount) < width * height))
                    {
                        colors[currElement].R = (byte)((colors[currElement].R + colors[prevElement].R + colors[nextElement].R) / 3.0f);
                        colors[currElement].G = (byte)((colors[currElement].G + colors[prevElement].G + colors[nextElement].G) / 3.0f);
                        colors[currElement].B = (byte)((colors[currElement].B + colors[prevElement].B + colors[nextElement].B) / 3.0f);
                    }
                }
            }
            tempText.SetData <Color>(colors);

            spriteBatch.Begin();
            spriteBatch.Draw(tempText, Vector2.Zero, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
Example #30
0
        private void DrawMasterTargetToBatch()
        {
            Texture2D drawTexture = masterRenderingTarget;

            if (NTSC)
            {
                masterRenderingTarget.GetData(pixels);

                snes_ntsc_blit(ntsc, pixels, 256, 0, 256, 224, filtered, 1204);

                ntscTexture.SetData(filtered);

                drawTexture = ntscTexture;
            }

            masterSpriteBatch.Draw(drawTexture, new Rectangle(0, 0, Width, Height), Color.White);
        }