Ejemplo n.º 1
0
        private void Render(Scene scene)
        {
            bool renderOverlay = DrawDirtyRects || DrawFps;
            bool composite     = false;

            if (_renderTarget == null)
            {
                _renderTarget = ((IRenderRoot)_root).CreateRenderTarget();
            }

            if (renderOverlay)
            {
                _dirtyRectsDisplay.Tick();
            }

            try
            {
                if (scene != null && scene.Size != Size.Empty)
                {
                    IDrawingContextImpl context = null;

                    if (scene.Generation != _lastSceneId)
                    {
                        context = _renderTarget.CreateDrawingContext(this);
                        _layers.Update(scene, context);

                        RenderToLayers(scene);

                        if (DebugFramesPath != null)
                        {
                            SaveDebugFrames(scene.Generation);
                        }

                        _lastSceneId = scene.Generation;

                        composite = true;
                    }

                    if (renderOverlay)
                    {
                        context = context ?? _renderTarget.CreateDrawingContext(this);
                        RenderOverlay(scene, context);
                        RenderComposite(scene, context);
                    }
                    else if (composite)
                    {
                        context = context ?? _renderTarget.CreateDrawingContext(this);
                        RenderComposite(scene, context);
                    }

                    context?.Dispose();
                }
            }
            catch (RenderTargetCorruptedException ex)
            {
                Logging.Logger.Information("Renderer", this, "Render target was corrupted. Exception: {0}", ex);
                _renderTarget?.Dispose();
                _renderTarget = null;
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Renders the specified visual.
 /// </summary>
 /// <param name="renderTarget">IRenderer instance</param>
 /// <param name="visual">The visual to render.</param>
 public static void Render(this IRenderTarget renderTarget, IVisual visual)
 {
     using (var ctx = renderTarget.CreateDrawingContext())
     {
         ctx.Render(visual);
         s_frameNum++;
         if (DrawFpsCounter)
         {
             s_currentFrames++;
             var now     = s_stopwatch.Elapsed;
             var elapsed = now - s_lastMeasure;
             if (elapsed.TotalSeconds > 0)
             {
                 s_fps           = (int)(s_currentFrames / elapsed.TotalSeconds);
                 s_currentFrames = 0;
                 s_lastMeasure   = now;
             }
             var pt = new Point(40, 40);
             using (
                 var txt = new FormattedText("Frame #" + s_frameNum + " FPS: " + s_fps, "Arial", 18,
                                             FontStyle.Normal,
                                             TextAlignment.Left,
                                             FontWeight.Normal,
                                             TextWrapping.NoWrap))
             {
                 ctx.FillRectangle(Brushes.White, new Rect(pt, txt.Measure()));
                 ctx.DrawText(Brushes.Black, pt, txt);
             }
         }
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Renders the specified visual.
 /// </summary>
 /// <param name="renderTarget">IRenderer instance</param>
 /// <param name="visual">The visual to render.</param>
 public static void Render(this IRenderTarget renderTarget, IVisual visual)
 {
     using (var ctx = renderTarget.CreateDrawingContext())
     {
         ctx.Render(visual);
         s_frameNum++;
         if (DrawFpsCounter)
         {
             s_currentFrames++;
             var now     = s_stopwatch.Elapsed;
             var elapsed = now - s_lastMeasure;
             if (elapsed.TotalSeconds > 1)
             {
                 s_fps           = (int)(s_currentFrames / elapsed.TotalSeconds);
                 s_currentFrames = 0;
                 s_lastMeasure   = now;
             }
             var pt  = new Point(40, 40);
             var txt = new FormattedText
             {
                 Text     = "Frame #" + s_frameNum + " FPS: " + s_fps,
                 Typeface = new Typeface("Arial", 18)
             };
             ctx.FillRectangle(Brushes.White, new Rect(pt, txt.Measure()));
             ctx.DrawText(Brushes.Black, pt, txt);
         }
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Renders a visual to a render target.
 /// </summary>
 /// <param name="visual">The visual.</param>
 /// <param name="target">The render target.</param>
 public static void Render(IVisual visual, IRenderTarget target)
 {
     using (var renderer = new ImmediateRenderer(visual))
         using (var context = new DrawingContext(target.CreateDrawingContext(renderer)))
         {
             renderer.Render(context, visual, visual.Bounds);
         }
 }
Ejemplo n.º 5
0
        private void RenderComposite(Scene scene)
        {
            try
            {
                if (_renderTarget == null)
                {
                    _renderTarget = ((IRenderRoot)_root).CreateRenderTarget();
                }

                using (var context = _renderTarget.CreateDrawingContext(this))
                {
                    var clientRect = new Rect(scene.Size);

                    foreach (var layer in scene.Layers)
                    {
                        var bitmap     = _layers[layer.LayerRoot].Bitmap;
                        var sourceRect = new Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight);

                        if (layer.GeometryClip != null)
                        {
                            context.PushGeometryClip(layer.GeometryClip);
                        }

                        if (layer.OpacityMask == null)
                        {
                            context.DrawImage(bitmap, layer.Opacity, sourceRect, clientRect);
                        }
                        else
                        {
                            context.DrawImage(bitmap, layer.OpacityMask, layer.OpacityMaskRect, sourceRect);
                        }

                        if (layer.GeometryClip != null)
                        {
                            context.PopGeometryClip();
                        }
                    }

                    if (_overlay != null)
                    {
                        var sourceRect = new Rect(0, 0, _overlay.PixelWidth, _overlay.PixelHeight);
                        context.DrawImage(_overlay, 0.5, sourceRect, clientRect);
                    }

                    if (DrawFps)
                    {
                        RenderFps(context, clientRect, true);
                    }
                }
            }
            catch (RenderTargetCorruptedException ex)
            {
                Logging.Logger.Information("Renderer", this, "Render target was corrupted. Exception: {0}", ex);
                _renderTarget?.Dispose();
                _renderTarget = null;
            }
        }
Ejemplo n.º 6
0
 protected override void Draw()
 {
     if (_renderTarget == null)
     {
         return;
     }
     using (var ctx = _renderTarget.CreateDrawingContext())
         OnRender(ctx);
 }
Ejemplo n.º 7
0
 protected override void OnPaint(PaintEventArgs pe)
 {
     using (var ctx = target.CreateDrawingContext())
     {
         ctx.BeginDraw();
         ctx.Clear(Seal.Colors.White);
         ctx.DrawPath(p.Path, this.brush);
     };
 }
Ejemplo n.º 8
0
        public static WriteableBitmap ToWriteableBitmap(Bitmap bmp)
        {
            var wb = new WriteableBitmap(bmp.PixelSize, bmp.Dpi, PixelFormat.Bgra8888);

            using (IRenderTarget rtb = Utils.RenderInterface.CreateRenderTarget(new[] { new WriteableBitmapSurface(wb) }))
                using (IDrawingContextImpl ctx = rtb.CreateDrawingContext(null))
                {
                    var rect = new Rect(bmp.Size);
                    ctx.DrawBitmap(bmp.PlatformImpl, 1, rect, rect);
                }
            bmp.Dispose();
            return(wb);
        }
Ejemplo n.º 9
0
            public DrawingContext CreateDrawingContext()
            {
                var cs     = _window.ClientSize;
                var ctx    = _target.CreateDrawingContext();
                var factor = _window.Scaling;

                if (factor != 1)
                {
                    ctx.PushPostTransform(Matrix.CreateScale(factor, factor));
                    ctx.PushTransformContainer();
                }
                return(ctx);
            }
Ejemplo n.º 10
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 15)
            {
                var now = Stopwatch.Elapsed;
                if ((now - _lastFps).Seconds >= 1)
                {
                    _fps     = _frames;
                    _frames  = 0;
                    _lastFps = now;
                    UpdateTitle();
                }
                _frames++;

                _renderTarget.Resize(ClientSize.Width, ClientSize.Height);
                using (var ctx = _renderTarget.CreateDrawingContext())
                {
                    ctx.FillRectangle(Brushes.White, new Rect(0, 0, Width, Height));
                    ctx.FillRectangle(Brushes.Green, new Rect(_textPos, _text.Measure()));
                    ctx.FillRectangle(Brushes.Blue, _textRect);
                    ctx.DrawText(Brushes.Red, _textPos, _text);


                    /*for(var x=0; x<Width; x+=40)
                     *  for (var y = 0; y < Height; y += 20)
                     *      ctx.FillRectangle(Brushes.Gray, new Rect(x + (y/20)%2*20, y, 20, 20));
                     */
                    /*
                     * _geometry.Transform = new MatrixTransform(GetTransform());
                     * var rad = CreateRadialGradient();
                     * rad.Opacity = 0.5;
                     * ctx.DrawGeometry(rad, new Pen(CreateLinearGradient(), 4),
                     *  _geometry);*/
                    /*
                     * using (ctx.PushPostTransform(GetTransform()))
                     * {
                     *  ctx.DrawImage(_rbitmap, 1, new Rect(0, 0, 50, 50), new Rect(0, 0, 50, 50));
                     *  using(ctx.PushPostTransform(Matrix.CreateTranslation(200, 0)))
                     *  ctx.DrawImage(_bitmap, 1, new Rect(0, 0, _bitmap.PixelWidth, _bitmap.PixelHeight),
                     *      new Rect(0, 0, 100, 100));
                     * }*/
                }
                m.Result = new IntPtr(1);
                return;
            }
            base.WndProc(ref m);
        }
Ejemplo n.º 11
0
        /// <inheritdoc/>
        public void Paint(Rect rect)
        {
            if (_renderTarget == null)
            {
                _renderTarget = ((IRenderRoot)_root).CreateRenderTarget();
            }

            try
            {
                using (var context = new DrawingContext(_renderTarget.CreateDrawingContext(this)))
                {
                    context.PlatformImpl.Clear(Colors.Transparent);

                    using (context.PushTransformContainer())
                    {
                        Render(context, _root, _root.Bounds);
                    }

                    if (DrawDirtyRects)
                    {
                        var color = (uint)new Random().Next(0xffffff) | 0x44000000;
                        context.FillRectangle(
                            new SolidColorBrush(color),
                            rect);
                    }

                    if (DrawFps)
                    {
                        RenderFps(context.PlatformImpl, _root.Bounds, null);
                    }
                }
            }
            catch (RenderTargetCorruptedException ex)
            {
                Logger.TryGet(LogEventLevel.Information, LogArea.Animations)?.Log(this, "Render target was corrupted. Exception: {0}", ex);
                _renderTarget.Dispose();
                _renderTarget = null;
            }

            SceneInvalidated?.Invoke(this, new SceneInvalidatedEventArgs((IRenderRoot)_root, rect));
        }
Ejemplo n.º 12
0
        protected override void Draw()
        {
            _radians += 0.02;
            var scale = UIScreen.MainScreen.Scale;
            int width = (int)(Bounds.Width * scale), height = (int)(Bounds.Height * scale);

            using (var ctx = _target.CreateDrawingContext())
            {
                ctx.FillRectangle(Brushes.Green, new Rect(0, 0, width, height));
                ctx.DrawText(Brushes.Red, new Point(50, 50), _text);
                var rc = new Rect(0, 0, width / 3, height / 3);
                using (ctx.PushPostTransform(
                           Avalonia.Matrix.CreateTranslation(-width / 6, -width / 6) *
                           Avalonia.Matrix.CreateRotation(_radians) *
                           Avalonia.Matrix.CreateTranslation(width / 2, height / 2)))
                {
                    ctx.FillRectangle(new LinearGradientBrush()
                    {
                        GradientStops =
                        {
                            new GradientStop()
                            {
                                Color = Colors.Blue
                            },
                            new GradientStop(Colors.Red, 1)
                        }
                    }, rc, 5);
                }
            }
            _frames++;
            var now     = St.Elapsed.TotalSeconds;
            var elapsed = now - _lastFps;

            if (elapsed > 1)
            {
                UpdateText((int)(_frames / elapsed));
                _frames  = 0;
                _lastFps = now;
            }
            DrawOnNextFrame();
        }
Ejemplo n.º 13
0
        /// <inheritdoc/>
        public void Paint(Rect rect)
        {
            if (_renderTarget == null)
            {
                _renderTarget = ((IRenderRoot)_root).CreateRenderTarget();
            }

            try
            {
                using (var context = new DrawingContext(_renderTarget.CreateDrawingContext(this)))
                {
                    using (context.PushTransformContainer())
                    {
                        Render(context, _root, _root.Bounds);
                    }

                    if (DrawDirtyRects)
                    {
                        var color = (uint)new Random().Next(0xffffff) | 0x44000000;
                        context.FillRectangle(
                            new SolidColorBrush(color),
                            rect);
                    }

                    if (DrawFps)
                    {
                        RenderFps(context.PlatformImpl, _root.Bounds, null);
                    }
                }
            }
            catch (RenderTargetCorruptedException ex)
            {
                Logging.Logger.Information("Renderer", this, "Render target was corrupted. Exception: {0}", ex);
                _renderTarget.Dispose();
                _renderTarget = null;
            }
        }
Ejemplo n.º 14
0
        public static Bitmap RenderString(string str, StringRenderStyle style)
        {
            // Return null for bad strings
            if (string.IsNullOrWhiteSpace(str))
            {
                return(null);
            }

            string path; int charHeight, spaceWidth;

            switch (style)
            {
            case StringRenderStyle.BattleName: path = "BattleName"; charHeight = 11; spaceWidth = 2; break;

            case StringRenderStyle.BattleLevel: path = "BattleLevel"; charHeight = 10; spaceWidth = 7; break;

            case StringRenderStyle.BattleHP: path = "BattleHP"; charHeight = 8; spaceWidth = 0; break;

            default: path = "Default"; charHeight = 15; spaceWidth = 4; break;
            }

            int index;

            string GetCharKey()
            {
                string key = $"FONT_{path}_";

                if (index + 6 <= str.Length && str.Substring(index, 6) == "[PKMN]")
                {
                    key   += "PKMN";
                    index += 6;
                }
                else if (index + 4 <= str.Length && str.Substring(index, 4) == "[LV]")
                {
                    key   += "LV";
                    index += 4;
                }
                else
                {
                    key += ((int)str[index]).ToString("X");
                    index++;
                }
                const string questionMark = "FONT_Default_3F";

                return(DoesResourceExist($"Kermalis.PokemonBattleEngineClient.FONT.{path}.{key}.png") ? key : questionMark);
            }

            // Measure how large the string will end up
            int stringWidth = 0, stringHeight = charHeight, curLineWidth = 0;

            index = 0;
            while (index < str.Length)
            {
                if (str[index] == ' ')
                {
                    index++;
                    curLineWidth += spaceWidth;
                }
                else if (str[index] == '\r')
                {
                    index++;
                    continue;
                }
                else if (str[index] == '\n')
                {
                    index++;
                    stringHeight += charHeight + 1;
                    if (curLineWidth > stringWidth)
                    {
                        stringWidth = curLineWidth;
                    }
                    curLineWidth = 0;
                }
                else
                {
                    string key = GetCharKey();
                    if (!loadedBitmaps.ContainsKey(key))
                    {
                        loadedBitmaps.TryAdd(key, UriToBitmap(new Uri($"resm:Kermalis.PokemonBattleEngineClient.FONT.{path}.{key}.png?assembly=PokemonBattleEngineClient")));
                    }
                    curLineWidth += loadedBitmaps[key].PixelSize.Width;
                }
            }
            if (curLineWidth > stringWidth)
            {
                stringWidth = curLineWidth;
            }

            // Draw the string
            var wb = new WriteableBitmap(new PixelSize(stringWidth, stringHeight), new Vector(96, 96), PixelFormat.Bgra8888);

            using (IRenderTarget rtb = AvaloniaLocator.Current.GetService <IPlatformRenderInterface>().CreateRenderTarget(new[] { new WriteableBitmapSurface(wb) }))
                using (IDrawingContextImpl ctx = rtb.CreateDrawingContext(null))
                {
                    double x = 0, y = 0;
                    index = 0;
                    while (index < str.Length)
                    {
                        if (str[index] == ' ')
                        {
                            index++;
                            x += spaceWidth;
                        }
                        else if (str[index] == '\r')
                        {
                            index++;
                            continue;
                        }
                        else if (str[index] == '\n')
                        {
                            index++;
                            y += charHeight + 1;
                            x  = 0;
                        }
                        else
                        {
                            Bitmap bmp = loadedBitmaps[GetCharKey()];
                            ctx.DrawImage(bmp.PlatformImpl, 1.0, new Rect(0, 0, bmp.PixelSize.Width, charHeight), new Rect(x, y, bmp.PixelSize.Width, charHeight));
                            x += bmp.PixelSize.Width;
                        }
                    }
                }
            // Edit colors
            using (ILockedFramebuffer l = wb.Lock())
            {
                uint primary = 0xFFFFFFFF, secondary = 0xFF000000, tertiary = 0xFF808080;
                switch (style)
                {
                case StringRenderStyle.MenuBlack: primary = 0xFF5A5252; secondary = 0xFFA5A5AD; break;

                case StringRenderStyle.BattleWhite:     //secondary = 0xF0FFFFFF; break; // Looks horrible because of Avalonia's current issues
                case StringRenderStyle.MenuWhite: secondary = 0xFF848484; break;

                case StringRenderStyle.BattleName:
                case StringRenderStyle.BattleLevel: primary = 0xFFF7F7F7; secondary = 0xFF181818; break;

                case StringRenderStyle.BattleHP: primary = 0xFFF7F7F7; secondary = 0xFF101010; tertiary = 0xFF9C9CA5; break;
                }
                for (int x = 0; x < stringWidth; x++)
                {
                    for (int y = 0; y < stringHeight; y++)
                    {
                        var  address = new IntPtr(l.Address.ToInt64() + (x * sizeof(uint)) + (y * l.RowBytes));
                        uint pixel   = (uint)Marshal.ReadInt32(address);
                        if (pixel == 0xFFFFFFFF)
                        {
                            Marshal.WriteInt32(address, (int)primary);
                        }
                        else if (pixel == 0xFF000000)
                        {
                            Marshal.WriteInt32(address, (int)secondary);
                        }
                        else if (pixel == 0xFF808080)
                        {
                            Marshal.WriteInt32(address, (int)tertiary);
                        }
                    }
                }
            }
            return(wb);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Renders the specified visual.
 /// </summary>
 /// <param name="renderTarget">IRenderer instance</param>
 /// <param name="visual">The visual to render.</param>
 public static void Render(this IRenderTarget renderTarget, IVisual visual)
 {
     using (var ctx = renderTarget.CreateDrawingContext())
         ctx.Render(visual);
 }