示例#1
0
        // Draw to the CanvasSwapChain.
        void DrawToSwapChain(Size size)
        {
            if (size.Width <= 0 || size.Height <= 0)
            {
                swapChain = null;
                swapChainPanel.SwapChain = null;
                return;
            }
            else if (swapChain == null)
            {
                swapChain = new CanvasSwapChain(canvasControl, (float)size.Width, (float)size.Height);
                swapChainPanel.SwapChain = swapChain;
            }
            else
            {
                swapChain.ResizeBuffers((float)size.Width, (float)size.Height);
            }

            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                Draw(ds, "Canvas\nSwap\nChain", size);
            }

            swapChain.Present();
        }
示例#2
0
        public void StartCaptureInternal(GraphicsCaptureItem item)
        {
            StopCapture();
            _item      = item;
            _lastSize  = _item.Size;
            _swapChain = new CanvasSwapChain(_canvasDevice, _item.Size.Width, _item.Size.Height, 96);

            swapChain.SwapChain = _swapChain;

            _framePool = Direct3D11CaptureFramePool.Create(
                _canvasDevice,                             // D3D device
                DirectXPixelFormat.B8G8R8A8UIntNormalized, // Pixel format
                60,                                        // Number of frames
                _item.Size);                               // Size of the buffers
            _session = _framePool.CreateCaptureSession(_item);
            _framePool.FrameArrived += (s, a) =>
            {
                using (var frame = _framePool.TryGetNextFrame())
                {
                    ProcessFrame(frame);
                }
            };
            _item.Closed += (s, a) =>
            {
                StopCapture();
            };
            _session.StartCapture();
        }
        private void DrawSwapChain(CanvasSwapChain swapChain, bool isPaused)
        {
            ++DrawCount;

            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                var size   = swapChain.Size.ToVector2();
                var radius = (Math.Min(size.X, size.Y) / 2f) - 4f;

                var center = size / 2;

                ds.FillCircle(center, radius, Colors.LightGoldenrodYellow);
                ds.DrawCircle(center, radius, Colors.LightGray);

                double mu = (-DrawCount / 50f);

                for (int i = 0; i < 16; i++)
                {
                    double a = mu + (i / 16f) * Math.PI * 2;
                    var    x = (float)Math.Sin(a);
                    var    y = (float)Math.Cos(a);
                    ds.DrawLine(center, center + new Vector2(x, y) * radius, Colors.Black, 5);
                }

                var rectLenght = Math.Sqrt(radius * radius * 2);

                ds.FillCircle(center, (float)rectLenght / 2, Colors.LightGoldenrodYellow);

                var rect = new Rect(center.X - rectLenght / 2, center.Y - rectLenght / 2, rectLenght, rectLenght);
            }
            SwapChain.Present();
        }
示例#4
0
        private void CreatePanelSizeDependentResources()
        {
            _panelWidth  = (float)layoutPanel.ActualWidth;
            _panelHeight = (float)layoutPanel.ActualHeight;

            // Regardless of display AC type, use the same render code.
            DirectXPixelFormat fmt = DirectXPixelFormat.R16G16B16A16Float;
            int numBuffers         = 2;

            if (_swapChain == null)
            {
                _swapChain = new CanvasSwapChain(
                    _device,
                    _panelWidth,
                    _panelHeight,
                    _dispInfo.LogicalDpi,
                    fmt,
                    numBuffers,
                    CanvasAlphaMode.Ignore);
            }
            else
            {
                _swapChain.ResizeBuffers(
                    _panelWidth,
                    _panelHeight,
                    _dispInfo.LogicalDpi,
                    fmt,
                    numBuffers);
            }

            swapChainPanel.SwapChain = _swapChain;
        }
示例#5
0
        void DrawSwapChain(CanvasSwapChain swapChain)
        {
            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                var size   = swapChain.Size.ToVector2();
                var radius = (Math.Min(size.X, size.Y) / 2.0f) - 4.0f;

                var center = size / 2;

                float fillRadius = radius;

                // yuck
                lock (PassthroughEffect.GetBadLock())
                {
                    if (PlayerService.Current.ReferencePropertySet != null &&
                        PlayerService.Current.ReferencePropertySet.ContainsKey("InputDataRaw"))
                    {
                        fillRadius *= (float)PlayerService.Current.ReferencePropertySet["InputDataRaw"];
                    }
                }

                ds.FillCircle(center, fillRadius, Colors.LightGoldenrodYellow);
                ds.DrawCircle(center, radius, Colors.LightGray);
            }

            swapChain.Present();
        }
示例#6
0
        private void CreateResources(Size sizeSwapchain)
        {
            _device    = new CanvasDevice();
            _swapchain = new CanvasSwapChain(_device, (float)sizeSwapchain.Width, (float)sizeSwapchain.Height, 96);

            // Start rendering the swapchain
            StartRendering(sizeSwapchain);
        }
示例#7
0
 private async Task InitShapChain(int width, int height)
 {
     await Dispatcher.TryRunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         swapChain = new CanvasSwapChain(device, width, height, dpi);
         SwapChainPanel.SwapChain = swapChain;
     });
 }
        private void CreateResources(Size sizeSwapchain)
        {
            _device = new CanvasDevice();
            _swapchain = new CanvasSwapChain(_device, (float)sizeSwapchain.Width, (float)sizeSwapchain.Height, 96);

            // Start rendering the swapchain
            StartRendering(sizeSwapchain);
        }
示例#9
0
        public void EnsureMatchesWindow(CoreWindow window)
        {
            var   bounds     = window.Bounds;
            Size  windowSize = new Size(bounds.Width, bounds.Height);
            float dpi        = DisplayInformation.GetForCurrentView().LogicalDpi;

            if (dpi != SwapChain.Dpi)
            {
                // If the DPI changes then we need to recreate the swapchain
                // TODO: #3905 should ResizeBuffers change the DPI as well as the size?
                var device = SwapChain.Device;
                SwapChain.Dispose();
                SwapChain = CanvasSwapChain.CreateForCoreWindow(device, window, dpi);
            }
            else if (!SizeEqualsWithTolerance(windowSize, SwapChain.Size))
            {
                // Note: swapchain size & window size may not be exactly equal since they are represented with
                // floating point numbers and are calculated via different code paths.
#if WINDOWS_PHONE_APP
                // Windows Phone does not support ResizeBuffers for CoreWindow swap chains
                //
                var device = SwapChain.Device;
                SwapChain.Dispose();
                SwapChain = CanvasSwapChain.CreateForCoreWindow(device, window, dpi);
#else
                SwapChain.ResizeBuffers((float)windowSize.Width, (float)windowSize.Height);
#endif
            }

#if WINDOWS_PHONE_APP
            var orientation = DisplayInformation.GetForCurrentView().CurrentOrientation;
            CanvasSwapChainRotation rotation = CanvasSwapChainRotation.None;

            switch (orientation)
            {
            case DisplayOrientations.Portrait:
                rotation = CanvasSwapChainRotation.None;
                break;

            case DisplayOrientations.Landscape:
                rotation = CanvasSwapChainRotation.Rotate270;
                break;

            case DisplayOrientations.LandscapeFlipped:
                rotation = CanvasSwapChainRotation.Rotate90;
                break;

            case DisplayOrientations.PortraitFlipped:
                rotation = CanvasSwapChainRotation.Rotate180;
                break;
            }

            if (SwapChain.Rotation != rotation)
            {
                SwapChain.Rotation = rotation;
            }
#endif
        }
示例#10
0
        void DrawSwapChain(CanvasSwapChain swapChain, bool isPaused)
        {
            ++drawCount;

            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                var size   = swapChain.Size.ToVector2();
                var radius = (Math.Min(size.X, size.Y) / 2.0f) - 4.0f;

                var center = size / 2;

                ds.FillCircle(center, radius, Colors.LightGoldenrodYellow);
                ds.DrawCircle(center, radius, Colors.LightGray);

                double mu = (-drawCount / 50.0f);

                for (int i = 0; i < 16; ++i)
                {
                    double a = mu + (i / 16.0) * Math.PI * 2;
                    var    x = (float)Math.Sin(a);
                    var    y = (float)Math.Cos(a);
                    ds.DrawLine(center, center + new Vector2(x, y) * radius, Colors.Black, 5);
                }

                var rectLength = Math.Sqrt(radius * radius * 2);

                ds.FillCircle(center, (float)rectLength / 2, Colors.LightGoldenrodYellow);

                var rect = new Rect(center.X - rectLength / 2, center.Y - rectLength / 2, rectLength, rectLength);

                ds.DrawText("This is a swap chain",
                            rect,
                            Colors.Black,
                            new CanvasTextFormat()
                {
                    FontFamily          = "Comic Sans MS",
                    FontSize            = 24,
                    VerticalAlignment   = CanvasVerticalAlignment.Center,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center,
                    WordWrapping        = CanvasWordWrapping.WholeWord,
                });

                var label = string.Format("Draws: {0}\nDevices: {1}\nTap to {2}", drawCount, deviceCount, isPaused ? "unpause" : "pause");

                ds.DrawText(label, rect, Colors.Black, new CanvasTextFormat()
                {
                    FontSize            = 10,
                    VerticalAlignment   = CanvasVerticalAlignment.Bottom,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center
                });
            }

            swapChain.Present();
        }
示例#11
0
        public void CreateSwapChain()
        {
            CanvasDevice canvasDevice = ((CanvasDeviceAdapter)this.graphicsDeviceAdapter).CanvasDevice;
            var          coreWindow   = (CoreWindow)this.platformWindow.Window;

            float currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;

            this.canvasSwapChain = CanvasSwapChain.CreateForCoreWindow(canvasDevice, coreWindow, currentDpi);

            this.Target = this;
        }
示例#12
0
        public Renderer(CoreWindow window)
        {
            _window = window;

            _canvasDevice = new CanvasDevice();

            float dpi = DisplayInformation.GetForCurrentView().LogicalDpi;

            _swapChain = CanvasSwapChain.CreateForCoreWindow(_canvasDevice, window, dpi);

            _fps = new FPSCounter();
        }
示例#13
0
        public CanvasPresenter(Canvas canvas, CanvasDevice device)
        {
            var dpi = GraphicsInformation.Dpi;

            _device = device;
            _canvas = canvas;
            _canvas.RegisterPresenter(this);

            DrawBackgroundBrush();

            _swapChain = new CanvasSwapChain(_device, canvas.Size.X, canvas.Size.Y, dpi);
        }
示例#14
0
        void Canvas_CreateResources(CanvasControl sender, object args)
        {
            mainDeviceResources = new PerDeviceResources(sender);

            imageBrush = new CanvasImageBrush(sender);

            imageSource         = new CanvasImageSource(sender, controlSize, controlSize);
            imageControl.Source = imageSource;

            swapChain = new CanvasSwapChain(sender, controlSize, controlSize);
            swapChainPanel.SwapChain = swapChain;
        }
示例#15
0
        void SetDevice(CanvasDevice device, Size windowSize)
        {
            _drawLoopCancellationTokenSource?.Cancel();

            _swapChain             = new CanvasSwapChain(device, (float)this.ActualWidth, (float)this.ActualHeight, 96);
            _swapChainVisual.Brush = _compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(_compositor, _swapChain));

            _drawLoopCancellationTokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(
                DrawLoop,
                _drawLoopCancellationTokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
        }
示例#16
0
        void DrawSwapChain(CanvasSwapChain swapChain, bool isPaused)
        {
            ++drawCount;

            using (var ds = swapChain.CreateDrawingSession(Color.FromArgb(80, 0, 0, 0)))
            {
                ds.DrawText(Display, new Rect(0, 0, this.swapChain.Size.Width, this.swapChain.Size.Height), Colors.White, new CanvasTextFormat()
                {
                    FontSize            = 30,
                    VerticalAlignment   = CanvasVerticalAlignment.Center,
                    HorizontalAlignment = CanvasHorizontalAlignment.Left
                });
            }
        }
示例#17
0
        void Canvas_CreateResources(CanvasControl sender, CanvasCreateResourcesEventArgs args)
        {
            args.TrackAsyncAction(LoadCanvasResources(sender).AsAsyncAction());

            imageBrush = new CanvasImageBrush(sender);

            imageSource         = new CanvasImageSource(sender, controlSize, controlSize);
            imageControl.Source = imageSource;

            virtualImageSource         = new CanvasVirtualImageSource(sender, controlSize, controlSize);
            virtualImageControl.Source = virtualImageSource.Source;

            swapChain = new CanvasSwapChain(sender, controlSize, controlSize);
            swapChainPanel.SwapChain = swapChain;
        }
示例#18
0
        public void EnsureMatchesWindow(CoreWindow window)
        {
            var bounds = window.Bounds;
            Size windowSize = new Size(bounds.Width, bounds.Height);
            float dpi = DisplayInformation.GetForCurrentView().LogicalDpi;

            if (!SizeEqualsWithTolerance(windowSize, SwapChain.Size) || dpi != SwapChain.Dpi)
            {
                // Note: swapchain size & window size may not be exactly equal since they are represented with
                // floating point numbers and are calculated via different code paths.
#if WINDOWS_PHONE_APP
                // Windows Phone does not support ResizeBuffers for CoreWindow swap chains
                //
                var device = SwapChain.Device;
                SwapChain.Dispose();
                SwapChain = CanvasSwapChain.CreateForCoreWindow(device, window, dpi);
#else
                SwapChain.ResizeBuffers((float)windowSize.Width, (float)windowSize.Height, dpi);
#endif
            }

#if WINDOWS_PHONE_APP
            var orientation = DisplayInformation.GetForCurrentView().CurrentOrientation;
            CanvasSwapChainRotation rotation = CanvasSwapChainRotation.None;

            switch (orientation)
            {
                case DisplayOrientations.Portrait:
                    rotation = CanvasSwapChainRotation.None;
                    break;

                case DisplayOrientations.Landscape:
                    rotation = CanvasSwapChainRotation.Rotate270;
                    break;

                case DisplayOrientations.LandscapeFlipped:
                    rotation = CanvasSwapChainRotation.Rotate90;
                    break;

                case DisplayOrientations.PortraitFlipped:
                    rotation = CanvasSwapChainRotation.Rotate180;
                    break;
            }

            if (SwapChain.Rotation != rotation)
                SwapChain.Rotation = rotation;
#endif
        }
示例#19
0
        public void SetDevice(CanvasDevice device, Size windowSize)
        {
            ++deviceCount;

            drawLoopCancellationTokenSource?.Cancel();

            swapChain = new CanvasSwapChain(device, 256, 256, 96);
            swapChainVisual.Brush = compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(compositor, swapChain));

            drawLoopCancellationTokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(
                DrawLoop,
                drawLoopCancellationTokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
        }
示例#20
0
        public void SetDevice(CanvasDevice device, Size windowSize)
        {
            ++deviceCount;

            drawLoopCancellationTokenSource?.Cancel();

            swapChain             = new CanvasSwapChain(device, 256, 256, 96);
            swapChainVisual.Brush = compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(compositor, swapChain));

            drawLoopCancellationTokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(
                DrawLoop,
                drawLoopCancellationTokenSource.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
        }
示例#21
0
        public SimpleCapture(CanvasDevice device, GraphicsCaptureItem item, SizeInt32 size)
        {
            _item   = item;
            _device = device;

            // TODO: Dpi?
            _swapChain = new CanvasSwapChain(_device, size.Width, size.Height, 96);

            _framePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
                _device,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                2,
                size);
            _session = _framePool.CreateCaptureSession(item);

            _framePool.FrameArrived += OnFrameArrived;
        }
示例#22
0
        private async void CanvasCreateResources(object o, RoutedEventArgs routedEventArgs)
        {
            // initialize current displayinfo
            UpdateDisplayInfo();
            DisplayInformation.DisplayContentsInvalidated += DisplayInformation_DisplayContentsInvalidated;
            // create swapchain
            var swapChain = new CanvasSwapChain(CanvasDevice.GetSharedDevice(), (float)CanvasWidth, (float)CanvasHeight, 96);

            _canvas.SwapChain = swapChain;
            // create back buffer
            _buffer    = CanvasRenderTargetExtension.CreateEmpty(_canvas, new Size(CanvasWidth, CanvasHeight));
            _tmpBuffer = CanvasRenderTargetExtension.CreateEmpty(_canvas, new Size(CanvasWidth, CanvasHeight));
            // create default layer
            AddLayer();
            _background = await CanvasBitmap.LoadAsync(_canvas.SwapChain, new Uri("ms-appx:///PaintCanvas/Assets/canvas.png"));

            //_canvas.Invalidate();
            Invalidate();
            Win2dInitialized?.Invoke(this, EventArgs.Empty);
            // initialize background input thread

            ThreadPool.RunAsync(_ =>
            {
                // touch processor
                _inputSource = _canvas.CreateCoreIndependentInputSource(
                    CoreInputDeviceTypes.Touch | CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen
                    );
                _inputSource.PointerPressed      += CanvasPointerPressed;
                _inputSource.PointerMoved        += CanvasPointerMoved;
                _inputSource.PointerReleased     += CanvasPointerReleased;
                _inputSource.PointerCaptureLost  += CanvasPointerReleased;
                _inputSource.PointerWheelChanged += CanvasWheelChanged;
                // setup gesture recognizer
                _recognizer = new GestureRecognizer {
                    AutoProcessInertia = true
                };
                _recognizer.GestureSettings =
                    GestureSettings.ManipulationTranslateInertia | GestureSettings.ManipulationTranslateRailsX |
                    GestureSettings.ManipulationTranslateRailsY | GestureSettings.ManipulationTranslateX |
                    GestureSettings.ManipulationTranslateY |
                    GestureSettings.ManipulationScale | GestureSettings.ManipulationScaleInertia;
                _recognizer.ManipulationUpdated += _recognizer_ManipulationUpdated;
                _inputSource.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit);
            }, WorkItemPriority.High, WorkItemOptions.TimeSliced);
        }
示例#23
0
        private void CanvasControl_SizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e)
        {
            CanvasSwapChain currentSwapChain = canvasControl.SwapChain;

            if (currentSwapChain == null)
            {
                CanvasSwapChain swapChain = new CanvasSwapChain(new CanvasDevice(), (float)e.NewSize.Width * 2, (float)e.NewSize.Height * 2, 96 * canvasControl.CompositionScaleX);
                canvasControl.SwapChain = swapChain;
            }
            else if (currentSwapChain.Size.Width < e.NewSize.Width || currentSwapChain.Size.Height < e.NewSize.Height)
            {
                canvasControl.SwapChain.ResizeBuffers((float)e.NewSize.Width * 2, (float)e.NewSize.Height * 2, 96 * canvasControl.CompositionScaleX);
            }
            var ds = canvasControl.SwapChain.CreateDrawingSession(Colors.AliceBlue);

            ds.Dispose();
            canvasControl.SwapChain.Present();
        }
示例#24
0
        // Draw to the CanvasSwapChain.
        void DrawToSwapChain(Size size)
        {
            if (swapChain == null)
            {
                swapChain = new CanvasSwapChain(canvasControl, (float)size.Width, (float)size.Height);
                swapChainPanel.SwapChain = swapChain;
            }
            else
            {
                swapChain.ResizeBuffers((float)size.Width, (float)size.Height);
            }

            using (var ds = swapChain.CreateDrawingSession(Colors.Yellow))
            {
                DrawTextLabel(ds, "Canvas\nSwap\nChain", size);
            }

            swapChain.Present();
        }
示例#25
0
        public void SetDevice(CanvasDevice device)
        {
            drawLoopCancellationTokenSource?.Cancel();

            var displayInfo = Windows.Graphics.Display.DisplayInformation.GetForCurrentView();

            this.swapChain = new CanvasSwapChain(
                device,
                (int)this.ActualWidth,
                (int)this.ActualHeight,
                displayInfo.LogicalDpi,
                Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                2,
                CanvasAlphaMode.Premultiplied);

            swapChainVisual.Brush = Window.Current.Compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(Window.Current.Compositor, swapChain));

            drawLoopCancellationTokenSource = new CancellationTokenSource();
        }
示例#26
0
        private void DrawSwapChain(CanvasSwapChain sc)
        {
            var result = Monitor.TryEnter(drawlock);

            if (result)
            {
                try
                {
                    ++drawCount;

                    using (var ds = sc.CreateDrawingSession(Colors.Transparent))
                    {
                        var size = sc.Size.ToVector2();

                        if (ShowAsPercentage)
                        {
                            ds.DrawText($"{CalcPercentage()}%", new Rect(0, 0, this.swapChain.Size.Width, this.swapChain.Size.Height), foregroundColor, new CanvasTextFormat()
                            {
                                FontSize            = 17,
                                VerticalAlignment   = CanvasVerticalAlignment.Bottom,
                                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            });
                        }
                        else
                        {
                            ds.DrawText($"{this.CurrentTime.ToString(@"hh\:mm\:ss")}", new Rect(0, 0, this.swapChain.Size.Width, this.swapChain.Size.Height), foregroundColor, new CanvasTextFormat()
                            {
                                FontSize            = 15,
                                VerticalAlignment   = CanvasVerticalAlignment.Center,
                                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            });
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(drawlock);
                }
            }
        }
示例#27
0
        private void RenderThread(object parameter)
        {
            CanvasSwapChain swapChain = (CanvasSwapChain)parameter;

            using (MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateOrOpen("XboxGameBarPoc_SharedMemory", 0x644, MemoryMappedFileAccess.ReadWriteExecute))
            {
                using (MemoryMappedViewAccessor viewAccessor = memoryMappedFile.CreateViewAccessor())
                {
                    using (Mutex mutex = new Mutex(false, "XboxGameBarPoc_Mutex"))
                    {
                        while (true)
                        {
                            try
                            {
                                mutex.WaitOne();

                                int count = 0;
                                viewAccessor.Read <int>(0, out count);
                                Box[] boxArray = new Box[count];
                                viewAccessor.ReadArray <Box>(4, boxArray, 0, count);

                                using (CanvasDrawingSession ds = canvasSwapChainPanel.SwapChain.CreateDrawingSession(Colors.Transparent))
                                {
                                    for (int i = 0; i < boxArray.Length; i++)
                                    {
                                        ds.DrawRectangle(boxArray[i].X, boxArray[i].Y, boxArray[i].Width, boxArray[i].Height, Colors.Red);
                                    }
                                }
                                canvasSwapChainPanel.SwapChain.Present();
                            }
                            finally
                            {
                                mutex.ReleaseMutex();
                            }
                        }
                    }
                }
            }
        }
示例#28
0
        void Canvas_CreateResources(CanvasControl sender, object args)
        {
            defaultDpiBitmap = CreateTestBitmap(sender, defaultDpi);
            highDpiBitmap    = CreateTestBitmap(sender, highDpi);
            lowDpiBitmap     = CreateTestBitmap(sender, lowDpi);

            autoDpiRenderTarget = new CanvasRenderTarget(sender, testSize, testSize);
            highDpiRenderTarget = new CanvasRenderTarget(sender, testSize, testSize, highDpi);
            lowDpiRenderTarget  = new CanvasRenderTarget(sender, testSize, testSize, lowDpi);

            saturationEffect = new SaturationEffect {
                Saturation = 0
            };

            imageBrush = new CanvasImageBrush(sender);

            imageSource         = new CanvasImageSource(sender, controlSize, controlSize);
            imageControl.Source = imageSource;

            swapChain = new CanvasSwapChain(sender, controlSize, controlSize);
            swapChainPanel.SwapChain = swapChain;
        }
示例#29
0
        public void SetDevice(CanvasDevice device)
        {
            drawLoopCancellationTokenSource?.Cancel();

            var displayInfo = Windows.Graphics.Display.DisplayInformation.GetForCurrentView();

            this.swapChain = new CanvasSwapChain(device, (int)this.ActualWidth, (int)this.ActualHeight, displayInfo.LogicalDpi);

            swapChainVisual.Brush = Window.Current.Compositor().CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(Window.Current.Compositor(), swapChain));

            drawLoopCancellationTokenSource = new CancellationTokenSource();

            Task.Factory.StartNew(

                DrawLoop,

                drawLoopCancellationTokenSource.Token,

                TaskCreationOptions.LongRunning,

                TaskScheduler.Default);
        }
示例#30
0
        public Capture(CanvasDevice device, GraphicsCaptureItem item)
        {
            _item   = item;
            _device = device;

            // TODO: Dpi?
            _swapChain = new CanvasSwapChain(_device, item.Size.Width, item.Size.Height, 96);

            _dispatcherQueueController = DispatcherQueueController.CreateOnDedicatedThread();
            _dispatcherQueue           = _dispatcherQueueController.DispatcherQueue;

            // We don't want to return from the constructor untill the frame pool and
            // the capture session are both initialized. We could do this on the UI thread,
            // but you really shouldn't. This will update as fast as the screen refresh rate,
            // so it would cause performance issues on the UI thread.
            var wait    = new AutoResetEvent(false);
            var success = _dispatcherQueue.TryEnqueue(() =>
            {
                _framePool = Direct3D11CaptureFramePool.Create(
                    _device,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    2,
                    item.Size);
                _session  = _framePool.CreateCaptureSession(item);
                _lastSize = item.Size;

                _framePool.FrameArrived += OnFrameArrived;

                wait.Set();
            });

            if (!success)
            {
                throw new Exception("Could not enqueue work!");
            }

            wait.WaitOne();
        }
示例#31
0
        void DrawStuff(CanvasDrawingSession ds)
        {
            int horizontalLimit = (int)m_canvasControl.ActualWidth;
            int verticalLimit   = (int)m_canvasControl.ActualHeight;

            DrawnContentType drawnContentType = (DrawnContentType)m_drawnContentTypeCombo.SelectedValue;

            ds.Clear(NextRandomColor());

            Vector2 point;
            float   radiusX;
            float   radiusY;

            Random random = new Random();

            m_canvasSwapChainPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            switch (drawnContentType)
            {
            case DrawnContentType.Clear_Only:
                break;

            case DrawnContentType.Bitmap:
                if (m_bitmap_tiger != null)
                {
                    ds.DrawImage(m_bitmap_tiger, NextRandomPoint(horizontalLimit, verticalLimit).ToVector2());
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.Rectangle_Filled:
                Point bound0 = NextRandomPoint(horizontalLimit, verticalLimit);
                Point bound1 = NextRandomPoint(horizontalLimit, verticalLimit);

                m_linearGradientBrush.StartPoint = bound0.ToVector2();
                m_linearGradientBrush.EndPoint   = bound1.ToVector2();

                ds.FillRectangle(
                    new Rect(bound0, bound1),
                    m_linearGradientBrush);

                break;

            case DrawnContentType.Ellipse_Fill:
                NextRandomEllipse(horizontalLimit, verticalLimit, out point, out radiusX, out radiusY);
                ds.FillEllipse(
                    point, radiusX, radiusY,
                    NextRandomColor());
                break;

            case DrawnContentType.Circle_Fill:
                ds.FillCircle(
                    NextRandomPoint(horizontalLimit, verticalLimit).ToVector2(),
                    100,
                    NextRandomColor());
                break;

            case DrawnContentType.Text:
                var p     = NextRandomPoint(horizontalLimit, verticalLimit);
                var x     = (float)p.X;
                var y     = (float)p.Y;
                var color = NextRandomColor();
                ds.DrawLine(new Vector2(x, 0), new Vector2(x, verticalLimit), color);
                ds.DrawLine(new Vector2(0, y), new Vector2(horizontalLimit, y), color);
                ds.DrawText(
                    "Centered",
                    p.ToVector2(),
                    color,
                    new CanvasTextFormat()
                {
                    FontSize           = 18,
                    VerticalAlignment  = CanvasVerticalAlignment.Center,
                    ParagraphAlignment = ParagraphAlignment.Center
                });

                var r = NextRandomRect(horizontalLimit, verticalLimit);
                ds.DrawRectangle(r, color);
                ds.DrawText(
                    m_quiteLongText,
                    r,
                    NextRandomColor(),
                    new CanvasTextFormat()
                {
                    FontFamily         = "Comic Sans MS",
                    FontSize           = 18,
                    ParagraphAlignment = ParagraphAlignment.Justify,
                    Options            = CanvasDrawTextOptions.Clip
                });
                break;

            case DrawnContentType.ImageBrush:
                if (m_bitmap_tiger != null)
                {
                    m_imageBrush.Image   = m_bitmap_tiger;
                    m_imageBrush.ExtendX = (CanvasEdgeBehavior)(m_random.Next(3));
                    m_imageBrush.ExtendY = (CanvasEdgeBehavior)(m_random.Next(3));
                    ds.FillRectangle(new Rect(0, 0, horizontalLimit, verticalLimit), m_imageBrush);
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.OffscreenTarget:
                m_imageBrush.Image   = m_offscreenTarget;
                m_imageBrush.ExtendX = (CanvasEdgeBehavior)(m_random.Next(3));
                m_imageBrush.ExtendY = (CanvasEdgeBehavior)(m_random.Next(3));
                ds.FillRectangle(new Rect(0, 0, horizontalLimit, verticalLimit), m_imageBrush);
                break;

            case DrawnContentType.Gradients:
                Vector2 center = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                m_radialGradientBrush.Center = center;
                float radius = m_random.Next(horizontalLimit / 2);
                m_radialGradientBrush.OriginOffset = new Vector2(radius, radius);
                m_radialGradientBrush.RadiusX      = radius;
                m_radialGradientBrush.RadiusY      = radius;
                ds.FillCircle(center, radius, m_radialGradientBrush);

                Vector2 line0 = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                Vector2 line1 = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                m_linearGradientBrush.StartPoint = line0;
                m_linearGradientBrush.EndPoint   = line1;
                float thickness = m_random.Next(horizontalLimit / 2);
                ds.DrawLine(line0, line1, m_linearGradientBrush, thickness);
                break;

            case DrawnContentType.AlternateBitmapLoading:
                if (m_bitmap_colorGrids != null)
                {
                    Matrix3x2 scale = Matrix3x2.CreateScale(20);

                    ds.Transform = scale;
                    ds.DrawImage(m_bitmap_colorGrids[0]);

                    ds.Transform = scale * Matrix3x2.CreateTranslation(200, 0);
                    ds.DrawImage(m_bitmap_colorGrids[1]);

                    ds.Transform = scale * Matrix3x2.CreateTranslation(0, 200);
                    ds.DrawImage(m_bitmap_colorGrids[2]);
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.SwapChainPanel:
                m_canvasSwapChainPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;

                float swapChainWidth  = horizontalLimit * ((float)random.NextDouble() / 2 + 0.5f);
                float swapChainHeight = verticalLimit * ((float)random.NextDouble() / 2 + 0.5f);

                if (m_swapChain == null)
                {
                    m_swapChain = new CanvasSwapChain(ds, swapChainWidth, swapChainHeight);
                    m_canvasSwapChainPanel.SwapChain = m_swapChain;
                }
                else
                {
                    m_swapChain.ResizeBuffers(swapChainWidth, swapChainHeight);
                }

                using (CanvasDrawingSession panelDS = m_swapChain.CreateDrawingSession(NextRandomColor()))
                {
                    panelDS.DrawCircle(swapChainWidth / 2.0f, swapChainHeight / 2.0f, 100.0f, NextRandomColor(), 20.0f);
                }
                m_swapChain.Present();
                break;

            case DrawnContentType.Test_Scene0_Default:
                GeometryTestScene0.DrawGeometryTestScene(ds, TestSceneRenderingType.Default);
                break;

            case DrawnContentType.Test_Scene0_Wireframe:
                GeometryTestScene0.DrawGeometryTestScene(ds, TestSceneRenderingType.Wireframe);
                break;

            case DrawnContentType.Test_Scene1_Default:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Default);
                break;

            case DrawnContentType.Test_Scene1_Randomized:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Randomized);
                break;

            case DrawnContentType.Test_Scene1_Wireframe:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Wireframe);
                break;

            default:
                System.Diagnostics.Debug.Assert(false);     // Unexpected
                break;
            }
        }
示例#32
0
        void DrawSwapChain(CanvasSwapChain swapChain, bool isPaused)
        {
            ++drawCount;

            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                var size = swapChain.Size.ToVector2();
                var radius = (Math.Min(size.X, size.Y) / 2.0f) - 4.0f;

                var center = size / 2;

                ds.FillCircle(center, radius, Colors.LightGoldenrodYellow);
                ds.DrawCircle(center, radius, Colors.LightGray);

                double mu = (-drawCount / 50.0f);

                for (int i =0; i < 16; ++i)
                {
                    double a = mu + (i / 16.0) * Math.PI * 2;
                    var x = (float)Math.Sin(a);
                    var y = (float)Math.Cos(a);
                    ds.DrawLine(center, center + new Vector2(x, y) * radius, Colors.Black, 5);
                }

                var rectLength = Math.Sqrt(radius * radius * 2);

                ds.FillCircle(center, (float)rectLength / 2, Colors.LightGoldenrodYellow);

                var rect = new Rect(center.X - rectLength / 2, center.Y - rectLength / 2, rectLength, rectLength);

                ds.DrawText("This is a swap chain",
                    rect,
                    Colors.Black,
                    new CanvasTextFormat()
                    {
                        FontFamily = "Comic Sans MS",
                        FontSize = 24,
                        VerticalAlignment = CanvasVerticalAlignment.Center,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        WordWrapping = CanvasWordWrapping.WholeWord,
                    });

                var label = string.Format("Draws: {0}\nDevices: {1}\nTap to {2}", drawCount, deviceCount, isPaused ? "unpause" : "pause");

                ds.DrawText(label, rect, Colors.Black, new CanvasTextFormat()
                {
                    FontSize = 10,
                    VerticalAlignment = CanvasVerticalAlignment.Bottom,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center
                });
            }

            swapChain.Present();
        }
示例#33
0
        void Canvas_CreateResources(CanvasControl sender, object args)
        {
            mainDeviceResources = new PerDeviceResources(sender);

            imageBrush = new CanvasImageBrush(sender);

            imageSource = new CanvasImageSource(sender, controlSize, controlSize);
            imageControl.Source = imageSource;

            swapChain = new CanvasSwapChain(sender, controlSize, controlSize);
            swapChainPanel.SwapChain = swapChain;
        }
示例#34
0
        // Draw to the CanvasSwapChain.
        void DrawToSwapChain(Size size)
        {
            if (size.Width <= 0 || size.Height <= 0)
            {
                swapChain = null;
                swapChainPanel.SwapChain = null;
                return;
            }
            else if (swapChain == null)
            {
                swapChain = new CanvasSwapChain(canvasControl, size);
                swapChainPanel.SwapChain = swapChain;
            }
            else
            {
                swapChain.ResizeBuffers((float)size.Width, (float)size.Height, canvasControl.Dpi);
            }

            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                Draw(ds, "Canvas\nSwap\nChain", size);
            }

            swapChain.Present();
        }
示例#35
0
        const float peakMeterFallTime = 0.003f;     // Slow fall time

        void DrawSwapChain(CanvasSwapChain swapChain)
        {
            using (var ds = swapChain.CreateDrawingSession(Colors.Transparent))
            {
                var size   = swapChain.Size.ToVector2();
                var radius = (Math.Min(size.X, size.Y) / 2.0f) - 4.0f;

                var center = size / 2;

                if (PlayerService.Current.ReferencePropertySet?.ContainsKey("samplegrabber") == true)
                {
                    SampleGrabber.IMyInterface mft = (SampleGrabber.IMyInterface)PlayerService.Current.ReferencePropertySet["samplegrabber"];

                    var     dataFrame           = mft.GetFrame();
                    Vector2 visualizationOffset = new Vector2(200, 20);
                    Vector2 barSize             = new Vector2(5, 150);
                    DrawVisualization(dataFrame, ds, true, true, true, barSize, visualizationOffset);
                    // yuck
                    //lock (PassthroughEffect.GetBadLock())

                    /*
                     * {
                     *  if (PlayerService.Current.ReferencePropertySet != null &&
                     *      PlayerService.Current.ReferencePropertySet.ContainsKey("dataQueue") &&
                     *      this.dataQueue == null)
                     *  {
                     *      this.dataQueue = PlayerService.Current.ReferencePropertySet["dataQueue"] as Queue<Tuple<double, double>>;
                     *  }
                     *
                     *  if (this.dataQueue != null && !hasNextValue && this.dataQueue.Count>0)
                     *  {
                     *      nextvalue = this.dataQueue.Dequeue();
                     *      hasNextValue = true;
                     *  } else if (this.dataQueue != null && this.dataQueue.Count == 0)
                     *  {
                     *      hasNextValue = false;
                     *
                     *  }
                     * }
                     *
                     * if (dataQueue != null)
                     * {
                     *  Debug.WriteLine(dataQueue.Count);
                     * }
                     *
                     * if (!weAreVisualizing && hasNextValue)
                     * {
                     *  weAreVisualizing = true;
                     *  delayStart = true;
                     * }
                     *
                     * if (weAreVisualizing && delayStart && delayCurrent < delayTotal)
                     * {
                     *  delayCurrent++;
                     * }
                     * else
                     * {
                     *  delayStart = false;
                     *  delayCurrent = 0;
                     * }
                     *
                     * if (weAreVisualizing && delayStart)
                     * {
                     *  DrawVU(ds, -100, -100);
                     * } else if (weAreVisualizing && !delayStart && nextvalue != null)
                     * {
                     *  DrawVU(ds, nextvalue.Item1, nextvalue.Item2);
                     *  hasNextValue = false;
                     * } else
                     * {
                     *  Debug.WriteLine("miss");
                     *  DrawVU(ds, -100, -100);
                     * }*/
                }

                swapChain.Present();
            }
        }
示例#36
0
        void Canvas_CreateResources(CanvasControl sender, CanvasCreateResourcesEventArgs args)
        {
            args.TrackAsyncAction(LoadCanvasResources(sender).AsAsyncAction());

            imageBrush = new CanvasImageBrush(sender);

            imageSource = new CanvasImageSource(sender, controlSize, controlSize);
            imageControl.Source = imageSource;

            virtualImageSource = new CanvasVirtualImageSource(sender, controlSize, controlSize);
            virtualImageControl.Source = virtualImageSource.Source;

            swapChain = new CanvasSwapChain(sender, controlSize, controlSize);
            swapChainPanel.SwapChain = swapChain;
        }
示例#37
0
        public SwapChainManager(CoreWindow window, CanvasDevice device)
        {
            float currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;

            SwapChain = CanvasSwapChain.CreateForCoreWindow(device, window, currentDpi);
        }
示例#38
0
 public SwapChainManager(CoreWindow window, CanvasDevice device)
 {
     float currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
     SwapChain = CanvasSwapChain.CreateForCoreWindow(device, window, currentDpi);
 }