Exemplo n.º 1
0
        /// <summary>
        /// Gets a Direct2D bitmap to use on the specified render target.
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <returns>The Direct2D bitmap.</returns>
        public override SharpDX.Direct2D1.Bitmap GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget)
        {
            FormatConverter converter = new FormatConverter(_factory);

            converter.Initialize(WicImpl, SharpDX.WIC.PixelFormat.Format32bppPBGRA);
            return(SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTarget, converter));
        }
Exemplo n.º 2
0
        /// <summary>
        ///		指定したレンダーターゲットに対して描画処理を実行する。
        /// </summary>
        /// <remarks>
        ///		描画処理は、レンダーターゲットの BeginDraw() と EndDraw() の間で行われることが保証される。
        ///		描画処理中に例外が発生しても EndDraw() の呼び出しが確実に保証される。
        /// </remarks>
        /// <param name="rt">レンダリングターゲット。</param>
        /// <param name="描画処理">BeginDraw() と EndDraw() の間で行う処理。</param>
        public void D2DBatchDraw(SharpDX.Direct2D1.RenderTarget rt, Action 描画処理)
        {
            // リストになかったらこの rt を使うのは初回なので、BeginDraw/EndDraw() の呼び出しを行う。
            // もしリストに登録されていたら、この rt は他の誰かが BeginDraw して EndDraw してない状態
            // (D2DBatcDraw() の最中に D2DBatchDraw() が呼び出されている状態)なので、これらを呼び出してはならない。
            bool BeginとEndを行う = !(this._Draw中のレンダーターゲットリスト.Contains(rt));

            try
            {
                if (BeginとEndを行う)
                {
                    this._Draw中のレンダーターゲットリスト.Add(rt);       // Begin したらリストに追加。
                    rt.BeginDraw();
                }

                var trans = rt.Transform;
                try
                {
                    描画処理();
                }
                finally
                {
                    // 描画が終わるたびに元に戻す。
                    rt.Transform = trans;
                }
            }
            finally
            {
                if (BeginとEndを行う)
                {
                    rt.EndDraw();
                    this._Draw中のレンダーターゲットリスト.Remove(rt);    // End したらリストから削除。
                }
            }
        }
        /// <summary>
        /// Creates device-based resources to store a constant buffer, cube
        /// geometry, and vertex and pixel shaders. In some cases this will also
        /// store a geometry shader.
        /// </summary>
        public void CreateDeviceDependentResources()
        {
            ReleaseDeviceDependentResources();

            // Create a default sampler state, which will use point sampling.
            pointSampler = ToDispose(new SamplerState(deviceResources.D3DDevice, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter             = Filter.MinMagMipLinear,
                MaximumAnisotropy  = 16,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0.0f
            }));

            // Create the texture that will be used as the offscreen render target.
            var textureDesc = new Texture2DDescription
            {
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Width             = textureWidth,
                Height            = textureHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                OptionFlags       = ResourceOptionFlags.None,
                Usage             = ResourceUsage.Default,
                CpuAccessFlags    = CpuAccessFlags.None
            };

            texture2D = new Texture2D(deviceResources.D3DDevice, textureDesc);

            // Create read and write views for the offscreen render target.
            shaderResourceView = new ShaderResourceView(deviceResources.D3DDevice, texture2D);
            renderTargetView   = new RenderTargetView(deviceResources.D3DDevice, texture2D);

            // In this example, we are using D2D and DirectWrite; so, we need to create a D2D render target as well.
            SharpDX.Direct2D1.RenderTargetProperties props = new SharpDX.Direct2D1.RenderTargetProperties(
                SharpDX.Direct2D1.RenderTargetType.Default,
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                96, 96,
                SharpDX.Direct2D1.RenderTargetUsage.None,
                SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

            // The DXGI surface is used to create the render target.
            SharpDX.DXGI.Surface dxgiSurface = texture2D.QueryInterface <SharpDX.DXGI.Surface>();
            d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(deviceResources.D2DFactory, dxgiSurface, props);

            // Create a solid color brush that will be used to render the text.
            whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, new RawColor4(1f, 1f, 1f, 1f));

            // This is where we format the text that will be written on the render target.
            textFormat = new SharpDX.DirectWrite.TextFormat(deviceResources.DWriteFactory, "Consolas", SharpDX.DirectWrite.FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 64f);
            textFormat.TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center;
            textFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center;
        }
Exemplo n.º 4
0
        internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line)
        {
            var rect = line.GetBoundingRect(rootElement).ToSharpDX();
            //var fill = line.Fill.ToSharpDX(renderTarget, rect);
            var stroke = await line.Stroke.ToSharpDX(renderTarget, rect);

            if (stroke == null ||
                line.StrokeThickness <= 0)
            {
                return;
            }

            //var layer = new Layer(renderTarget);
            //var layerParameters = new LayerParameters();
            //layerParameters.ContentBounds = rect;
            //renderTarget.PushLayer(ref layerParameters, layer);

            renderTarget.DrawLine(
                new DrawingPointF(
                    rect.Left + (float)line.X1,
                    rect.Top + (float)line.Y1),
                new DrawingPointF(
                    rect.Left + (float)line.X2,
                    rect.Top + (float)line.Y2),
                stroke,
                (float)line.StrokeThickness,
                line.GetStrokeStyle(compositionEngine.D2DFactory));

            //renderTarget.PopLayer();
        }
Exemplo n.º 5
0
        private void CloseDx()
        {
            logger.Debug("GDICapture::CloseDx()");

            if (renderTarget != null)
            {
                renderTarget.Dispose();
                renderTarget = null;
            }

            if (renderTexture != null)
            {
                renderTexture.Dispose();
                renderTexture = null;
            }

            if (SharedTexture != null)
            {
                SharedTexture.Dispose();
                SharedTexture = null;
            }

            if (gdiTexture != null)
            {
                gdiTexture.Dispose();
                gdiTexture = null;
            }

            if (device != null)
            {
                device.Dispose();
                device = null;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets a Direct2D bitmap to use on the specified render target.
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <returns>The Direct2D bitmap.</returns>
        public override OptionalDispose <D2DBitmap> GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget)
        {
            FormatConverter converter = new FormatConverter(Direct2D1Platform.ImagingFactory);

            converter.Initialize(WicImpl, SharpDX.WIC.PixelFormat.Format32bppPBGRA);
            return(new OptionalDispose <D2DBitmap>(D2DBitmap.FromWicBitmap(renderTarget, converter), true));
        }
        /// <summary>
        ///		指定したレンダーターゲットに対して描画処理をバッチ実行する。
        /// </summary>
        /// <remarks>
        ///		描画処理は、レンダーターゲットの BeginDraw() と EndDraw() の間で行われることが保証される。
        ///		描画処理中に例外が発生しても EndDraw() の呼び出しが確実に保証される。
        /// </remarks>
        /// <param name="rt">レンダリングターゲット。</param>
        /// <param name="描画処理">BeginDraw() と EndDraw() の間で行う処理。</param>
        public void D2DBatchDraw(SharpDX.Direct2D1.RenderTarget rt, Action 描画処理)
        {
            // リストになかったらこの rt を使うのは初回なので、BeginDraw/EndDraw() の呼び出しを行う。
            // もしリストに登録されていたら、この rt は他の誰かが BeginDraw して EndDraw してない状態
            // (D2DBatcDraw() の最中に D2DBatchDraw() が呼び出されている状態)なので、これらを呼び出してはならない。
            bool BeginとEndを行う = !(this._BatchDraw中のレンダーターゲットリスト.Contains(rt));

            var pretrans = rt.Transform;
            var preblend = (rt is SharpDX.Direct2D1.DeviceContext dc) ? dc.PrimitiveBlend : SharpDX.Direct2D1.PrimitiveBlend.SourceOver;

            try
            {
                if (BeginとEndを行う)
                {
                    this._BatchDraw中のレンダーターゲットリスト.Add(rt);       // Begin したらリストに追加。
                    rt.BeginDraw();
                }

                描画処理();
            }
            finally
            {
                rt.Transform = pretrans;
                if (rt is SharpDX.Direct2D1.DeviceContext dc2)
                {
                    dc2.PrimitiveBlend = preblend;
                }

                if (BeginとEndを行う)
                {
                    rt.EndDraw();
                    this._BatchDraw中のレンダーターゲットリスト.Remove(rt);    // End したらリストから削除。
                }
            }
        }
Exemplo n.º 8
0
        public RadialGradientBrushImpl(
            Perspex.Media.RadialGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size destinationSize)
        {
            var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop {
                Color = s.Color.ToDirect2D(), Position = (float)s.Offset
            }).ToArray();

            Point centerPoint          = brush.Center.ToPixels(destinationSize);
            Point GradientOriginOffset = brush.GradientOrigin.ToPixels(destinationSize);
            // Note: Direct2D supports RadiusX and RadiusY but Cairo backend supports only Radius property
            double radiusX = brush.Radius;
            double radiusY = brush.Radius;

            PlatformBrush = new SharpDX.Direct2D1.RadialGradientBrush(
                target,
                new SharpDX.Direct2D1.RadialGradientBrushProperties {
                Center = centerPoint.ToSharpDX(), GradientOriginOffset = GradientOriginOffset.ToSharpDX(), RadiusX = (float)radiusX, RadiusY = (float)radiusY
            },
                new SharpDX.Direct2D1.BrushProperties {
                Opacity = (float)brush.Opacity, Transform = target.Transform
            },
                new SharpDX.Direct2D1.GradientStopCollection(target, gradientStops, brush.SpreadMethod.ToDirect2D())
                );
        }
Exemplo n.º 9
0
        internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line)
        {
            var rect   = line.GetBoundingRect(rootElement).ToSharpDX();
            var stroke = await line.Stroke.ToSharpDX(renderTarget, rect);

            if (stroke == null ||
                line.StrokeThickness <= 0)
            {
                return;
            }

            var layer = line.CreateAndPushLayerIfNecessary(renderTarget, rootElement);

            renderTarget.DrawLine(
                new Vector2(
                    rect.Left + (float)line.X1,
                    rect.Top + (float)line.Y1),
                new Vector2(
                    rect.Left + (float)line.X2,
                    rect.Top + (float)line.Y2),
                stroke,
                (float)line.StrokeThickness,
                line.GetStrokeStyle(compositionEngine.D2DFactory));

            if (layer != null)
            {
                renderTarget.PopLayer();
                layer.Dispose();
            }
        }
Exemplo n.º 10
0
        public void LoadGraphics(SharpDX.Direct2D1.RenderTarget target)
        {
            up    = new List <SharpDX.Direct2D1.Bitmap>();
            down  = new List <SharpDX.Direct2D1.Bitmap>();
            left  = new List <SharpDX.Direct2D1.Bitmap>();
            right = new List <SharpDX.Direct2D1.Bitmap>();
            death = new List <SharpDX.Direct2D1.Bitmap>();

            Bitmap    original = Properties.Resources.blue;
            Bitmap    sprite;
            Rectangle srcRect;

            // Init down
            int i = 0;

            for (; i < 3; ++i)
            {
                srcRect = new Rectangle(i * 48, 0, 48, 48);
                sprite  = original.Clone(srcRect, original.PixelFormat);
                down.Add(sprite.CreateDirectX2D1Bitmap(target));
                sprite.Dispose();
            }

            // Init right
            for (; i < 6; ++i)
            {
                srcRect = new Rectangle(i * 48, 0, 48, 48);
                sprite  = original.Clone(srcRect, original.PixelFormat);
                right.Add(sprite.CreateDirectX2D1Bitmap(target));
                sprite.Dispose();
            }

            // Init left
            for (; i < 9; ++i)
            {
                srcRect = new Rectangle(i * 48, 0, 48, 48);
                sprite  = original.Clone(srcRect, original.PixelFormat);
                left.Add(sprite.CreateDirectX2D1Bitmap(target));
                sprite.Dispose();
            }

            // Init up
            for (; i < 12; ++i)
            {
                srcRect = new Rectangle(i * 48, 0, 48, 48);
                sprite  = original.Clone(srcRect, original.PixelFormat);
                up.Add(sprite.CreateDirectX2D1Bitmap(target));
                sprite.Dispose();
            }

            // Init death
            for (; i < 20; ++i)
            {
                srcRect = new Rectangle(i * 48, 0, 48, 48);
                sprite  = original.Clone(srcRect, original.PixelFormat);
                death.Add(sprite.CreateDirectX2D1Bitmap(target));
                sprite.Dispose();
            }
        }
Exemplo n.º 11
0
 public void Draw(SharpDX.Direct2D1.RenderTarget target)
 {
     target.PushAxisAlignedClip(new SharpDX.Mathematics.Interop.RawRectangleF(this.bounds.Left, this.bounds.Top, this.bounds.Right, this.bounds.Bottom), SharpDX.Direct2D1.AntialiasMode.PerPrimitive);
     Ground.Draw(target, this.bounds);
     //this.containedObject?.Draw(target);
     target.PopAxisAlignedClip();
     IsChanged = false;
 }
Exemplo n.º 12
0
        public override void Draw(SharpDX.Direct2D1.RenderTarget target)
        {
            if (this.spriteAnimation.CurrentFrame == null)
            {
                return;
            }
            var b = Tile.Bounds;

            target.DrawBitmap(this.spriteAnimation.CurrentFrame, new SharpDX.Mathematics.Interop.RawRectangleF(b.Left, b.Top, b.Right, b.Bottom), 1, SharpDX.Direct2D1.BitmapInterpolationMode.Linear);
        }
Exemplo n.º 13
0
        public D2DGraphics(D2DView.RenderTargetEventArgs e)
        {
            _renderTarget = e.RenderTarget;
            _graphics = e.Graphics;

            _renderTarget.Transform = SharpDX.Matrix3x2.Identity;

            if (!_renderTargetCache.ContainsKey(_renderTarget))
                _renderTargetCache[_renderTarget] = new RenderTargetCache();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets a Direct2D bitmap to use on the specified render target.
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <returns>The Direct2D bitmap.</returns>
        public SharpDX.Direct2D1.Bitmap GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget)
        {
            if (_direct2D == null)
            {
                FormatConverter converter = new FormatConverter(_factory);
                converter.Initialize(WicImpl, PixelFormat.Format32bppPBGRA);
                _direct2D = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTarget, converter);
            }

            return(_direct2D);
        }
 public SolidColorBrushImpl(ISolidColorBrush brush, SharpDX.Direct2D1.RenderTarget target)
 {
     PlatformBrush = new SharpDX.Direct2D1.SolidColorBrush(
         target,
         brush?.Color.ToDirect2D() ?? new SharpDX.Mathematics.Interop.RawColor4(),
         new SharpDX.Direct2D1.BrushProperties
     {
         Opacity   = brush != null ? (float)brush.Opacity : 1.0f,
         Transform = target.Transform
     }
         );
 }
Exemplo n.º 16
0
        private void DrawTexture(SharpDX.Direct2D1.RenderTarget renderTarget, Texture2D texture)
        {
            using (var surf = texture.QueryInterface <SharpDX.DXGI.Surface1>())
            {
                var prop = new SharpDX.Direct2D1.BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
                SharpDX.Direct2D1.Bitmap screenBits = new SharpDX.Direct2D1.Bitmap(renderTarget, surf, prop);
                try
                {
                    var   srcDecr   = surf.Description;
                    float srcWidth  = srcDecr.Width;
                    float srcHeight = srcDecr.Height;

                    float destX      = 0;
                    float destY      = 0;
                    float destWidth  = DestSize.Width;
                    float destHeight = DestSize.Height;

                    float scaleX = destWidth / srcWidth;
                    float scaleY = destHeight / srcHeight;

                    if (AspectRatio)
                    {
                        if (scaleY < scaleX)
                        {
                            scaleX = scaleY;
                            destX  = ((destWidth - srcWidth * scaleX) / 2);
                        }
                        else
                        {
                            scaleY = scaleX;
                            destY  = ((destHeight - srcHeight * scaleY) / 2);
                        }
                    }

                    destWidth  = srcWidth * scaleX;
                    destHeight = srcHeight * scaleY;

                    var destRect = new SharpDX.Mathematics.Interop.RawRectangleF
                    {
                        Left   = destX,
                        Right  = destX + destWidth,
                        Top    = destY,
                        Bottom = destY + destHeight,
                    };

                    renderTarget.DrawBitmap(screenBits, destRect, 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.Linear);
                }
                finally
                {
                    screenBits?.Dispose();
                }
            }
        }
Exemplo n.º 17
0
 public void LoadGraphics(SharpDX.Direct2D1.RenderTarget target)
 {
     sprites = new Dictionary <FireType, IReadOnlyList <SharpDX.Direct2D1.Bitmap> > {
         { FireType.Left, BuildSpriteSequence(Properties.Resources.ExplosionLeft, target) },
         { FireType.Right, BuildSpriteSequence(Properties.Resources.ExplosionRight, target) },
         { FireType.Up, BuildSpriteSequence(Properties.Resources.ExplosionUp, target) },
         { FireType.Down, BuildSpriteSequence(Properties.Resources.ExplosionDown, target) },
         { FireType.Horizontal, BuildSpriteSequence(Properties.Resources.ExplosionHorizontal, target) },
         { FireType.Vertical, BuildSpriteSequence(Properties.Resources.ExplosionVertical, target) },
         { FireType.Center, BuildSpriteSequence(Properties.Resources.ExplosionCentre, target) },
     };
 }
Exemplo n.º 18
0
 private void CreateFromBitmap(SharpDX.Direct2D1.RenderTarget InRenderTarget, Bitmap InBitmap)
 {
     MemStream = new System.IO.MemoryStream();
     InBitmap.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
     BitDecorder = new SharpDX.WIC.BitmapDecoder(Direct2DDrawingSystem.instance.ImagingFactory,
                                                 MemStream,
                                                 SharpDX.WIC.DecodeOptions.CacheOnDemand);
     BFDecorde  = BitDecorder.GetFrame(0);
     fConverter = new SharpDX.WIC.FormatConverter(Direct2DDrawingSystem.instance.ImagingFactory);
     fConverter.Initialize(BFDecorde, SharpDX.WIC.PixelFormat.Format32bppPBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0, SharpDX.WIC.BitmapPaletteType.Custom);
     Texture2D = SharpDX.Direct2D1.Bitmap.FromWicBitmap(InRenderTarget, fConverter);
 }
Exemplo n.º 19
0
        public static Brush2D ToSharpDX(this Brush brush, RenderTarget2D target)
        {
            SolidColorBrush solidColorBrush = brush as SolidColorBrush;

            if (solidColorBrush != null)
            {
                return(solidColorBrush.ToSharpDX(target));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Exemplo n.º 20
0
        private void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new SharpDX.DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                                  new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);

            var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                IsWindowed        = false
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport,
                                                          new[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, swapChainDesc,
                                                          out _d3DDevice, out var swapChain);
            _d3DDeviceContext = _d3DDevice.ImmediateContext;

            _swapChain = new SharpDX.DXGI.SwapChain1(swapChain.NativePointer);

            _d2DFactory = new SharpDX.Direct2D1.Factory();

            using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3DDevice, backBuffer);
                _renderTarget     = new SharpDX.Direct2D1.RenderTarget(_d2DFactory, backBuffer.QueryInterface <SharpDX.DXGI.Surface>(),
                                                                       new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype
                };
            }

            _solidColorBrush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, Color.White);

            _dwFactory  = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            _textFormat = new SharpDX.DirectWrite.TextFormat(_dwFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold,
                                                             SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale)
            {
                TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center
            };
            //                var rectangleGeometry = new D2D1.RoundedRectangleGeometry(_d2DFactory,
            //                    new D2D1.RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, Width - 128 * 2, Height - 128 * 2) });
        }
Exemplo n.º 21
0
        public RadialGradientBrushImpl(
            IRadialGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Rect destinationRect)
        {
            if (brush.GradientStops.Count == 0)
            {
                return;
            }

            var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop
            {
                Color    = s.Color.ToDirect2D(),
                Position = (float)s.Offset
            }).ToArray();

            var position       = destinationRect.Position;
            var centerPoint    = position + brush.Center.ToPixels(destinationRect.Size);
            var gradientOrigin = position + brush.GradientOrigin.ToPixels(destinationRect.Size) - centerPoint;

            // Note: Direct2D supports RadiusX and RadiusY but Cairo backend supports only Radius property
            var radiusX = brush.Radius * destinationRect.Width;
            var radiusY = brush.Radius * destinationRect.Height;

            using (var stops = new SharpDX.Direct2D1.GradientStopCollection(
                       target,
                       gradientStops,
                       brush.SpreadMethod.ToDirect2D()))
            {
                PlatformBrush = new SharpDX.Direct2D1.RadialGradientBrush(
                    target,
                    new SharpDX.Direct2D1.RadialGradientBrushProperties
                {
                    Center = centerPoint.ToSharpDX(),
                    GradientOriginOffset = gradientOrigin.ToSharpDX(),
                    RadiusX = (float)radiusX,
                    RadiusY = (float)radiusY
                },
                    new SharpDX.Direct2D1.BrushProperties
                {
                    Opacity   = (float)brush.Opacity,
                    Transform = PrimitiveExtensions.Matrix3x2Identity,
                },
                    stops);
            }
        }
Exemplo n.º 22
0
 public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer visualBrushRenderer)
 {
     _target = _target ?? _externalRenderTargetProvider.CreateRenderTarget();
     _externalRenderTargetProvider.BeforeDrawing();
     return(new DrawingContextImpl(visualBrushRenderer, _target, _dwFactory, null, () =>
     {
         try
         {
             _externalRenderTargetProvider.AfterDrawing();
         }
         catch (SharpDXException ex) when((uint)ex.HResult == 0x8899000C)   // D2DERR_RECREATE_TARGET
         {
             _target?.Dispose();
             _target = null;
         }
     }));
 }
Exemplo n.º 23
0
            /// <summary>
            /// Updates device dependent resources for when RenderTarget changes.
            /// </summary>
            /// <param name="renderTarget">The hosting NinjaScript's RenderTarget</param>
            public void RenderTargetChange(SharpDX.Direct2D1.RenderTarget renderTarget)
            {
                if (renderTarget == null || renderTarget.IsDisposed)
                {
                    return;
                }

                if (dxBrush != null)
                {
                    dxBrush.Dispose();
                }

                if (mediaBrush != null)
                {
                    dxBrush = mediaBrush.ToDxBrush(renderTarget);
                }
            }
Exemplo n.º 24
0
        public RadialGradientBrushImpl(
            Perspex.Media.RadialGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size destinationSize)
        {
            if (brush.GradientStops.Count == 0)
            {
                return;
            }

            var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop
            {
                Color    = s.Color.ToDirect2D(),
                Position = (float)s.Offset
            }).ToArray();

            var centerPoint          = brush.Center.ToPixels(destinationSize);
            var GradientOriginOffset = brush.GradientOrigin.ToPixels(destinationSize);

            // Note: Direct2D supports RadiusX and RadiusY but Cairo backend supports only Radius property
            var radiusX = brush.Radius;
            var radiusY = brush.Radius;

            using (var stops = new SharpDX.Direct2D1.GradientStopCollection(
                       target,
                       gradientStops,
                       brush.SpreadMethod.ToDirect2D()))
            {
                PlatformBrush = new SharpDX.Direct2D1.RadialGradientBrush(
                    target,
                    new SharpDX.Direct2D1.RadialGradientBrushProperties
                {
                    Center = centerPoint.ToSharpDX(),
                    GradientOriginOffset = GradientOriginOffset.ToSharpDX(),
                    RadiusX = (float)radiusX,
                    RadiusY = (float)radiusY
                },
                    new SharpDX.Direct2D1.BrushProperties
                {
                    Opacity   = (float)brush.Opacity,
                    Transform = SharpDX.Matrix3x2.Identity,
                },
                    stops);
            }
        }
        public static Bitmap LoadBitmap(RenderTarget device, byte[] bytes)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (bytes.Length == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bytes));
            }

            using MemoryStream stream   = new MemoryStream(bytes);
            using BitmapDecoder decoder = new BitmapDecoder(imageFactory, stream, DecodeOptions.CacheOnDemand);
            return(Decode(device, decoder));
        }
        private void CreateRenderTarget(SharpDX.DXGI.Surface surface)
        {
            // Create a D2D render target which can draw into our offscreen D3D surface.
            // D2D uses device independant units, like WPF, at 96/inch.
            var properties = new SharpDX.Direct2D1.RenderTargetProperties();

            properties.DpiX        = 96;
            properties.DpiY        = 96;
            properties.MinLevel    = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT;
            properties.PixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            properties.Usage       = SharpDX.Direct2D1.RenderTargetUsage.None;

            if (this.renderTarget != null)
            {
                this.renderTarget.Dispose();
            }

            renderTarget = new SharpDX.Direct2D1.RenderTarget(factory2D, surface, properties);
        }
Exemplo n.º 27
0
            /// <summary>
            /// Updates the Media Bursh and SharpDX Brush also changing opacity.
            /// </summary>
            /// <param name="owner">The hosting NinjaScript's RenderTarget</param>
            /// <param name="owner">The new Media Brush to use</param>
            /// <param name="owner">The new Opacity to use</param>
            public void UpdateBrush(SharpDX.Direct2D1.RenderTarget renderTarget, Brush newMediaBrush, double newOpacity)
            {
                // Set Media Brush to brush passed
                mediaBrush = newMediaBrush;

                // Call SetOpacity() to clone, set opacity and freeze brush.
                SetOpacity(newOpacity);

                // Dispose DX Brushes and other Device Dependant resources
                if (dxBrush != null)
                {
                    dxBrush.Dispose();
                }

                // Recreate DX Brushes and other Device Dependant Resources here, making sure RenderTarget is not null or IsDisposed
                if (renderTarget != null && !renderTarget.IsDisposed)
                {
                    dxBrush = mediaBrush.ToDxBrush(renderTarget);
                }
            }
Exemplo n.º 28
0
        public LinearGradientBrushImpl(
            Perspex.Media.LinearGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size destinationSize)
        {
            if (brush != null)
            {
                var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop {
                    Color = s.Color.ToDirect2D(), Position = (float)s.Offset
                }).ToArray();

                Point startPoint = new Point(0, 0);
                Point endPoint   = new Point(0, 0);

                switch (brush.MappingMode)
                {
                case Perspex.Media.BrushMappingMode.Absolute:
                    // TODO:

                    break;

                case Perspex.Media.BrushMappingMode.RelativeToBoundingBox:
                    startPoint = new Point(brush.StartPoint.X * destinationSize.Width, brush.StartPoint.Y * destinationSize.Height);
                    endPoint   = new Point(brush.EndPoint.X * destinationSize.Width, brush.EndPoint.Y * destinationSize.Height);

                    break;
                }

                PlatformBrush = new SharpDX.Direct2D1.LinearGradientBrush(
                    target,
                    new SharpDX.Direct2D1.LinearGradientBrushProperties {
                    StartPoint = startPoint.ToSharpDX(), EndPoint = endPoint.ToSharpDX()
                },
                    new SharpDX.Direct2D1.BrushProperties {
                    Opacity = (float)brush.Opacity, Transform = target.Transform
                },
                    new SharpDX.Direct2D1.GradientStopCollection(target, gradientStops, brush.SpreadMethod.ToDirect2D())
                    );
            }
        }
Exemplo n.º 29
0
        public LinearGradientBrushImpl(
            ILinearGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Rect destinationRect)
        {
            if (brush.GradientStops.Count == 0)
            {
                return;
            }

            var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop
            {
                Color    = s.Color.ToDirect2D(),
                Position = (float)s.Offset
            }).ToArray();

            var position   = destinationRect.Position;
            var startPoint = position + brush.StartPoint.ToPixels(destinationRect.Size);
            var endPoint   = position + brush.EndPoint.ToPixels(destinationRect.Size);

            using (var stops = new SharpDX.Direct2D1.GradientStopCollection(
                       target,
                       gradientStops,
                       brush.SpreadMethod.ToDirect2D()))
            {
                PlatformBrush = new SharpDX.Direct2D1.LinearGradientBrush(
                    target,
                    new SharpDX.Direct2D1.LinearGradientBrushProperties
                {
                    StartPoint = startPoint.ToSharpDX(),
                    EndPoint   = endPoint.ToSharpDX()
                },
                    new SharpDX.Direct2D1.BrushProperties
                {
                    Opacity   = (float)brush.Opacity,
                    Transform = PrimitiveExtensions.Matrix3x2Identity,
                },
                    stops);
            }
        }
Exemplo n.º 30
0
 private SharpDX.Direct2D1.Bitmap CreateFromBitmap(SharpDX.Direct2D1.RenderTarget InRenderTarget, Bitmap InBitmap)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         InBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
         using (SharpDX.WIC.BitmapDecoder bitDecorder =
                    new SharpDX.WIC.BitmapDecoder(Direct2DDrawingSystem.instance.ImagingFactory,
                                                  ms,
                                                  SharpDX.WIC.DecodeOptions.CacheOnDemand)
                )
         {
             using (SharpDX.WIC.BitmapFrameDecode bfDecode = bitDecorder.GetFrame(0))
             {
                 using (SharpDX.WIC.FormatConverter fConverter = new SharpDX.WIC.FormatConverter(Direct2DDrawingSystem.instance.ImagingFactory))
                 {
                     fConverter.Initialize(bfDecode, SharpDX.WIC.PixelFormat.Format32bppPBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0, SharpDX.WIC.BitmapPaletteType.Custom);
                     return(SharpDX.Direct2D1.Bitmap.FromWicBitmap(InRenderTarget, fConverter));
                 }
             }
         }
     }
 }
        private static Bitmap Decode(RenderTarget device, BitmapDecoder decoder)
        {
            using (BitmapFrameDecode frame = decoder.GetFrame(0))
            {
                FormatConverter converter = new FormatConverter(imageFactory); // Converter get clobbered on failure so we're not wrapping this in a using.
                foreach (Guid format in PixelFormatEnumerator)
                {
                    try
                    {
                        converter.Initialize(frame, format);
                        return(Bitmap.FromWicBitmap(device, converter));
                    }
                    catch // Ignore error here, just try another format. We'll throw an error below if we exhaust all options.
                    {
                        converter?.Dispose();
                        converter = new FormatConverter(imageFactory);
                    }
                }
                converter?.Dispose();
            }

            throw new Exception("Unsupported Image Format!");
        }
Exemplo n.º 32
0
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0);
            using (var factory = new Factory4())
            {

                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //Init Direct3D11 device from Direct3D12 device
            device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            deviceContext11 = device11.ImmediateContext;
            device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>();
            var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                //init Direct2D surfaces
                SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };

                device11on12.CreateWrappedResource(
                    renderTargets[n], format,
                    (int)ResourceStates.Present,
                    (int)ResourceStates.RenderTarget,
                    typeof(SharpDX.Direct3D11.Resource).GUID,
                    out wrappedBackBuffers[n]);

                //Init direct2D surface
                var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>();
                direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
                d2dSurface.Dispose();
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            d2dFactory.Dispose();

            //Init font
            var directWriteFactory = new SharpDX.DirectWrite.Factory();
            textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
            textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White);
            directWriteFactory.Dispose();
        }
Exemplo n.º 33
0
        public static Brush2D ToSharpDX(this Brush brush, RenderTarget2D target)
        {
            SolidColorBrush solidColorBrush = brush as SolidColorBrush;

            if (solidColorBrush != null)
            {
                return solidColorBrush.ToSharpDX(target);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Exemplo n.º 34
0
 public static SolidColorBrush2D ToSharpDX(this SolidColorBrush brush, RenderTarget2D target)
 {
     return new SharpDX.Direct2D1.SolidColorBrush(target, brush.Color.ToSharpDX());
 }
Exemplo n.º 35
0
        private void DirectXRender(List<UIElement> points)
        {
            if (points.Count <= 0)
                return;

            Line initLine = points[0] as Line;

            Point
                p1 = new Point
                (
                    Math.Min(initLine.X1 - initLine.StrokeThickness / 2, initLine.X2 - initLine.StrokeThickness / 2),
                    Math.Min(initLine.Y1 - initLine.StrokeThickness / 2, initLine.Y2 - initLine.StrokeThickness / 2)
                ),
                p2 = new Point
                (
                    Math.Max(initLine.X1 + initLine.StrokeThickness / 2, initLine.X2 + initLine.StrokeThickness / 2),
                    Math.Max(initLine.Y1 + initLine.StrokeThickness / 2, initLine.Y2 + initLine.StrokeThickness / 2)
                );

            foreach (var child in points)
            {
                var line = child as Line;

                if (line == null)
                    continue;

                if (p1.X > line.X1 - line.StrokeThickness / 2)
                    p1.X = line.X1 - line.StrokeThickness / 2;
                if (p1.X > line.X2 - line.StrokeThickness / 2)
                    p1.X = line.X2 - line.StrokeThickness / 2;

                if (p2.X < line.X1 + line.StrokeThickness / 2)
                    p2.X = line.X1 + line.StrokeThickness / 2;
                if (p2.X < line.X2 + line.StrokeThickness / 2)
                    p2.X = line.X2 + line.StrokeThickness / 2;

                if (p1.Y > line.Y1 - line.StrokeThickness / 2)
                    p1.Y = line.Y1 - line.StrokeThickness / 2;
                if (p1.Y > line.Y2 - line.StrokeThickness / 2)
                    p1.Y = line.Y2 - line.StrokeThickness / 2;

                if (p2.Y < line.Y1 + line.StrokeThickness / 2)
                    p2.Y = line.Y1 + line.StrokeThickness / 2;
                if (p2.Y < line.Y2 + line.StrokeThickness / 2)
                    p2.Y = line.Y2 + line.StrokeThickness / 2;
            }

            var bndRect = new Rect(p1, p2);

            var dxTarget = new SurfaceImageSource
            (
                (int)(bndRect.Width * DisplayProperties.LogicalDpi / 96.0 + 1),
                (int)(bndRect.Height * DisplayProperties.LogicalDpi / 96.0 + 1)
            );

            SharpDX.DXGI.ISurfaceImageSourceNative dxTargetNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNative>(dxTarget);
            dxTargetNative.Device = d3dDevice.QueryInterface<SharpDX.DXGI.Device>();

            /*
             * Draw Logic
             */
            SharpDX.DrawingPoint drawingPoint;
            var surface = dxTargetNative.BeginDraw(new SharpDX.Rectangle(0, 0,
                (int)(bndRect.Width * DisplayProperties.LogicalDpi / 96.0 + 1),
                (int)(bndRect.Height * DisplayProperties.LogicalDpi / 96.0 + 1)),
                out drawingPoint);

            var dxRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, surface, new SharpDX.Direct2D1.RenderTargetProperties()
            {
                DpiX = DisplayProperties.LogicalDpi,
                DpiY = DisplayProperties.LogicalDpi,
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                Type = SharpDX.Direct2D1.RenderTargetType.Default,
                Usage = SharpDX.Direct2D1.RenderTargetUsage.None
            });

            dxRenderTarget.BeginDraw();
            dxRenderTarget.Clear(SharpDX.Color.Transparent);

            foreach (var child in points)
            {
                var line = child as Line;

                if (line == null)
                    continue;

                Color c = (line.Stroke as SolidColorBrush).Color;
                var brush = new SharpDX.Direct2D1.SolidColorBrush(dxRenderTarget, new SharpDX.Color(c.R, c.G, c.B, c.A));

                var style = new SharpDX.Direct2D1.StrokeStyleProperties();
                style.LineJoin = SharpDX.Direct2D1.LineJoin.Round;
                style.StartCap = SharpDX.Direct2D1.CapStyle.Round;
                style.EndCap = SharpDX.Direct2D1.CapStyle.Round;
                var stroke = new SharpDX.Direct2D1.StrokeStyle(d2dFactory, style);

                dxRenderTarget.DrawLine(
                    new SharpDX.DrawingPointF((float)(line.X1 - bndRect.Left), (float)(line.Y1 - bndRect.Top)),
                    new SharpDX.DrawingPointF((float)(line.X2 - bndRect.Left), (float)(line.Y2 - bndRect.Top)),
                    brush, (float)line.StrokeThickness, stroke);
            }

            dxRenderTarget.EndDraw();
            dxTargetNative.EndDraw();

            var dxImage = new Image();
            dxImage.Source = dxTarget;
            canvas.Children.Add(dxImage);
            Canvas.SetLeft(dxImage, bndRect.X);
            Canvas.SetTop(dxImage, bndRect.Y);
        }
        private void CreateRenderTarget(SharpDX.DXGI.Surface surface)
        {
            // Create a D2D render target which can draw into our offscreen D3D surface. 
            // D2D uses device independant units, like WPF, at 96/inch.
            var properties = new SharpDX.Direct2D1.RenderTargetProperties();
            properties.DpiX = 96;
            properties.DpiY = 96;
            properties.MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT;
            properties.PixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            properties.Usage = SharpDX.Direct2D1.RenderTargetUsage.None;

            if (this.renderTarget != null)
            {
                this.renderTarget.Dispose();
            }

            renderTarget = new SharpDX.Direct2D1.RenderTarget(factory2D, surface, properties);
        }