Пример #1
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>
        ///		指定したレンダーターゲットに対して描画処理をバッチ実行する。
        /// </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 したらリストから削除。
                }
            }
        }
        public void RenderTextOffscreen(string text)
        {
            // Clear the off-screen render target.
            deviceResources.D3DDeviceContext.ClearRenderTargetView(renderTargetView, new RawColor4(0f, 0f, 0f, 0f));

            // Begin drawing with D2D.
            d2dRenderTarget.BeginDraw();

            // Create a text layout to match the screen.
            SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(deviceResources.DWriteFactory, text, textFormat, textureWidth, textureHeight);

            // Get the text metrics from the text layout.
            SharpDX.DirectWrite.TextMetrics metrics = textLayout.Metrics;

            // In this example, we position the text in the center of the off-screen render target.
            Matrix3x2 screenTranslation = Matrix3x2.CreateTranslation(
                textureWidth * 0.5f,
                textureHeight * 0.5f + metrics.Height * 0.5f
                );

            whiteBrush.Transform = screenTranslation.ToRawMatrix3x2();

            // Render the text using DirectWrite.
            d2dRenderTarget.DrawTextLayout(new RawVector2(), textLayout, whiteBrush);

            // End drawing with D2D.
            d2dRenderTarget.EndDraw();
        }
Пример #4
0
 public void EndDraw()
 {
     if (_inRender)
     {
         lock (_lock)
         {
             d2dRenderTarget.EndDraw();
             _inRender = false;
         }
     }
 }
Пример #5
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);
        }
Пример #6
0
        private ErrorCode CopyGdiScreenToDxSurf()
        {
            ErrorCode errorCode = ErrorCode.Unexpected;

            try
            {
                if (hWnd != IntPtr.Zero)
                {
                    var isIconic = User32.IsIconic(hWnd);
                    if (!isIconic)
                    {
                        var clientRect = User32.GetClientRect(hWnd);

                        if (this.SrcRect != clientRect)
                        {
                            logger.Info(SrcRect.ToString());

                            this.SrcRect = clientRect;

                            if (gdiTexture != null)
                            {
                                gdiTexture.Dispose();
                                gdiTexture = null;
                            }
                        }
                    }
                    else
                    {
                        logger.Debug("IsIconic: " + hWnd);
                        return(ErrorCode.Ok);
                    }

                    var srcWidth  = SrcRect.Width;
                    var srcHeight = SrcRect.Height;

                    if (srcWidth == 0 || srcHeight == 0)
                    {
                        logger.Error("Invalid rect: " + SrcRect.ToString());
                        return(ErrorCode.Unexpected);
                    }

                    if (gdiTexture == null)
                    {
                        gdiTexture = new Texture2D(device,
                                                   new Texture2DDescription
                        {
                            CpuAccessFlags    = CpuAccessFlags.None,
                            BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                            Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                            Width             = SrcRect.Width,
                            Height            = SrcRect.Height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = ResourceUsage.Default,
                            OptionFlags       = ResourceOptionFlags.GdiCompatible,
                        });
                    }
                }



                using (var surf = gdiTexture.QueryInterface <SharpDX.DXGI.Surface1>())
                {
                    int nXSrc      = SrcRect.Left;
                    int nYSrc      = SrcRect.Top;
                    int nWidthSrc  = SrcRect.Width;
                    int nHeightSrc = SrcRect.Height;

                    var descr = surf.Description;

                    int nXDest  = 0;
                    int nYDest  = 0;
                    int nWidth  = descr.Width;
                    int nHeight = descr.Height;

                    try
                    {
                        var    hdcDest = surf.GetDC(true);
                        IntPtr hdcSrc  = IntPtr.Zero;
                        try
                        {
                            hdcSrc = User32.GetDC(hWnd);
                            //hdcSrc = User32.GetDC(IntPtr.Zero);
                            //hdcSrc = User32.GetWindowDC(hWnd);

                            var dwRop = TernaryRasterOperations.SRCCOPY;
                            if (CaptureAllLayers)
                            {
                                dwRop |= TernaryRasterOperations.CAPTUREBLT;
                            }

                            //var dwRop = TernaryRasterOperations.CAPTUREBLT | TernaryRasterOperations.SRCCOPY;
                            //var dwRop = TernaryRasterOperations.SRCCOPY;

                            //bool success = User32.PrintWindow(hWnd, hdcDest, 0);

                            bool success = Gdi32.BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, dwRop);
                            if (!success)
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }

                            if (CaptureMouse)
                            {
                                var x = nXSrc;
                                var y = nYSrc;

                                if (hWnd != IntPtr.Zero)
                                {
                                    POINT lpPoint = new POINT
                                    {
                                        x = 0,
                                        y = 0,
                                    };

                                    User32.ClientToScreen(hWnd, ref lpPoint);

                                    x = lpPoint.x;
                                    y = lpPoint.y;
                                }

                                User32.DrawCursorEx(hdcDest, x, y);
                            }

                            errorCode = ErrorCode.Ok;
                        }
                        finally
                        {
                            Gdi32.DeleteDC(hdcSrc);
                        }
                    }
                    catch (Win32Exception ex)
                    {
                        logger.Warn(ex);

                        if (ex.NativeErrorCode == Win32ErrorCodes.ERROR_ACCESS_DENIED ||
                            ex.NativeErrorCode == Win32ErrorCodes.ERROR_INVALID_HANDLE)
                        {
                            errorCode = ErrorCode.AccessDenied;
                        }
                    }
                    finally
                    {
                        surf.ReleaseDC();
                    }
                }

                if (errorCode == ErrorCode.Ok)
                {
                    Texture2D finalTexture = gdiTexture;
                    if (renderTarget != null)
                    {                                            // масштабируем текстуру если нужно
                        renderTarget.BeginDraw();
                        renderTarget.Clear(SharpDX.Color.Black); //(Color.Red);

                        DrawTexture(renderTarget, gdiTexture);

                        renderTarget.EndDraw();
                        finalTexture = renderTexture;
                    }

                    //device.ImmediateContext.CopySubresourceRegion(finalTexture, SharedTexture);

                    device.ImmediateContext.CopyResource(finalTexture, SharedTexture);
                    device.ImmediateContext.Flush();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(errorCode);
        }
Пример #7
0
        private void OnRender()
        {
            lock (_renderContextLock)
            {
                if (_renderTarget?.IsDisposed ?? true)
                {
                    return;
                }

                _renderTarget.BeginDraw();
                _renderTarget.Clear(_backgroundColor);

                if (_experimentStarted) // Draw blocks
                {
                    var secsPassed = (CurrentTime - _stageUpdatedAt) / 1000.0;
                    switch (_paradigm)
                    {
                    case SsvepExperiment.Configuration.TestConfig.StimulationParadigm.Flicker:
                        foreach (var block in _blocks)
                        {
                            if (block.BorderWidth > 0)
                            {
                                _solidColorBrush.Color = _blockBorderColor;
                                _renderTarget.FillRectangle(block.BorderRect, _solidColorBrush);
                            }
                            if (!_trialStarted || block.Patterns == null)
                            {
                                _solidColorBrush.Color = _blockNormalColor;
                            }
                            else
                            {
                                _solidColorBrush.Color = Color.SmoothStep(_blockNormalColor, _blockFlashingColor,
                                                                          (float)ConvertCosineValueToGrayScale(block.Patterns[0].Sample(secsPassed)));
                            }
                            _renderTarget.FillRectangle(block.ContentRect, _solidColorBrush);

                            if (block.FixationPointSize > 0)
                            {
                                _solidColorBrush.Color = _blockFixationPointColor;
                                _renderTarget.FillEllipse(block.CenterPointEllipse, _solidColorBrush);
                            }
                        }
                        break;

                    case SsvepExperiment.Configuration.TestConfig.StimulationParadigm.DualFlickers:
                        foreach (var block in _blocks)
                        {
                            if (block.BorderWidth > 0)
                            {
                                _solidColorBrush.Color = _blockBorderColor;
                                _renderTarget.FillRectangle(block.BorderRect, _solidColorBrush);
                            }

                            for (var i = 0; i < block.DualFlickerRects.Length; i++)
                            {
                                if (!_trialStarted || block.Patterns == null)
                                {
                                    _solidColorBrush.Color = _blockNormalColor;
                                }
                                else
                                {
                                    _solidColorBrush.Color = Color.SmoothStep(_blockNormalColor, _blockFlashingColor,
                                                                              (float)ConvertCosineValueToGrayScale(block.Patterns[i].Sample(secsPassed)));
                                }
                                _renderTarget.FillRectangle(block.DualFlickerRects[i], _solidColorBrush);
                            }

                            if (block.FixationPointSize > 0)
                            {
                                _solidColorBrush.Color = _blockFixationPointColor;
                                _renderTarget.FillEllipse(block.CenterPointEllipse, _solidColorBrush);
                            }
                        }
                        break;
                    }
                }
                else if (!(_displayText?.IsBlank() ?? true)) // Draw text
                {
                    _solidColorBrush.Color = _fontColor;
                    _renderTarget.DrawText(_displayText, _textFormat, new RawRectangleF(0, 0, Width, Height),
                                           _solidColorBrush, SharpDX.Direct2D1.DrawTextOptions.None);
                }

                _renderTarget.EndDraw();

                _swapChain.Present(1, SharpDX.DXGI.PresentFlags.None, _presentParameters);
            }
        }
Пример #8
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);
        }