Exemplo n.º 1
2
 public override void Render(RenderTarget pRender, float pPercent)
 {
     pRender.Transform = Matrix3x2.Identity;
     pRender.DrawText("dx:" + dx + "  dy:" + dy + "  da:" + da, Constants.SmallFont, new RectangleF(0, 0, 200, 50), new SolidColorBrush(pRender, Color4.Black));
     pRender.Transform = Matrix3x2.Rotation(MathUtil.DegreesToRadians(-a + 180)) * Matrix3x2.Translation(x, y);
     pRender.DrawBitmap(ShipBitmap, new RectangleF(-17, -17, 34, 34), 1.0f, BitmapInterpolationMode.Linear);
 }
Exemplo n.º 2
0
        private BitmapBrush CreateDirectBrush(
            ImageBrush brush,
            RenderTarget target,
            Bitmap image, 
            Rect sourceRect, 
            Rect destinationRect)
        {
            var tileMode = brush.TileMode;
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                Matrix.CreateScale(scale) *
                Matrix.CreateTranslation(translate);

            var opts = new BrushProperties
            {
                Transform = transform.ToDirect2D(),
                Opacity = (float)brush.Opacity,
            };

            var bitmapOpts = new BitmapBrushProperties
            {
                ExtendModeX = GetExtendModeX(tileMode),
                ExtendModeY = GetExtendModeY(tileMode),                
            };

            return new BitmapBrush(target, image, bitmapOpts, opts);
        }
Exemplo n.º 3
0
        public override void Render(RenderTarget pRender, float pPercent)
        {
            pRender.Clear(new RawColor4(0.9f, 0.85f, 0.75f, 1.0f));

            upgradesButton.Render(pRender, pPercent);
            playerShip.Render(pRender, pPercent);
        }
Exemplo n.º 4
0
 public PerspexTextRenderer(
     RenderTarget target,
     Brush foreground)
 {
     this.renderTarget = target;
     this.foreground = foreground;
 }
Exemplo n.º 5
0
        public void OnRender(RenderTarget target)
        {
            if(gBorderBrush == null)
            {
                gBackgroundBrush = Brushes.Solid[0xCC555555];
                gBackgroundHoverBrush = Brushes.Solid[0xCC888888];
                gClickBrush = Brushes.Solid[0xFFFF7F00];
                gBackgroundClickedBrush = Brushes.Solid[0xCCBBBBBB];
                gBorderBrush = Brushes.White;
            }

            target.DrawTextLayout(new Vector2(Position.X + Size + 7, Position.Y - 2), mTextDraw, Brushes.White);

            var brush = gBackgroundBrush;
            if (mIsPressed)
                brush = gBackgroundClickedBrush;
            else if (mIsHovered)
                brush = gBackgroundHoverBrush;

            target.FillRectangle(mTargetRect, brush);
            target.DrawRectangle(mTargetRect, gBorderBrush);
            if (!Checked) return;

            target.DrawLine(Position + new Vector2(3, 3), Position + new Vector2(mSize - 3, mSize - 3), gClickBrush,
                mSize / 4.0f);
            target.DrawLine(new Vector2(Position.X + 3, Position.Y + mSize - 3),
                new Vector2(Position.X + mSize - 3, Position.Y + 3), gClickBrush, mSize / 4.0f);
        }
Exemplo n.º 6
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
 
            // Direct2D
            var renderTargetProperties = new RenderTargetProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            var hwndRenderTargetProperties = new HwndRenderTargetProperties()
            {
                Hwnd = this.Handle,
                PixelSize = new Size2(bounds.Width, bounds.Height),
                PresentOptions = PresentOptions.Immediately,
            };
            renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);

            var bitmapProperties = new BitmapProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bounds.Width, bounds.Height), bitmapProperties);

            textFormat = new TextFormat(directWriteFacrtory, "Arial", FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 96.0f);
            textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            textFormat.TextAlignment = TextAlignment.Center;

            solidColorBrush = new SolidColorBrush(renderTarget, Color4.White);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Draws all the entities wich are visible in the viewport
        /// </summary>
        /// <param name="g">The RenderTarget used to perform the drawing operations.</param>
        public virtual void Draw(RenderTarget g)
        {
            //At the start set the matrix to the identy viewport matrix
            SetMatrixViewportID(g);
            //Start drawing all the entities.
            foreach (BaseEntity ent in VisibleEntities)
            {
                //If an entity is mirror the matrix needs to get mirrored too.
                if(ent.Mirrored)
                {
                    Matrix3x2 m = g.Transform;
                    m.ScaleVector = new Vector2(-1, 1);
                    m.TranslationVector = new Vector2(-VIEWPORT.X + ent.X + ent.Width + ent.X, -VIEWPORT.Y);
                    g.Transform = m;
                    /*
                    Vector2 mirroredviewPortTranslation = new Vector2(-VIEWPORT.X + ent.X + ent.Width + ent.X, -VIEWPORT.Y);
                    ViewportIDMatrixMirror.TranslationVector = mirroredviewPortTranslation;
                    g.Transform = ViewportIDMatrixMirror;
                    */
                }

                //Actual drawing of the entity
                ent.Draw(g);

                //If the entity was mirrored then the matrix needs to be reset back to the identity viewport matrix.
                if (ent.Mirrored)
                    SetMatrixViewportID(g);
            }
            if (Config.DEBUG_MODE == DebugMode.DISPLAY_HITBOX)
            {
                Quad.Draw(g);
            }
            g.Transform = Matrix.Identity;
        }
 public Direct2D1DrawingContext(Factory factory, RenderTarget target)
 {
     this.factory = factory;
     this.target = target;
     this.target.BeginDraw();
     this.stack = new Stack<object>();
 }
Exemplo n.º 9
0
        public void OnUpdateTarget(RenderTarget target)
        {
            foreach (var pair in mBrushes)
                pair.Value.OnUpdateBrush(pair.Key, target);

            mTarget = target;
        }
Exemplo n.º 10
0
        /**
            Create a drawing target from an already existing RenderTarget.

            Note that the RenderTarget must use the the same Factory the
            drawing backend does.
        **/
        public IDrawingTarget CreateDrawingTarget(RenderTarget renderTarget)
        {
            var width = renderTarget.Size.Width;
            var height = renderTarget.Size.Height;

            var state = new DrawingState();
            var transform = new DrawingTransform();
            var drawingTarget = new DrawingTarget(state, transform, renderTarget, (int)Math.Floor(width), (int)Math.Floor(height));

            var target = new DrawingTargetSplitter(
                this,
                state,
                transform,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                () =>
                {
                    drawingTarget.Dispose();
                });

            var pixelAligner = PixelAligningDrawingTarget.Create(target, target.Dispose, state, transform);
            return pixelAligner;
        }
Exemplo n.º 11
0
        public IDisposable beginDraw(out IDrawingContext context)
        {
            var surface = _texture.AsSurface();

            var rtProperties = new RenderTargetProperties()
            {
                DpiX = 96,
                DpiY = 96,
                Type = RenderTargetType.Default,
                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
            };

            var renderTarget = new RenderTarget(_factory, surface, rtProperties);

            var c = new RenderTargetDrawingContext(renderTarget, _width, _height);
            context = c;

            renderTarget.BeginDraw();

            return new DisposeAction(() =>
                {
                    renderTarget.EndDraw();

                    c.Dispose();
                    renderTarget.Dispose();
                    surface.Dispose();
                });
        }
Exemplo n.º 12
0
 public void RenderScatterGeometry(RenderTarget renderTarget)
 {
     double[] x = curve.X;
     double[] y = curve.Y;
     int length = x.Length;
     double xScale, xOffset, yScale, yOffset;
     xScale = graphToCanvas.Matrix.M11;
     xOffset = graphToCanvas.Matrix.OffsetX - this.xOffsetMarker;
     yScale = graphToCanvas.Matrix.M22;
     yOffset = graphToCanvas.Matrix.OffsetY - this.yOffsetMarker;
     bool[] include = curve.includeMarker;
     StrokeStyleProperties properties = new StrokeStyleProperties();
     properties.LineJoin = LineJoin.MiterOrBevel;
     StrokeStyle strokeStyle = new StrokeStyle(renderTarget.Factory, properties);
     for (int i = 0; i < length; ++i)
     {
         if (include[i])
         {
             renderTarget.Transform = (Matrix3x2)Matrix.Translation((float)(x[i] * xScale + xOffset), (float)(y[i] * yScale + yOffset), 0);
             renderTarget.FillGeometry(Geometry, FillBrush);
             renderTarget.DrawGeometry(Geometry, Brush, (float)StrokeThickness, strokeStyle);
         }
     }
     renderTarget.Transform = Matrix3x2.Identity;
 }
        public void CleanUp(RenderTarget target, Graphics g, Map map)
        {
            target.EndDraw();

            var hdc = (IntPtr)target.Tag;
            g.ReleaseHdc(hdc);
        }
Exemplo n.º 14
0
        public static void Render(RenderTarget pRender, float pPercent)
        {
            if (Loading) return;

            pRender.BeginDraw();
            currentLevel.Render(pRender, pPercent);
            pRender.EndDraw();
        }
Exemplo n.º 15
0
 /// <summary>
 /// Loads a Direct2D Bitmap from a file using System.Drawing.Image.FromFile(...)
 /// </summary>
 /// <param name="renderTarget">The render target.</param>
 /// <param name="file">The file.</param>
 /// <returns>A D2D1 Bitmap</returns>
 public static Bitmap LoadFromFile(RenderTarget renderTarget, string file)
 {
     // Loads from file using System.Drawing.Image
     using (var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(file))
     {
         return LoadFromImage(renderTarget, file, bitmap);
     }
 }
Exemplo n.º 16
0
 //public static Brush TEXT_BRUSH;
 public static void Initialize(RenderTarget g)
 {
     SCBRUSH_RED = new SolidColorBrush(g, Color.Red);
     SCBRUSH_BLACK = new SolidColorBrush(g, Color.Black);
     WRITE_FACTORY = new SharpDX.DirectWrite.Factory();
     TEXT_FORMAT = new TextFormat(WRITE_FACTORY, "Arial", 14);
     //TEXT_BRUSH = new SolidColorBrush(g, Color.Red);
 }
Exemplo n.º 17
0
 /// <summary>	
 /// Create a mesh that uses triangles to describe a shape and populates it with triangles.
 /// </summary>	
 /// <param name="renderTarget">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="triangles">An array of <see cref="SharpDX.Direct2D1.Triangle"/> structures that describe the triangles to add to this mesh.</param>
 /// <unmanaged>HRESULT CreateMesh([Out] ID2D1Mesh** mesh)</unmanaged>
 public Mesh(RenderTarget renderTarget, SharpDX.Direct2D1.Triangle[] triangles) : this(renderTarget)
 {
     using(var sink = Open())
     {
         sink.AddTriangles(triangles);
         sink.Close();
     }
 }
Exemplo n.º 18
0
 public void OnRender(RenderTarget target)
 {
     lock(mElements)
     {
         foreach (var component in mElements)
             component.OnRender(target);
     }
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawingContext"/> class.
 /// </summary>
 /// <param name="renderTarget">The render target to draw to.</param>
 /// <param name="directWriteFactory">The DirectWrite factory.</param>
 public DrawingContext(
     RenderTarget renderTarget,
     SharpDX.DirectWrite.Factory directWriteFactory)
 {
     this.renderTarget = renderTarget;
     this.directWriteFactory = directWriteFactory;
     this.renderTarget.BeginDraw();
 }
Exemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawingContext"/> class.
 /// </summary>
 /// <param name="renderTarget">The render target to draw to.</param>
 /// <param name="directWriteFactory">The DirectWrite factory.</param>
 public DrawingContext(
     SharpDX.Direct2D1.RenderTarget renderTarget,
     SharpDX.DirectWrite.Factory directWriteFactory)
 {
     _renderTarget = renderTarget;
     _directWriteFactory = directWriteFactory;
     _renderTarget.BeginDraw();
 }
Exemplo n.º 21
0
        public void OnRender(RenderTarget target)
        {
            target.PushAxisAlignedClip(new RectangleF(Position.X, Position.Y, Size.X, Size.Y), AntialiasMode.Aliased);

            target.DrawTextLayout(Position, mTextDraw, Color, mMultiline ? DrawTextOptions.None : DrawTextOptions.Clip);

            target.PopAxisAlignedClip();
        }
Exemplo n.º 22
0
        static void Main()
        {
            var form = new RenderForm("KinectLight");
            form.Size = new System.Drawing.Size(1920,1200);

            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            SharpDX.Direct3D10.Device1 device;
            SwapChain swapChain;
            SharpDX.Direct3D10.Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, SharpDX.Direct3D10.FeatureLevel.Level_10_1, out device, out swapChain);

            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var surface = Surface.FromSwapChain(swapChain, 0);

            RenderTarget dc = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            MainGame.Instance.Height = form.ClientSize.Height;
            MainGame.Instance.Width = form.ClientSize.Width;
            GameTime gameTime = new GameTime();

            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{name}",
                new { id = RouteParameter.Optional });

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            RenderLoop.Run(form, () =>
            {
                gameTime.StartFrame();
                MainGame.Instance.Update(gameTime);
                dc.BeginDraw();
                dc.Clear(Colors.White);
                MainGame.Instance.Render(dc);
                var res = dc.EndDraw();
                swapChain.Present(1, PresentFlags.None);
                //Thread.Sleep(1);
            });

            server.Dispose();
            MainGame.Instance.Dispose();
            dc.Dispose();
            surface.Dispose();
            d2dFactory.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Exemplo n.º 23
0
 public AvaloniaTextRenderer(
     DrawingContext context,
     SharpDX.Direct2D1.RenderTarget target,
     Brush foreground)
 {
     _context = context;
     _renderTarget = target;
     _foreground = foreground;
 }
Exemplo n.º 24
0
        public VisualBrushImpl(
            VisualBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;

            if (visual == null)
            {
                return;
            }

            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var tileMode = brush.TileMode;
            var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);
                var renderer = new RenderTarget(intermediate);

                using (var ctx = renderer.CreateDrawingContext())
                using (ctx.PushClip(drawRect))
                using (ctx.PushPostTransform(transform))
                {
                    intermediate.Clear(new Color4(0));
                    ctx.Render(visual);
                }

                this.PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }
        }
Exemplo n.º 25
0
        public override void Render(RenderTarget pRender, float pPercent)
        {
            pRender.Clear(new RawColor4(0.9f, 0.85f, 0.75f, 1.0f));

            MainTitle.Render(pRender, pPercent);
            NewGameButton.Render(pRender, pPercent);
            OptionsButton.Render(pRender, pPercent);
            QuitButton.Render(pRender, pPercent);
        }
Exemplo n.º 26
0
        public override void Render(RenderTarget pRender, float pPercent)
        {
            pRender.Transform = Matrix3x2.Identity;

            RectangleF rect = new RectangleF(x, y, width, height);
            pRender.FillRectangle(rect, highlight ? highlightBrush : backBrush);
            pRender.DrawRectangle(rect, borderBrush);
            pRender.DrawTextLayout(new Vector2(x + dx * (pPercent - 1), y + dy * (pPercent - 1)), textLayout, textBrush);
        }
Exemplo n.º 27
0
        public VisualBrushImpl(
            VisualBrush brush,
            RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;
            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var bitmapSize = brush.TileMode == TileMode.None ? targetSize : destinationRect.Size;
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var options = CompatibleRenderTargetOptions.None;

            using (var brt = new BitmapRenderTarget(target, options, bitmapSize.ToSharpDX()))
            {
                var renderer = new Renderer(brt);
                var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                                Matrix.CreateScale(scale) *
                                Matrix.CreateTranslation(translate);

                Rect drawRect;

                if (brush.TileMode == TileMode.None)
                {
                    drawRect = destinationRect;
                    transform *= Matrix.CreateTranslation(destinationRect.Position);
                }
                else
                {
                    drawRect = new Rect(0, 0, destinationRect.Width, destinationRect.Height);
                }

                renderer.Render(visual, null, transform, drawRect);

                var result = new BitmapBrush(brt, brt.Bitmap);
                result.ExtendModeX = (brush.TileMode & TileMode.FlipX) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;
                result.ExtendModeY = (brush.TileMode & TileMode.FlipY) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;

                if (brush.TileMode != TileMode.None)
                {
                    result.Transform = SharpDX.Matrix3x2.Translation(
                        (float)destinationRect.X,
                        (float)destinationRect.Y);
                }

                PlatformBrush = result;
            }
        }
Exemplo n.º 28
0
 internal void InitializeResources(RenderTarget d2dRenderTarget)
 {
     if (!initialized)
     {
         Fill = new SolidColorBrush(d2dRenderTarget, Colors.Green);
         Stroke = new SolidColorBrush(d2dRenderTarget, Colors.Azure);
         initialized = true;
        texture = MainGame.LoadFromFile(d2dRenderTarget, @"C:\git\KinectLight\resources\Logo_EDGE_40.bmp");
     }
 }
Exemplo n.º 29
0
        internal void Render(RenderTarget d2dRenderTarget)
        {
            InitializeResources(d2dRenderTarget);

            d2dRenderTarget.Transform = Matrix.Translation(Position);
            d2dRenderTarget.DrawBitmap(texture,1, BitmapInterpolationMode.Linear);
            //d2dRenderTarget.FillRectangle(new RectangleF(-20, -20, 20, 20), Fill);

            //d2dRenderTarget.DrawRectangle(new RectangleF(-20, -20, 20, 20), Stroke);
        }
        public RenderTargetDrawingContext(RenderTarget target, int width, int height)
        {
            _target = target;

            Width = width;
            Height = height;

            _strokeBrush = new SolidColorBrush(_target, new Color4(0, 0, 0, 1));
            _strokeWidth = 1;
        }
Exemplo n.º 31
0
        public VRUI(Device device, SharpDX.Toolkit.Graphics.GraphicsDevice gd)
        {
            Texture2DDescription uiTextureDescription = new Texture2DDescription()
            {
                Width             = 1024,
                Height            = 512,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.B8G8R8A8_UNorm,
                Usage             = ResourceUsage.Default,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.Shared
            };

            uiTexture = new SharpDX.Direct3D11.Texture2D(device, uiTextureDescription);

            using (DX2D.Factory factory2d = new DX2D.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, DX2D.DebugLevel.Information))
            {
                DX2D.RenderTargetProperties renderTargetProperties = new DX2D.RenderTargetProperties()
                {
                    DpiX        = 96,
                    DpiY        = 96,
                    PixelFormat = new DX2D.PixelFormat(Format.B8G8R8A8_UNorm, DX2D.AlphaMode.Premultiplied),
                    Type        = DX2D.RenderTargetType.Hardware,
                    MinLevel    = DX2D.FeatureLevel.Level_10,
                    Usage       = DX2D.RenderTargetUsage.None
                };
                using (var uiSurface = uiTexture.QueryInterface <Surface>())
                    target2d = new DX2D.RenderTarget(factory2d, uiSurface, renderTargetProperties)
                    {
                        AntialiasMode = DX2D.AntialiasMode.PerPrimitive
                    };
            }


            // 2D materials
            uiEffect = new SharpDX.Toolkit.Graphics.BasicEffect(gd)
            {
                PreferPerPixelLighting = false,
                Texture         = SharpDX.Toolkit.Graphics.Texture2D.New(gd, uiTexture),
                TextureEnabled  = true,
                LightingEnabled = false
            };


            BlendStateDescription blendStateDescription = new BlendStateDescription()
            {
                AlphaToCoverageEnable = false
            };

            blendStateDescription.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDescription.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
            blendStateDescription.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].SourceAlphaBlend      = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDescription.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            using (var blendState = SharpDX.Toolkit.Graphics.BlendState.New(gd, blendStateDescription))
                gd.SetBlendState(blendState);

            uiPrimitive = SharpDX.Toolkit.Graphics.GeometricPrimitive.Plane.New(gd, 2, 1);

            using (SharpDX.DirectWrite.Factory factoryDW = new SharpDX.DirectWrite.Factory())
            {
                textFormat = new SharpDX.DirectWrite.TextFormat(factoryDW, "Segoe UI Light", 34f)
                {
                    TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                    ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center
                };

                textFormatSmall = new SharpDX.DirectWrite.TextFormat(factoryDW, "Segoe UI Light", 20f)
                {
                    TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                    ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center
                };
            }

            textBrush = new SharpDX.Direct2D1.SolidColorBrush(target2d, new Color(1f, 1f, 1f, 1f));
            blueBrush = new SharpDX.Direct2D1.SolidColorBrush(target2d, new Color(0, 167, 245, 255));

            uiInitialized = true;
        }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderTarget"/> class.
 /// </summary>
 /// <param name="renderTarget">The render target.</param>
 public RenderTarget(SharpDX.Direct2D1.RenderTarget renderTarget)
 {
     Direct2DFactory    = AvaloniaLocator.Current.GetService <Factory>();
     DirectWriteFactory = AvaloniaLocator.Current.GetService <DwFactory>();
     _renderTarget      = renderTarget;
 }
Exemplo n.º 33
0
 public D2DSolidBrush(SharpDX.Direct2D1.RenderTarget target, RawColor4 color)
 {
     NativeBrush = new SolidColorBrush(target, color);
 }
Exemplo n.º 34
0
 protected virtual void AfterDraw(D2D1.RenderTarget renderTarget)
 {
 }
Exemplo n.º 35
0
 protected abstract void Draw(D2D1.RenderTarget renderTarget);
Exemplo n.º 36
0
        public static sd.Brush ToDx(this Brush brush, sd.RenderTarget target)
        {
            var obj = (BrushData)brush.ControlObject;

            return(obj.Get(target));
        }
Exemplo n.º 37
0
        /// <summary>
        /// Creates and pushes a D2D layer if necessary. Returns the layer or null if not required.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="renderTarget">The render target.</param>
        /// <param name="rootElement"></param>
        /// <returns></returns>
        public static D2D.Layer CreateAndPushLayerIfNecessary(this Jupiter.FrameworkElement element, D2D.RenderTarget renderTarget, Jupiter.FrameworkElement rootElement)
        {
            if (element.Opacity >= 1)
            //element.Clip == null &&
            //element.RenderTransform == null)
            {
                return(null);
            }

            var layer           = new D2D.Layer(renderTarget);
            var layerParameters = new D2D.LayerParameters();

            layerParameters.Opacity       = (float)element.Opacity;
            layerParameters.ContentBounds = element.GetBoundingRect(rootElement).ToSharpDX();
            renderTarget.PushLayer(ref layerParameters, layer);

            return(layer);
        }
Exemplo n.º 38
0
 public void AssignResources(D2D1.RenderTarget renderTarget, D2D1.SolidColorBrush defaultBrush)
 {
     _renderTarget = renderTarget;
     _defaultBrush = defaultBrush;
 }
Exemplo n.º 39
0
 public void Present(D2D1.RenderTarget renderTarget, Block block, double secsPassed)
 {
     _brush.Color = Color.SmoothStep(_normalColor, _flashingColor, (float)ConvertCosineValueToGrayScale(block.Pattern.Sample(secsPassed)));
     renderTarget.FillRectangle(block.ContentRect, _brush);
 }
Exemplo n.º 40
0
 public void Initialize(D2D1.RenderTarget renderTarget, RawVector2 size, Block[] blocks) => _brush = new D2D1.SolidColorBrush(renderTarget, _normalColor);
Exemplo n.º 41
0
        public static async Task <D2D.Brush> ToSharpDX(
            this Jupiter.Media.Brush brush,
            D2D.RenderTarget renderTarget,
            RectangleF rect)
        {
            if (brush == null)
            {
                return(null);
            }

            var solidColorBrush = brush as Jupiter.Media.SolidColorBrush;

            if (solidColorBrush != null)
            {
                var color = solidColorBrush.Color.ToSharpDX();

                return(new D2D.SolidColorBrush(
                           renderTarget,
                           color,
                           new D2D.BrushProperties
                {
                    Opacity = (float)solidColorBrush.Opacity
                }));
            }

            var linearGradientBrush = brush as Jupiter.Media.LinearGradientBrush;

            if (linearGradientBrush != null)
            {
                var properties = new D2D.LinearGradientBrushProperties();
                //properties.StartPoint =
                //    new Vector2(
                //        (float)(linearGradientBrush.StartPoint.X * renderTarget.Size.Width),
                //        (float)(linearGradientBrush.StartPoint.Y * renderTarget.Size.Height));
                //properties.EndPoint =
                //    new Vector2(
                //        (float)(linearGradientBrush.EndPoint.X * renderTarget.Size.Width),
                //        (float)(linearGradientBrush.EndPoint.Y * renderTarget.Size.Height));
                properties.StartPoint =
                    new Vector2(
                        rect.Left + (float)(linearGradientBrush.StartPoint.X * rect.Width),
                        rect.Top + (float)(linearGradientBrush.StartPoint.Y * rect.Height));
                properties.EndPoint =
                    new Vector2(
                        rect.Left + (float)(linearGradientBrush.EndPoint.X * rect.Width),
                        rect.Top + (float)(linearGradientBrush.EndPoint.Y * rect.Height));

                var brushProperties = new D2D.BrushProperties();

                brushProperties.Opacity = (float)linearGradientBrush.Opacity;

                if (linearGradientBrush.Transform != null)
                {
                    brushProperties.Transform = linearGradientBrush.Transform.ToSharpDX();
                }

                var gradientStopCollection = linearGradientBrush.GradientStops.ToSharpDX(renderTarget);

                return(new D2D.LinearGradientBrush(
                           renderTarget,
                           properties,
                           brushProperties,
                           gradientStopCollection));
            }

            var imageBrush = brush as Jupiter.Media.ImageBrush;

            if (imageBrush != null)
            {
                var bitmap = await imageBrush.ImageSource.ToSharpDX(renderTarget);

                var       w         = bitmap.PixelSize.Width;
                var       h         = bitmap.PixelSize.Height;
                Matrix3x2 transform = Matrix3x2.Identity;

                switch (imageBrush.Stretch)
                {
                case Stretch.None:
                    transform.M31 += rect.Left + rect.Width * 0.5f - w / 2;
                    transform.M32 += rect.Top + rect.Height * 0.5f - h / 2;
                    break;

                case Stretch.Fill:
                    transform = Matrix3x2.Scaling(
                        rect.Width / w,
                        rect.Height / h);
                    transform.M31 += rect.Left;
                    transform.M32 += rect.Top;
                    break;

                case Stretch.Uniform:
                    var bitmapAspectRatio  = (float)w / h;
                    var elementAspectRatio = rect.Width / rect.Height;

                    if (bitmapAspectRatio > elementAspectRatio)
                    {
                        var scale = rect.Width / w;
                        transform      = Matrix3x2.Scaling(scale);
                        transform.M31 += rect.Left;
                        transform.M32 += rect.Top + rect.Height * 0.5f - scale * h / 2;
                    }
                    else     // (elementAspectRatio >= bitmapAspectRatio)
                    {
                        var scale = rect.Height / h;
                        transform      = Matrix3x2.Scaling(scale);
                        transform.M31 += rect.Left + rect.Width * 0.5f - scale * w / 2;
                        transform.M32 += rect.Top;
                    }

                    break;

                case Stretch.UniformToFill:
                    var bitmapAspectRatio2  = (float)w / h;
                    var elementAspectRatio2 = rect.Width / rect.Height;

                    if (bitmapAspectRatio2 > elementAspectRatio2)
                    {
                        var scale = rect.Height / h;
                        transform      = Matrix3x2.Scaling(scale);
                        transform.M31 += rect.Left + rect.Width * 0.5f - scale * w / 2;
                        transform.M32 += rect.Top;
                    }
                    else     // (elementAspectRatio >= bitmapAspectRatio)
                    {
                        var scale = rect.Width / w;
                        transform      = Matrix3x2.Scaling(scale);
                        transform.M31 += rect.Left;
                        transform.M32 += rect.Top + rect.Height * 0.5f - scale * h / 2;
                    }

                    break;
                }


                return(new D2D.BitmapBrush1(
                           (D2D.DeviceContext)renderTarget,
                           bitmap,
                           new D2D.BitmapBrushProperties1
                {
                    ExtendModeX = D2D.ExtendMode.Clamp,
                    ExtendModeY = D2D.ExtendMode.Clamp,
                    InterpolationMode = D2D.InterpolationMode.HighQualityCubic
                })
                {
                    Opacity = (float)imageBrush.Opacity,
                    Transform = transform
                });
                //    var writeableBitmap = imageBrush.ImageSource as WriteableBitmap;
                //    var bitmapImage = imageBrush.ImageSource as BitmapImage;

                //    if (bitmapImage != null)
                //    {
                //        writeableBitmap =
                //            await WriteableBitmapFromBitmapImageExtension.FromBitmapImage(bitmapImage);
                //    }
                //    CompositionEngine c;

                //    return new D2D.BitmapBrush(
                //        renderTarget,
                //        writeableBitmap.ToSharpDX(),
                //}
            }

#if DEBUG
            throw new NotSupportedException("Only SolidColorBrush supported for now");
#else
            return(new D2D.SolidColorBrush(renderTarget, Color.Transparent));
#endif
        }
Exemplo n.º 42
0
        public static async Task <D2D.Bitmap1> ToSharpDX(this ImageSource imageSource, D2D.RenderTarget renderTarget)
        {
            var wb = imageSource as Jupiter.Media.Imaging.WriteableBitmap;

            if (wb == null)
            {
                var bi = imageSource as Jupiter.Media.Imaging.BitmapImage;

                if (bi == null)
                {
                    return(null);
                }

                wb = await WriteableBitmapFromBitmapImageExtension.FromBitmapImage(bi);

                if (wb == null)
                {
                    return(null);
                }
            }

            int width  = wb.PixelWidth;
            int height = wb.PixelHeight;
            //var cpuReadBitmap = CompositionEngine.CreateCpuReadBitmap(width, height);
            var cpuReadBitmap = CompositionEngine.CreateRenderTargetBitmap(width, height);

            //var mappedRect = cpuReadBitmap.Map(D2D.MapOptions.Write | D2D.MapOptions.Read | D2D.MapOptions.Discard);

            using (var readStream = wb.PixelBuffer.AsStream())
            {
                var pitch = width * 4;
                //using (var writeStream =
                //    new DataStream(
                //        userBuffer: mappedRect.DataPointer,
                //        sizeInBytes: mappedRect.Pitch * height,
                //        canRead: false,
                //        canWrite: true))
                {
                    var buffer = new byte[pitch * height];
                    readStream.Read(buffer, 0, buffer.Length);
                    cpuReadBitmap.CopyFromMemory(buffer, pitch);

                    //for (int i = 0; i < height; i++)
                    //{
                    //    readStream.Read(buffer, 0, mappedRect.Pitch);
                    //    writeStream.Write(buffer, 0, buffer.Length);
                    //}
                }
            }
            //cpuReadBitmap.CopyFromMemory();

            return(cpuReadBitmap);
        }
Exemplo n.º 43
0
 public CoverLayer(D2D.RenderTarget renderTarget) : base(renderTarget)
 {
     _brush = new D2D.SolidColorBrush(renderTarget, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
 }
Exemplo n.º 44
0
        internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Jupiter.Shapes.Path path)
        {
            var rect = path.GetBoundingRect(rootElement).ToSharpDX();
            var fill = await path.Fill.ToSharpDX(renderTarget, rect);

            var stroke = await path.Stroke.ToSharpDX(renderTarget, rect);

            var layer        = path.CreateAndPushLayerIfNecessary(renderTarget, rootElement);
            var oldTransform = renderTarget.Transform;

            renderTarget.Transform = new Matrix3x2(
                1, 0, 0, 1, rect.Left, rect.Top);
            //renderTarget.PushLayer(ref layerParameters, layer);

            var d2dGeometry = path.Data.ToSharpDX(compositionEngine.D2DFactory, rect);

            if (fill != null)
            {
                renderTarget.FillGeometry(d2dGeometry, fill, null);
            }

            if (stroke != null &&
                path.StrokeThickness > 0)
            {
                renderTarget.DrawGeometry(
                    d2dGeometry,
                    stroke,
                    (float)path.StrokeThickness,
                    path.GetStrokeStyle(compositionEngine.D2DFactory));
            }

            //if (path.StrokeThickness > 0 &&
            //    stroke != null)
            //{
            //    var halfThickness = (float)(path.StrokeThickness * 0.5);
            //    roundedRect.Rect = rect.Eroded(halfThickness);

            //    if (fill != null)
            //    {
            //        renderTarget.FillRoundedRectangle(roundedRect, fill);
            //    }

            //    renderTarget.DrawRoundedRectangle(
            //        roundedRect,
            //        stroke,
            //        (float)path.StrokeThickness,
            //        path.GetStrokeStyle(compositionEngine.D2DFactory));
            //}
            //else
            //{
            //    renderTarget.FillRoundedRectangle(roundedRect, fill);
            //}

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

            renderTarget.Transform = oldTransform;
        }
Exemplo n.º 45
0
        public static sd.Bitmap ToDx(this Image image, sd.RenderTarget target)
        {
            var handler = (ID2DBitmapHandler)image.Handler;

            return(target != null?handler.GetBitmap(target) : null);
        }
Exemplo n.º 46
0
 protected virtual sd.Bitmap CreateDrawableBitmap(sd.RenderTarget target)
 {
     return(sd.Bitmap.FromWicBitmap(target, Control));
 }
Exemplo n.º 47
0
        public static D2D.Brush ToD2DBrush(this Media.Brush brush, global::SharpDX.Vector2 renderSize, D2D.RenderTarget renderTarget)
        {
            if (brush == null)
            {
                return(null);
            }

            if (brush is Media.SolidColorBrush solid)
            {
                return(new D2D.SolidColorBrush(renderTarget, solid.Color.ToColor4()));
            }
            else if (brush is Media.LinearGradientBrush linear)
            {
                var brushProperties = new D2D.LinearGradientBrushProperties()
                {
                    StartPoint = linear.StartPoint.ToVector2(),
                    EndPoint   = linear.EndPoint.ToVector2()
                };

                if (linear.MappingMode == Media.BrushMappingMode.RelativeToBoundingBox)
                {
                    Point strtPoint = new Point(linear.StartPoint.X * renderSize.X, linear.StartPoint.Y * renderSize.Y);
                    Point endPoint  = new Point(linear.EndPoint.X * renderSize.X, linear.EndPoint.Y * renderSize.Y);
                    brushProperties.StartPoint = strtPoint.ToVector2();
                    brushProperties.EndPoint   = endPoint.ToVector2();
                }

                return(new D2D.LinearGradientBrush(renderTarget,
                                                   brushProperties,
                                                   new D2D.GradientStopCollection
                                                   (
                                                       renderTarget,
                                                       linear.GradientStops.Select(x => new D2D.GradientStop()
                {
                    Color = x.Color.ToColor4(), Position = (float)x.Offset
                }).ToArray(),
                                                       linear.ColorInterpolationMode.ToD2DColorInterpolationMode(),
                                                       linear.SpreadMethod.ToD2DExtendMode()
                                                   )
                                                   ));
            }
#if NETFX_CORE
#else
            else if (brush is Media.RadialGradientBrush radial)
            {
                var brushProperties = new D2D.RadialGradientBrushProperties()
                {
                    Center = radial.Center.ToVector2(),
                    GradientOriginOffset = radial.GradientOrigin.ToVector2(),
                    RadiusX = (float)radial.RadiusX,
                    RadiusY = (float)radial.RadiusY
                };

                if (radial.MappingMode == Media.BrushMappingMode.RelativeToBoundingBox)
                {
                    Point center = new Point(radial.Center.X * renderSize.X, radial.Center.Y * renderSize.Y);
                    Point gradientOriginOffset = new Point((radial.GradientOrigin.X - 0.5) * renderSize.X, (radial.GradientOrigin.Y - 0.5) * renderSize.Y);
                    brushProperties.Center = center.ToVector2();
                    brushProperties.GradientOriginOffset = gradientOriginOffset.ToVector2();
                    brushProperties.RadiusX = (float)(renderSize.X * radial.RadiusX);
                    brushProperties.RadiusY = (float)(renderSize.Y * radial.RadiusY);
                }

                return(new D2D.RadialGradientBrush(renderTarget,
                                                   brushProperties,
                                                   new D2D.GradientStopCollection
                                                   (
                                                       renderTarget,
                                                       radial.GradientStops.Select(x => new D2D.GradientStop()
                {
                    Color = x.Color.ToColor4(), Position = (float)x.Offset
                }).ToArray(),
                                                       radial.ColorInterpolationMode.ToD2DColorInterpolationMode(),
                                                       radial.SpreadMethod.ToD2DExtendMode()
                                                   )));
            }
#endif
            else
            {
                throw new NotImplementedException("Brush does not support yet.");
            }
        }
Exemplo n.º 48
0
        protected void InitializeDirectXResources()
        {
            ScaleFactor = (float)GraphicsUtils.Scale;

            var clientSize     = ClientSize;
            var backBufferDesc = new DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                          new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm);

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

            D3D11.Device.CreateWithSwapChain(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport,
                                             new[] { D3D.FeatureLevel.Level_10_0 }, swapChainDesc, out D3DDevice, out var swapChain);
            D3DDeviceContext = D3DDevice.ImmediateContext;

            SwapChain = new DXGI.SwapChain1(swapChain.NativePointer);

            D2DFactory = new D2D1.Factory();

            using (var backBuffer = SwapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, backBuffer);
                RenderTarget     = new D2D1.RenderTarget(D2DFactory, backBuffer.QueryInterface <DXGI.Surface>(),
                                                         new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype
                };
            }

            DwFactory = new DW.Factory(DW.FactoryType.Shared);

            _customColorRenderer.AssignResources(RenderTarget, ForegroundBrush);

            CueTextFormat = new DW.TextFormat(DwFactory, "Arial", DW.FontWeight.Bold,
                                              DW.FontStyle.Normal, DW.FontStretch.Normal, 120 * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            SubtitleTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Light,
                                                   DW.FontStyle.Normal, DW.FontStretch.Normal, Experiment.Config.Gui.InputTextFontSize * ScaleFactor / 2)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            ButtonLabelTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Bold,
                                                      DW.FontStyle.Normal, DW.FontStretch.Normal, Experiment.Config.Gui.ButtonFontSize * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Center,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };
            InputTextFormat = new DW.TextFormat(DwFactory, "Consolas", DW.FontWeight.Bold,
                                                DW.FontStyle.Normal, DW.FontStretch.Normal, Experiment.Config.Gui.InputTextFontSize * ScaleFactor)
            {
                TextAlignment      = DW.TextAlignment.Leading,
                ParagraphAlignment = DW.ParagraphAlignment.Center
            };

            SharedBrush       = new D2D1.SolidColorBrush(RenderTarget, Color.White);
            BackgroundBrush   = new D2D1.SolidColorBrush(RenderTarget, BackgroundColor);
            ForegroundBrush   = new D2D1.SolidColorBrush(RenderTarget, ForegroundColor);
            CorrectColorBrush = new D2D1.SolidColorBrush(RenderTarget, CorrectTextColor);
            WrongColorBrush   = new D2D1.SolidColorBrush(RenderTarget, WrongTextColor);

            PostInitDirectXResources();
        }
Exemplo n.º 49
0
 protected virtual void BeforeDraw(D2D1.RenderTarget renderTarget)
 {
 }
Exemplo n.º 50
0
        private void RenderInternal(D2D1.Factory factory, D2D1.RenderTarget rt, Map map,
                                    Envelope envelope, Rendering.Thematics.ITheme theme)
        {
            var ds = new FeatureDataSet();

            lock (_syncRoot)
            {
                DataSource.Open();
                DataSource.ExecuteIntersectionQuery(envelope, ds);
                DataSource.Close();
            }

            var scale = map.MapScale;
            var zoom  = map.Zoom;

            foreach (FeatureDataTable features in ds.Tables)
            {
                // Transform geometries if necessary
                if (CoordinateTransformation != null)
                {
                    for (var i = 0; i < features.Count; i++)
                    {
                        features[i].Geometry = ToTarget(features[i].Geometry);
                    }
                }

                //Linestring outlines is drawn by drawing the layer once with a thicker line
                //before drawing the "inline" on top.
                if (Style.EnableOutline)
                {
                    for (int i = 0; i < features.Count; i++)
                    {
                        var feature      = features[i];
                        var outlineStyle = theme.GetStyle(feature) as VectorStyle;
                        if (outlineStyle == null)
                        {
                            continue;
                        }
                        if (!(outlineStyle.Enabled && outlineStyle.EnableOutline))
                        {
                            continue;
                        }

                        double compare = outlineStyle.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;

                        if (!(outlineStyle.MinVisible <= compare && compare <= outlineStyle.MaxVisible))
                        {
                            continue;
                        }

                        using (var sdxStyle = SharpDXVectorStyle.FromVectorStyle(rt, factory, outlineStyle))
                        {
                            if (sdxStyle != null)
                            {
                                //Draw background of all line-outlines first
                                if (feature.Geometry is ILineString)
                                {
                                    SharpDXVectorRenderer.DrawLineString(rt, factory, (ILineString)feature.Geometry,
                                                                         sdxStyle.Outline, sdxStyle.OutlineWidth, sdxStyle.OutlineStrokeStyle,
                                                                         map, sdxStyle.LineOffset);
                                }
                                else if (feature.Geometry is IMultiLineString)
                                {
                                    SharpDXVectorRenderer.DrawMultiLineString(rt, factory, (IMultiLineString)feature.Geometry,
                                                                              sdxStyle.Outline, sdxStyle.OutlineWidth, sdxStyle.OutlineStrokeStyle,
                                                                              map, sdxStyle.LineOffset);
                                }
                            }
                        }
                    }
                }


                var sdxVectorStyles = new Dictionary <VectorStyle, SharpDXVectorStyle>();
                for (var i = 0; i < features.Count; i++)
                {
                    var feature = features[i];
                    var style   = theme.GetStyle(feature);
                    if (style == null)
                    {
                        continue;
                    }
                    if (!style.Enabled)
                    {
                        continue;
                    }

                    var compare = style.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;

                    if (!(style.MinVisible <= compare && compare <= style.MaxVisible))
                    {
                        continue;
                    }


                    IEnumerable <IStyle> stylesToRender = GetStylesToRender(style);

                    if (stylesToRender == null)
                    {
                        return;
                    }

                    foreach (var styleToRender in stylesToRender)
                    {
                        if (!styleToRender.Enabled)
                        {
                            continue;
                        }
                        if (!(styleToRender is VectorStyle))
                        {
                            continue;
                        }
                        if (!(style.MinVisible <= compare && compare <= style.MaxVisible))
                        {
                            continue;
                        }

                        var vstyle = (VectorStyle)styleToRender;
                        SharpDXVectorStyle sdxStyle;
                        if (!sdxVectorStyles.TryGetValue(vstyle, out sdxStyle))
                        {
                            sdxStyle = SharpDXVectorStyle.FromVectorStyle(rt, factory, vstyle);
                            sdxVectorStyles.Add(vstyle, sdxStyle);
                        }

                        RenderGeometry(factory, rt, map, feature.Geometry, sdxStyle);
                    }
                }

                foreach (var value in sdxVectorStyles.Values)
                {
                    value.Dispose();
                }
            }
        }
Exemplo n.º 51
0
 public override OptionalDispose <Bitmap> GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget target)
 {
     return(new OptionalDispose <Bitmap>(_direct2D, false));
 }
Exemplo n.º 52
0
 public LinearBrush(D2D1.RenderTarget render, D2D1.LinearGradientBrushProperties radial,
                    D2D1.GradientStopCollection g) : base(render, radial, g)
 {
     RawStart = radial.StartPoint;
     RawEnd   = radial.EndPoint;
 }
Exemplo n.º 53
0
 /// <summary>
 /// Converts a pen to a Direct2D stroke style.
 /// </summary>
 /// <param name="pen">The pen to convert.</param>
 /// <param name="renderTarget">The render target.</param>
 /// <returns>The Direct2D brush.</returns>
 public static StrokeStyle ToDirect2DStrokeStyle(this Avalonia.Media.IPen pen, SharpDX.Direct2D1.RenderTarget renderTarget)
 {
     return(pen.ToDirect2DStrokeStyle(renderTarget.Factory));
 }
            public void Init(Output output, GDI.Rectangle srcRect)
            {
                logger.Debug("DesktopDuplicator::Init(...) " + srcRect.ToString());

                try
                {
                    var          descr      = output.Description;
                    RawRectangle screenRect = descr.DesktopBounds;
                    int          width      = screenRect.Right - screenRect.Left;
                    int          height     = screenRect.Bottom - screenRect.Top;

                    SetupRegions(screenRect, srcRect);


                    if (descr.DeviceName == "\\\\.\\DISPLAY1")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 1920,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }
                    else if (descr.DeviceName == "\\\\.\\DISPLAY2")
                    {
                        drawRect = new Rectangle
                        {
                            X      = 0,
                            Y      = 0,
                            Width  = width,
                            Height = height,
                        };
                    }

                    screenTexture = new Texture2D(device,
                                                  new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.None,
                        BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = width,
                        Height            = height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Default,

                        OptionFlags = ResourceOptionFlags.Shared,
                    });

                    using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded))
                    {
                        using (var surf = screenTexture.QueryInterface <Surface>())
                        {
                            var pixelFormat       = new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied);
                            var renderTargetProps = new Direct2D.RenderTargetProperties(pixelFormat);
                            screenTarget = new Direct2D.RenderTarget(factory2D1, surf, renderTargetProps);
                        }
                    }

                    using (var output1 = output.QueryInterface <Output1>())
                    {
                        // Duplicate the output
                        deskDupl = output1.DuplicateOutput(device);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    Close();

                    throw;
                }

                deviceReady = true;
            }
            private unsafe void DrawCursor(SharpDX.Direct2D1.RenderTarget renderTarger, CursorInfo cursor)
            {
                var position = cursor.Position;

                var shapeBuff = cursor.PtrShapeBuffer;
                var shapeInfo = cursor.ShapeInfo;

                int width  = shapeInfo.Width;
                int height = shapeInfo.Height;
                int pitch  = shapeInfo.Pitch;

                int left   = position.X;
                int top    = position.Y;
                int right  = position.X + width;
                int bottom = position.Y + height;

                //logger.Debug(left + " " + top + " " + right + " " + bottom);

                if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    var data       = new DataPointer(shapeBuff, height * pitch);
                    var prop       = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                    var size       = new Size2(width, height);
                    var cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                    try
                    {
                        var cursorRect = new RawRectangleF(left, top, right, bottom);

                        renderTarger.DrawBitmap(cursorBits, cursorRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                    }
                    finally
                    {
                        cursorBits?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME)
                {
                    height = height / 2;

                    left   = position.X;
                    top    = position.Y;
                    right  = position.X + width;
                    bottom = position.Y + height;
                    pitch  = width * 4;

                    Texture2D desktopRegionTex = null;
                    try
                    {
                        desktopRegionTex = new Texture2D(device,
                                                         new Texture2DDescription
                        {
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            BindFlags         = BindFlags.None,
                            Format            = Format.B8G8R8A8_UNorm,
                            Width             = width,
                            Height            = height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = ResourceUsage.Staging,
                            OptionFlags       = ResourceOptionFlags.None,
                        });

                        var region           = new ResourceRegion(left, top, 0, right, bottom, 1);
                        var immediateContext = device.ImmediateContext;
                        immediateContext.CopySubresourceRegion(screenTexture, 0, region, desktopRegionTex, 0);

                        var dataBox = immediateContext.MapSubresource(desktopRegionTex, 0, MapMode.Read, MapFlags.None);
                        try
                        {
                            var desktopBuffer = new byte[width * height * 4];
                            Marshal.Copy(dataBox.DataPointer, desktopBuffer, 0, desktopBuffer.Length);

                            var shapeBufferLenght = width * height * 4;
                            var shapeBuffer       = new byte[shapeBufferLenght];

                            var maskBufferLenght = width * height / 8;
                            var andMaskBuffer    = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff, andMaskBuffer, 0, andMaskBuffer.Length);

                            var xorMaskBuffer = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff + andMaskBuffer.Length, xorMaskBuffer, 0, xorMaskBuffer.Length);

                            for (var row = 0; row < height; ++row)
                            {
                                byte mask = 0x80;

                                for (var col = 0; col < width; ++col)
                                {
                                    var maskIndex = row * width / 8 + col / 8;

                                    var andMask = ((andMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;
                                    var xorMask = ((xorMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;

                                    int pos = row * width * 4 + col * 4;
                                    for (int i = 0; i < 3; i++)
                                    {// RGB
                                        shapeBuffer[pos] = (byte)((desktopBuffer[pos] & andMask) ^ xorMask);
                                        pos++;
                                    }
                                    // Alpha
                                    shapeBuffer[pos] = (byte)((desktopBuffer[pos] & 0xFF) ^ 0);

                                    if (mask == 0x01)
                                    {
                                        mask = 0x80;
                                    }
                                    else
                                    {
                                        mask = (byte)(mask >> 1);
                                    }
                                }
                            }


                            Direct2D.Bitmap cursorBits = null;
                            try
                            {
                                fixed(byte *ptr = shapeBuffer)
                                {
                                    var data = new DataPointer(ptr, height * pitch);
                                    var prop = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                                    var size = new Size2(width, height);

                                    cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                                };

                                var shapeRect = new RawRectangleF(left, top, right, bottom);

                                renderTarger.DrawBitmap(cursorBits, shapeRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                            }
                            finally
                            {
                                cursorBits?.Dispose();
                            }
                        }
                        finally
                        {
                            immediateContext.UnmapSubresource(desktopRegionTex, 0);
                        }
                    }
                    finally
                    {
                        desktopRegionTex?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    logger.Warn("Not supported cursor type " + ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR);
                }
            }
Exemplo n.º 56
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 根据 [Surface sharing between Windows graphics APIs - Win32 apps](https://docs.microsoft.com/en-us/windows/win32/direct3darticles/surface-sharing-between-windows-graphics-apis?WT.mc_id=WD-MVP-5003260 ) 文档

            var width  = ImageWidth;
            var height = ImageHeight;

            // 2021.12.23 不能在 x86 下运行,会炸掉。参阅 https://github.com/dotnet/Silk.NET/issues/731

            var texture2DDesc = new D3D11.Texture2DDesc()
            {
                BindFlags  = (uint)(D3D11.BindFlag.BindRenderTarget | D3D11.BindFlag.BindShaderResource),
                Format     = DXGI.Format.FormatB8G8R8A8Unorm, // 最好使用此格式,否则还需要后续转换
                Width      = (uint)width,
                Height     = (uint)height,
                MipLevels  = 1,
                SampleDesc = new DXGI.SampleDesc(1, 0),
                Usage      = D3D11.Usage.UsageDefault,
                MiscFlags  = (uint)D3D11.ResourceMiscFlag.ResourceMiscShared,
                // The D3D11_RESOURCE_MISC_FLAG cannot be used when creating resources with D3D11_CPU_ACCESS flags.
                CPUAccessFlags = 0, //(uint) D3D11.CpuAccessFlag.None,
                ArraySize      = 1
            };

            D3D11.ID3D11Device *       pD3D11Device;
            D3D11.ID3D11DeviceContext *pD3D11DeviceContext;
            D3DFeatureLevel            pD3DFeatureLevel = default;

            D3D11.D3D11 d3D11 = D3D11.D3D11.GetApi();

            var hr = d3D11.CreateDevice((DXGI.IDXGIAdapter *)IntPtr.Zero, D3DDriverType.D3DDriverTypeHardware,
                                        Software: 0,
                                        Flags: (uint)D3D11.CreateDeviceFlag.CreateDeviceBgraSupport,
                                        (D3DFeatureLevel *)IntPtr.Zero,
                                        FeatureLevels: 0,                        // D3DFeatureLevel 的长度
                                        SDKVersion: 7,
                                        (D3D11.ID3D11Device * *) & pD3D11Device, // 参阅 [C# 从零开始写 SharpDx 应用 聊聊功能等级](https://blog.lindexi.com/post/C-%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%86%99-SharpDx-%E5%BA%94%E7%94%A8-%E8%81%8A%E8%81%8A%E5%8A%9F%E8%83%BD%E7%AD%89%E7%BA%A7.html )
                                        ref pD3DFeatureLevel,
                                        (D3D11.ID3D11DeviceContext * *) & pD3D11DeviceContext
                                        );

            SilkMarshal.ThrowHResult(hr);

            Debugger.Launch();
            Debugger.Break();

            _pD3D11Device        = pD3D11Device;
            _pD3D11DeviceContext = pD3D11DeviceContext;

            D3D11.ID3D11Texture2D *pD3D11Texture2D;
            hr = pD3D11Device->CreateTexture2D(ref texture2DDesc, (D3D11.SubresourceData *)IntPtr.Zero, &pD3D11Texture2D);
            SilkMarshal.ThrowHResult(hr);

            var renderTarget = pD3D11Texture2D;

            _pD3D11Texture2D = pD3D11Texture2D;

            DXGI.IDXGISurface *pDXGISurface;
            var dxgiSurfaceGuid = DXGI.IDXGISurface.Guid;

            renderTarget->QueryInterface(ref dxgiSurfaceGuid, (void **)&pDXGISurface);
            _pDXGISurface = pDXGISurface;

            var d2DFactory = new D2D.Factory();

            var renderTargetProperties =
                new D2D.RenderTargetProperties(new D2D.PixelFormat(SharpDXDXGI.Format.Unknown, D2D.AlphaMode.Premultiplied));
            var surface = new SharpDXDXGI.Surface(new IntPtr((void *)pDXGISurface));

            _d2DRenderTarget = new D2D.RenderTarget(d2DFactory, surface, renderTargetProperties);

            SetRenderTarget(renderTarget);

            var viewport = new D3D11.Viewport(0, 0, width, height, 0, 1);

            pD3D11DeviceContext->RSSetViewports(NumViewports: 1, ref viewport);

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
Exemplo n.º 57
0
        private void RenderGeometry(D2D1.Factory factory, D2D1.RenderTarget g, Map map, IGeometry feature, SharpDXVectorStyle style)
        {
            if (feature == null)
            {
                return;
            }

            var geometryType = feature.OgcGeometryType;

            switch (geometryType)
            {
            case OgcGeometryType.Polygon:
                if (style.EnableOutline)
                {
                    SharpDXVectorRenderer.DrawPolygon(g, factory, (IPolygon)feature, style.Fill, style.Outline, style.OutlineWidth, style.OutlineStrokeStyle, ClippingEnabled, map);
                }
                else
                {
                    SharpDXVectorRenderer.DrawPolygon(g, factory, (IPolygon)feature, style.Fill, null, 0f, null, ClippingEnabled, map);
                }
                break;

            case OgcGeometryType.MultiPolygon:
                if (style.EnableOutline)
                {
                    SharpDXVectorRenderer.DrawMultiPolygon(g, factory, (IMultiPolygon)feature, style.Fill, style.Outline, style.OutlineWidth, style.OutlineStrokeStyle,
                                                           ClippingEnabled, map);
                }
                else
                {
                    SharpDXVectorRenderer.DrawMultiPolygon(g, factory, (IMultiPolygon)feature, style.Fill, null, 0f, null, ClippingEnabled,
                                                           map);
                }
                break;

            case OgcGeometryType.LineString:
                SharpDXVectorRenderer.DrawLineString(g, factory, (ILineString)feature, style.Line, style.LineWidth, style.LineStrokeStyle, map, style.LineOffset);
                return;

            case OgcGeometryType.MultiLineString:
                SharpDXVectorRenderer.DrawMultiLineString(g, factory, (IMultiLineString)feature, style.Line, style.LineWidth, style.LineStrokeStyle, map, style.LineOffset);
                break;

            case OgcGeometryType.Point:
                if (style.Symbol != null || style.PointColor == null)
                {
                    SharpDXVectorRenderer.DrawPoint(g, factory, (IPoint)feature, style.Symbol, style.SymbolOffset,
                                                    style.SymbolRotation, map);
                    return;
                }
                SharpDXVectorRenderer.DrawPoint(g, factory, (IPoint)feature, style.PointColor, style.PointSize, style.SymbolOffset, map);

                break;

            case OgcGeometryType.MultiPoint:
                if (style.Symbol != null || style.PointColor == null)
                {
                    SharpDXVectorRenderer.DrawMultiPoint(g, factory, (IMultiPoint)feature, style.Symbol,
                                                         style.SymbolOffset, style.SymbolRotation, map);
                }
                else
                {
                    SharpDXVectorRenderer.DrawMultiPoint(g, factory, (IMultiPoint)feature, style.PointColor, style.PointSize, style.SymbolOffset, map);
                }
                break;

            case OgcGeometryType.GeometryCollection:
                var coll = (IGeometryCollection)feature;
                for (var i = 0; i < coll.NumGeometries; i++)
                {
                    IGeometry geom = coll[i];
                    RenderGeometry(factory, g, map, geom, style);
                }
                break;

            default:
                lock (_syncRoot)
                    _logger.Debug(fmh => fmh("Unhandled geometry: {0}", feature.OgcGeometryType));
                break;
            }
        }
 protected void Initialize(D2D1.RenderTarget renderTarget)
 {
     this.renderTarget = renderTarget;
     renderTarget.BeginDraw();
 }
Exemplo n.º 59
0
        public void OnResize(int width, int height)
        {
            if (mRealTexture != null)
            {
                mRealTexture.Dispose();
            }
            if (mTmpTexture != null)
            {
                mTmpTexture.Dispose();
            }

            mRealTexture = new SharpDX.Direct3D11.Texture2D(mDevice.Device, new SharpDX.Direct3D11.Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Height            = height,
                Width             = width,
                MipLevels         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default
            });

            using (var resource = mRealTexture.QueryInterface <SharpDX.DXGI.Resource>())
                mTmpTexture = D2DDevice.OpenSharedResource <Texture2D>(resource.SharedHandle);

            if (NativeView != null)
            {
                NativeView.Dispose();
            }
            NativeView = new SharpDX.Direct3D11.ShaderResourceView(mDevice.Device, mRealTexture,
                                                                   new SharpDX.Direct3D11.ShaderResourceViewDescription
            {
                Format    = Format.B8G8R8A8_UNorm,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            });

            if (RenderTarget != null)
            {
                RenderTarget.Dispose();
            }
            using (var surface = mTmpTexture.QueryInterface <Surface>())
                RenderTarget = new RenderTarget(Direct2DFactory, surface, new RenderTargetProperties()
                {
                    DpiX        = 0.0f,
                    DpiY        = 0.0f,
                    MinLevel    = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT,
                    PixelFormat = new PixelFormat()
                    {
                        AlphaMode = AlphaMode.Premultiplied, Format = Format.Unknown
                    },
                    Type  = RenderTargetType.Hardware,
                    Usage = RenderTargetUsage.None
                });

            if (mMutex10 != null)
            {
                mMutex10.Dispose();
            }
            if (mMutex11 != null)
            {
                mMutex11.Dispose();
            }

            mMutex10 = mTmpTexture.QueryInterface <KeyedMutex>();
            mMutex11 = mRealTexture.QueryInterface <KeyedMutex>();

            Brushes.Initialize(RenderTarget);
            Fonts.Initialize(DirectWriteFactory);

            Button.Initialize();
            Frame.Initialize();

            // right now the texture is unowned and only a key of 0 will succeed.
            // after releasing it with a specific key said key then can be used for
            // further locking.
            mMutex10.Acquire(0, -1);
            mMutex10.Release(Key11);
        }
Exemplo n.º 60
0
 public D2DSolidBrush(SharpDX.Direct2D1.RenderTarget target, Color color)
 {
     NativeBrush = new SolidColorBrush(target, color.ToRC4());
 }