public void Present()
 {
     if (swapChain != null)
     {
         swapChain.Present(0, PresentFlags.None);
     }
 }
Пример #2
0
        void Render()
        {
            if (resized)
            {
                Resize();
                resized = false;
            }

            d2dDeviceContext.BeginDraw();
            d2dDeviceContext.Clear(Color4.White);

            d2dDeviceContext.PushAxisAlignedClip(new RectangleF(5, 5, Child.Width - 10, Child.Height - 10), AntialiasMode.Aliased);
            d2dDeviceContext.Transform = Matrix3x2.Translation(Child.Width / 2f / Scale + Translation.X, Child.Height / 2f / Scale + Translation.Y) * Matrix3x2.Scaling(Scale);

            d2dDeviceContext.AntialiasMode = AntialiasMode.Aliased;
            d2dDeviceContext.DrawLine(new Vector2(0, int.MinValue), new Vector2(0, int.MaxValue), RasterDrawBrush, 1 / Scale);
            d2dDeviceContext.DrawLine(new Vector2(int.MinValue, 0), new Vector2(int.MaxValue, 0), RasterDrawBrush, 1 / Scale);
            d2dDeviceContext.AntialiasMode = AntialiasMode.PerPrimitive;

            RenderGeometry();

            d2dDeviceContext.Transform = Matrix3x2.Identity;
            d2dDeviceContext.PopAxisAlignedClip();

            d2dDeviceContext.EndDraw();
            swapChain.Present(0, PresentFlags.None);
        }
Пример #3
0
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                // Clear the target.
                d2dContext.BeginDraw();
                d2dContext.Clear(Color.CornflowerBlue);

                // Draw a block of text that will be clipped against the specified layout rectangle.
                d2dContext.FillRectangle(new RectangleF(50, 50, 200, 200), backgroundBrush);
                d2dContext.DrawText("This text is long enough to overflow the designed region but will be clipped to the containing rectangle. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", textFormat, new RectangleF(50, 50, 200, 200), textBrush, DrawTextOptions.Clip);

                // Draw a block of text that will overflow the specified layout rectangle.
                d2dContext.FillRectangle(new RectangleF(50, 300, 200, 200), backgroundBrush);
                d2dContext.DrawText("However, this other text isn't going to be clipped: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean gravida dui id accumsan dictum.", textFormat, new RectangleF(50, 300, 200, 200), textBrush, DrawTextOptions.None);

                // Draw three lines of text with different measuring modes.
                d2dContext.FillRectangle(new RectangleF(300, 50, 400, 200), backgroundBrush);
                d2dContext.DrawText("MeasuringMode: Natural", textFormat, new RectangleF(300, 50, 400, 200), textBrush, DrawTextOptions.None, MeasuringMode.Natural);
                d2dContext.DrawText("MeasuringMode: GDI classic", textFormat, new RectangleF(300, 80, 400, 200), textBrush, DrawTextOptions.None, MeasuringMode.GdiClassic);
                d2dContext.DrawText("MeasuringMode: GDI natural", textFormat, new RectangleF(300, 110, 400, 200), textBrush, DrawTextOptions.None, MeasuringMode.GdiNatural);

                float layoutYOffset = (float)Math.Cos(layoutY) * 50.0f;

                // Draw moving text.
                d2dContext.FillRectangle(new RectangleF(300, 300, 400, 200), backgroundBrush);
                d2dContext.DrawTextLayout(new Vector2(300, 350 + layoutYOffset), textLayout1, textBrush);

                // Draw moving text without pixel snapping, thus giving a smoother movement.
                d2dContext.FillRectangle(new RectangleF(750, 300, 400, 200), backgroundBrush);
                d2dContext.DrawTextLayout(new Vector2(750, 350 + layoutYOffset), textLayout2, textBrush, DrawTextOptions.NoSnap);

                d2dContext.EndDraw();
                layoutY += 1.0f / 60.0f;

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }
Пример #4
0
            /// <inheritdoc/>
            public void Run()
            {
                // Activate the application window, making it visible and enabling it to receive events.
                window.Activate();

                // Prepare matrices
                var view     = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
                var proj     = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, width / (float)height, 0.1f, 100.0f);
                var viewProj = Matrix.Multiply(view, proj);

                // Enter the render loop.  Note that Metro style apps should never exit.
                while (true)
                {
                    // Process events incoming to the window.
                    window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                    if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                    {
                        break;
                    }

                    // Gets the current graphics context
                    var graphicsContext = graphicsDevice.ImmediateContext;

                    var time = (float)(clock.ElapsedMilliseconds / 1000.0);

                    // Set targets (This is mandatory in the loop)
                    graphicsContext.OutputMerger.SetTargets(renderTargetView);

                    // Clear the views
                    graphicsContext.ClearRenderTargetView(renderTargetView, Color.CornflowerBlue);

                    // Calculate WorldViewProj
                    Matrix worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2.0f) * Matrix.RotationZ(time * .7f) * viewProj;
                    worldViewProj.Transpose();

                    // Setup the pipeline
                    graphicsContext.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
                    graphicsContext.InputAssembler.InputLayout       = layout;
                    graphicsContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                    graphicsContext.VertexShader.SetConstantBuffer(0, constantBuffer);
                    graphicsContext.VertexShader.Set(vertexShader);
                    graphicsContext.PixelShader.Set(pixelShader);

                    // Update Constant Buffer
                    graphicsContext.UpdateSubresource(ref worldViewProj, constantBuffer, 0);

                    // Draw the cube
                    graphicsContext.Draw(36, 0);

                    // Present the backbuffer
                    swapChain.Present(1, PresentFlags.None, new PresentParameters());
                }
            }
Пример #5
0
            /// <summary>
            /// Presents this instance.
            /// </summary>
            /// <returns></returns>
            public override bool Present()
            {
                var res = swapChain.Present(VSyncInterval, PresentFlags.None, presentParams);

                if (res.Success)
                {
                    return(true);
                }
                else
                {
                    var desc = ResultDescriptor.Find(res);
                    if (desc == global::SharpDX.DXGI.ResultCode.DeviceRemoved || desc == global::SharpDX.DXGI.ResultCode.DeviceReset || desc == global::SharpDX.DXGI.ResultCode.DeviceHung)
                    {
                        RaiseOnDeviceLost();
                    }
                    else
                    {
                        swapChain.Present(VSyncInterval, PresentFlags.Restart, presentParams);
                    }
                    return(false);
                }
            }
 void Render()
 {
     if (ImmediateContext != null)
     {
         // https://msdn.microsoft.com/en-us/library/windows/desktop/bb205120(v=vs.85).aspx
         // 把renderTargetView綁定到Output-Merger Stage
         ImmediateContext.OutputMerger.SetRenderTargets(renderTargetView);
         // 填滿背景色
         ImmediateContext.ClearRenderTargetView(renderTargetView, Color.Black);
         // 畫一個三角形
         ImmediateContext.Draw(3, 0);
         // 把畫好的結果輸出到螢幕上!
         swapChain1.Present(1, PresentFlags.None);
     }
 }
            public void InitializeRenderThread(DeviceContext renderContext, SwapChain1 swapChain)
            {
                DestoryRenderThread();
                Exception          = null;
                this.renderContext = renderContext;
                this.swapChain     = swapChain;
                tsc = new CancellationTokenSource();
                var token = tsc.Token;

                RenderThread = new Thread(new ThreadStart(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        try
                        {
                            renderThreadEvent.Wait();
                            if (token.IsCancellationRequested)
                            {
                                break;
                            }
                            lock (mlock)
                            {
                                if (!paused)
                                {
                                    renderContext.ExecuteCommandList(commandList, true);
                                    renderContext.Flush();
                                    swapChain.Present(0, 0);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Exception = ex;
                            Pause();
                            break;
                        }
                        finally
                        {
                            Disposer.RemoveAndDispose(ref commandList);
                            renderThreadEvent.Reset();
                            IsBusy = false;
                        }
                    }
                }));
                RenderThread.SetApartmentState(ApartmentState.STA);
                RenderThread.IsBackground = true;
                RenderThread.Start();
            }
Пример #8
0
        public void Present()
        {
            if (!_ready)
            {
                return;
            }
            var pp = new PresentParameters()
            {
                DirtyRectangles = null,
                ScrollOffset    = null,
                ScrollRectangle = null
            };

            // Present
            _swap.Present(1, PresentFlags.None, pp);
            _context.DiscardView(_rtv);
        }
Пример #9
0
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                // Clear the target and draw some geometry with the brushes we created.
                d2dContext.BeginDraw();
                d2dContext.Clear(Color.CornflowerBlue);

                // Calculate the center of the screen
                int halfWidth  = this.swapChain.Description.ModeDescription.Width / 2;
                int halfHeight = this.swapChain.Description.ModeDescription.Height / 2;

                // Translate the origin of coordinates for drawing the bitmap filled rectangle
                d2dContext.Transform = Matrix3x2.Translation(halfWidth - 350, halfHeight);
                d2dContext.FillRectangle(new RectangleF(0, 0, 700, 70), terrainBrush);

                // Translate again for drawing the player bitmap
                d2dContext.Transform = Matrix3x2.Translation(halfWidth, halfHeight - playerBitmap.Size.Height);
                d2dContext.DrawBitmap(playerBitmap, 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.Linear);
                d2dContext.EndDraw();

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }
Пример #10
0
        public override void Present()
        {
            if (swapChain1 == null)
            {
                swapChain.Present(1, PresentFlags.None);
            }
            else
            {
                swapChain1.Present(1, PresentFlags.None, new PresentParameters());
            }

            try {//only for Window 10
                if (swapChain3 != null)
                {
                    WaitForSingleObjectEx(swapChain3.FrameLatencyWaitableObject.ToInt32(), 1000, true);
                }
            } catch { }
            // Output the current active Direct3D objects
            //System.Diagnostics.Debug.Write(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
        }
Пример #11
0
        public void Dispose()
        {
            if (pinnedMemBuffer.IsAllocated)
            {
                pinnedMemBuffer.Free();
            }

            TryReleaseFrame();
            if (Settings.SettingsHwnd != IntPtr.Zero)  // restore window background color
            {
                try {
                    device?.ImmediateContext.ClearRenderTargetView(renderTarget, SharpDX.Color.WhiteSmoke);
                    renderWindow?.Present(0, PresentFlags.None);
                } catch { }
            }

            Settings.Model.PropertyChanged -= LedsChanged;
            fpsCounter?.Dispose();
            fpsColor?.Dispose();
            fpsFont?.Dispose();
            renderOverlay?.Dispose();
            renderTarget?.Dispose();
            renderTexture?.Dispose();
            renderWindow?.Dispose();

            try {
                device?.ImmediateContext?.ClearState();
                device?.ImmediateContext?.Flush();
                device?.ImmediateContext?.Dispose();
            } catch { }

            adapter?.Dispose();
            output?.Dispose();
            device?.Dispose();
            duplicator?.Dispose();
            capture?.Dispose();
            scaler?.Dispose();
            gpuTexture?.Dispose();
            cpuTexture?.Dispose();
        }
Пример #12
0
        /// <summary>
        /// Run our application until the user quits.
        /// </summary>
        public void Run()
        {
            // Make window active and hide mouse cursor.
            window.PointerCursor = null;
            window.Activate();

            // Infinite loop to prevent the application from exiting.
            while (true)
            {
                // Dispatch all pending events in the queue.
                window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

                // Quit if the users presses Escape key.
                if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
                {
                    return;
                }

                // Set the Direct2D drawing target.
                d2dContext.Target = d2dTarget;

                // Clear the target and draw some geometry with the brushes we created.
                d2dContext.BeginDraw();
                d2dContext.Clear(Color.CornflowerBlue);
                d2dContext.FillRectangle(new RectangleF(50, 50, 450, 150), solidBrush);
                d2dContext.FillRoundedRectangle(new RoundedRectangle()
                {
                    Rect    = new RectangleF(50, 250, 450, 150),
                    RadiusX = 10,
                    RadiusY = 10
                }, linearGradientBrush);
                d2dContext.FillEllipse(new Ellipse(new Vector2(250, 525), 100, 100), radialGradientBrush);
                d2dContext.EndDraw();

                // Present the current buffer to the screen.
                swapChain.Present(1, PresentFlags.None);
            }
        }
Пример #13
0
        private void Render(byte[] points)
        {
            if (CheckRender(Settings.SettingsHwnd))
            {
                device.ImmediateContext.CopySubresourceRegion(gpuTexture, gpuTexture.Description.MipLevels - 1, null, renderTexture, 0);

                renderOverlay.BeginDraw();
                renderOverlay.DrawText($"FPS: {fpsCounter.NextFPS():00.00}", fpsFont, fpsLocation, fpsColor);

                for (var i = 0; i < ledPoints.Length; i++)
                {
                    var r     = points[(i * 3)] / 255F;
                    var g     = points[(i * 3) + 1] / 255F;
                    var b     = points[(i * 3) + 2] / 255F;
                    var point = ledPoints[i];
                    var x     = point.width / 2F;
                    var y     = point.height / 2F;

                    var selected =
#if DEBUG
                        i == Settings.Model.PreviewLED? 1F :
#endif
                        0F;

                    using (var color = new SolidColorBrush(renderOverlay, new Color4(r, g, b, 1F)))
                        using (var outline = new SolidColorBrush(renderOverlay, new Color4(selected, selected, selected, 1F))) {
                            renderOverlay.DrawEllipse(new Ellipse(new RawVector2(point.x + x, point.y + y), x / 2, y / 2), outline);
                            renderOverlay.FillEllipse(new Ellipse(new RawVector2(point.x + x, point.y + y), x / 2, y / 2), color);
                        }
                }

                //TODO: draw volume bar meter
                renderOverlay.EndDraw();
                renderWindow.Present(0, PresentFlags.None, presentParameters);
            }
        }
Пример #14
0
        internal void Present()
        {
            if (FPSCounter)
            {
                _fpsCounter.DrawFrame(this);
            }

            try
            {
                _swapChain.Present(VSync ? 1 : 0, PresentFlags.None);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved ||
                    ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset)
                {
                    Initialise();
                }
                else
                {
                    throw;
                }
            }
        }
Пример #15
0
 public override void Swap()
 {
     _swapChain.Present(_vsync ? 1 : 0, PresentFlags.None);
 }
Пример #16
0
 /// <summary>
 /// Completes drawing.
 /// </summary>
 private void EndDraw()
 {
     _d2dContext.EndDraw();
     _swapChain.Present(1, PresentFlags.None);
 }
Пример #17
0
 public void Present()
 {
     ImmediateContext.OutputMerger.ResetTargets();
     m_swapChain.Present(1, PresentFlags.None);
 }
Пример #18
0
        public static void Run()
        {
            var featureLevels = new[]
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0
            };
            const DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            const int width  = 640;
            const int height = 480;

            using (var form = new RenderForm
            {
                Width = width,
                Height = height
            })
            {
                var swapChainDescription = new SwapChainDescription1
                {
                    Width             = form.ClientSize.Width,
                    Height            = form.ClientSize.Height,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription(4, 4),
                    Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount       = 1,
                    Scaling           = Scaling.Stretch,
                    SwapEffect        = SwapEffect.Discard,
                    Flags             = SwapChainFlags.AllowModeSwitch
                };
                var swapChainFullScreenDescription = new SwapChainFullScreenDescription
                {
                    RefreshRate = new Rational(60, 1),
                    Scaling     = DisplayModeScaling.Centered,
                    Windowed    = true
                };

                var samplerStateDescription = new SamplerStateDescription
                {
                    AddressU = TextureAddressMode.Wrap,
                    AddressV = TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                    Filter   = Filter.MinMagMipLinear
                };
                var rasterizerStateDescription = RasterizerStateDescription.Default();
                rasterizerStateDescription.IsFrontCounterClockwise = true;

                // Set up the graphics devices
                using (var device0 = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags, featureLevels))
                    using (var device1 = device0.QueryInterface <SharpDX.Direct3D11.Device1>())
                        using (var context = device0.ImmediateContext.QueryInterface <DeviceContext1>())


                            // Create shaders and related resources
                            using (var vertexShaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", ShaderFlags.Debug))
                                using (var vertexShader = new VertexShader(device1, vertexShaderBytecode))
                                    using (var pixelShaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", ShaderFlags.Debug))
                                        using (var pixelShader = new PixelShader(device1, pixelShaderBytecode))
                                            using (var inputLayout = new InputLayout(device1, ShaderSignature.GetInputSignature(vertexShaderBytecode), new[]
                                            {
                                                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                                                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                                                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),
                                            }))
                                                using (var worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device1, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0))
                                                    using (var texture = TextureLoader.CreateTexture2DFromBitmap(device1, TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), "text.png")))
                                                        using (ShaderResourceView textureView = new ShaderResourceView(device1, texture))
                                                            using (var samplerState = new SamplerState(device1, samplerStateDescription))

                                                                // Prepare rendering targets and related resources
                                                                using (var dxgiDevice2 = device1.QueryInterface <SharpDX.DXGI.Device2>())
                                                                    using (var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <Factory2>())
                                                                        using (var swapChain = new SwapChain1(dxgiFactory2, device1, form.Handle, ref swapChainDescription, swapChainFullScreenDescription))
                                                                            using (var backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0))
                                                                                using (var rasterizerState = new RasterizerState(device1, rasterizerStateDescription))
                                                                                    using (var renderTargetView = new RenderTargetView(device1, backBuffer))
                                                                                    {
                                                                                        var viewport = new ViewportF(0, 0, backBuffer.Description.Width, backBuffer.Description.Height);
                                                                                        context.Rasterizer.SetViewport(viewport);
                                                                                        context.Rasterizer.State = rasterizerState;

                                                                                        var depthBufferDescription = new Texture2DDescription
                                                                                        {
                                                                                            Format            = Format.D32_Float_S8X24_UInt,
                                                                                            ArraySize         = 1,
                                                                                            MipLevels         = 1,
                                                                                            Width             = backBuffer.Description.Width,
                                                                                            Height            = backBuffer.Description.Height,
                                                                                            SampleDescription = swapChain.Description.SampleDescription,
                                                                                            BindFlags         = BindFlags.DepthStencil,
                                                                                        };
                                                                                        var depthStencilViewDescription = new DepthStencilViewDescription
                                                                                        {
                                                                                            Dimension = swapChain.Description.SampleDescription.Count > 1 || swapChain.Description.SampleDescription.Quality > 0
                            ? DepthStencilViewDimension.Texture2DMultisampled
                            : DepthStencilViewDimension.Texture2D
                                                                                        };
                                                                                        var depthStencilStateDescription = new DepthStencilStateDescription
                                                                                        {
                                                                                            IsDepthEnabled   = true,
                                                                                            DepthComparison  = Comparison.Less,
                                                                                            DepthWriteMask   = DepthWriteMask.All,
                                                                                            IsStencilEnabled = false,
                                                                                            StencilReadMask  = 0xff,
                                                                                            StencilWriteMask = 0xff,
                                                                                            FrontFace        = new DepthStencilOperationDescription
                                                                                            {
                                                                                                Comparison         = Comparison.Always,
                                                                                                PassOperation      = StencilOperation.Keep,
                                                                                                FailOperation      = StencilOperation.Keep,
                                                                                                DepthFailOperation = StencilOperation.Increment
                                                                                            },
                                                                                            BackFace = new DepthStencilOperationDescription
                                                                                            {
                                                                                                Comparison         = Comparison.Always,
                                                                                                PassOperation      = StencilOperation.Keep,
                                                                                                FailOperation      = StencilOperation.Keep,
                                                                                                DepthFailOperation = StencilOperation.Decrement
                                                                                            }
                                                                                        };

                                                                                        using (var depthBuffer = new Texture2D(device1, depthBufferDescription))
                                                                                            using (var depthStencilView = new DepthStencilView(device1, depthBuffer, depthStencilViewDescription))
                                                                                                using (var depthStencilState = new DepthStencilState(device1, depthStencilStateDescription))
                                                                                                {
                                                                                                    context.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
                                                                                                    context.OutputMerger.DepthStencilState = depthStencilState;
                                                                                                    context.InputAssembler.InputLayout     = inputLayout;
                                                                                                    context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);
                                                                                                    context.VertexShader.Set(vertexShader);
                                                                                                    context.PixelShader.Set(pixelShader);
                                                                                                    context.PixelShader.SetShaderResource(0, textureView);
                                                                                                    context.PixelShader.SetSampler(0, samplerState);

                                                                                                    form.Show();

                                                                                                    var cameraPosition      = new Vector3(1.5f, 1.8f, -3);
                                                                                                    var cameraTarget        = Vector3.Zero;
                                                                                                    var cameraUp            = Vector3.UnitY;
                                                                                                    var worldMatrix         = Matrix.Identity;
                                                                                                    var viewMatrix          = Matrix.LookAtLH(cameraPosition, cameraTarget, cameraUp);                                                        // reorient everything to camera space
                                                                                                    var projectionMatrix    = Matrix.PerspectiveFovLH((float)Math.PI / 3f, form.ClientSize.Width / (float)form.ClientSize.Height, .5f, 100f); // create a generic perspective projection matrix
                                                                                                    var viewProjection      = Matrix.Multiply(viewMatrix, projectionMatrix);                                                                  // apply the perspective projection to the view matrix so that we're performing both operations
                                                                                                    var worldViewProjection = worldMatrix * viewProjection;                                                                                   // include world translation with the view projection matrix
                                                                                                    worldViewProjection.Transpose();

                                                                                                    var model = GetCubeModel();
                                                                                                    using (var vertexBuffer = CreateBuffer(device1, BindFlags.VertexBuffer, model.Vertices))
                                                                                                        using (var indexBuffer = CreateBuffer(device1, BindFlags.IndexBuffer, model.Triangles))
                                                                                                        {
                                                                                                            var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0);
                                                                                                            context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
                                                                                                            context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
                                                                                                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                                                                                                            RenderLoop.Run(form, () =>
                                                                                                            {
                                                                                                                context.ClearRenderTargetView(renderTargetView, Color.CornflowerBlue);
                                                                                                                context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

                                                                                                                context.DrawIndexed(model.Triangles.Length * 3, 0, 0);

                                                                                                                swapChain.Present(1, PresentFlags.None);
                                                                                                            });
                                                                                                        }
                                                                                                }
                                                                                    }
            }
        }
Пример #19
0
 public void Present()
 {
     m_swapChain.Present(0, PresentFlags.None);
 }
Пример #20
0
        public void PresentFrame(MediaFrame frame = null)
        {
            if (device == null)
            {
                return;
            }

            // Drop Frames | Priority on video frames
            bool gotIn = frame == null?Monitor.TryEnter(device, 1) : Monitor.TryEnter(device, 5);

            if (gotIn)
            {
                try
                {
                    if (frame != null)
                    {
                        if (decoder.vDecoder.hwAccelSuccess)
                        {
                            curSRVs    = new ShaderResourceView[2];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0], srvDescR);
                            curSRVs[1] = new ShaderResourceView(device, frame.textures[0], srvDescRG);
                        }
                        else if (decoder.vDecoder.info.PixelFormatType == PixelFormatType.Software_Handled)
                        {
                            curSRVs    = new ShaderResourceView[3];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0]);
                            curSRVs[1] = new ShaderResourceView(device, frame.textures[1]);
                            curSRVs[2] = new ShaderResourceView(device, frame.textures[2]);
                        }
                        else
                        {
                            curSRVs    = new ShaderResourceView[1];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0]);
                        }

                        context.PixelShader.Set(curPixelShader);
                        context.PixelShader.SetShaderResources(0, curSRVs);
                    }

                    context.OutputMerger.SetRenderTargets(rtv);
                    context.ClearRenderTargetView(rtv, cfg.video._ClearColor);
                    context.Draw(6, 0);

                    swapChain.Present(cfg.video.VSync, PresentFlags.None);

                    if (frame != null)
                    {
                        if (frame.textures != null)
                        {
                            for (int i = 0; i < frame.textures.Length; i++)
                            {
                                Utilities.Dispose(ref frame.textures[i]);
                            }
                        }
                        if (curSRVs != null)
                        {
                            for (int i = 0; i < curSRVs.Length; i++)
                            {
                                Utilities.Dispose(ref curSRVs[i]);
                            }
                            curSRVs = null;
                        }
                    }
                } finally { Monitor.Exit(device); }
            }
            else
            {
                Log("Dropped Frame - Lock timeout " + (frame != null ? Utils.TicksToTime(frame.timestamp) : "")); Utils.DisposeVideoFrame(frame);
            }
        }
Пример #21
0
 public void EndDraw()
 {
     Context.EndDraw();
     _swapChain.Present(_form.SyncInterval, PresentFlags.None, new PresentParameters());
 }
Пример #22
0
        static void Main()
        {
            #region Direct3D 11.1 Initialization
            var form = new Form1();
            form.Text   = "D3D 11.1 App";
            form.Width  = 1920;
            form.Height = 1080;

            Device1 device11_1;
            SharpDX.DXGI.SwapChain1 swapChain1;

            // 1. Create a regular D3D11 device
            // Explicitly excluding feature levels below 11_0 as we will be using SM5.0 and other D3D11 features
#if DEBUG
            using (var device11 = new Device(SharpDX.Direct3D.DriverType.Hardware,
                                             DeviceCreationFlags.Debug,
                                             new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0
            }))
            {
                // Query device for the device11_1 interface (ID3D11device11_1)
                device11_1 = device11.QueryInterfaceOrNull <Device1>();
                if (device11_1 == null)
                {
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported.");
                }
            }
#else
            using (var device11 = new Device(SharpDX.Direct3D.DriverType.Hardware,
                                             DeviceCreationFlags.None,
                                             new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0
            }))
            {
                // Query device for the device11_1 interface (ID3D11device11_1)
                device11_1 = device11.QueryInterfaceOrNull <Device1>();
                if (device11_1 == null)
                {
                    throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported.");
                }
            }
#endif



            // 2. Initialize Swap Chain
            // To create the swap chain, we need to first get a reference to SharpDX.DXGI.Factory2 instance
            // Rather than creating a new factory, we will use the one that was initialized internally to create our device

            using (var dxgi = device11_1.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        // Describing the
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = form.ClientSize.Width,
                            Height            = form.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = SharpDX.DXGI.Scaling.Stretch,
                            SwapEffect        = SharpDX.DXGI.SwapEffect.Discard
                        };

                        swapChain1 = new SwapChain1(factory,
                                                    device11_1,
                                                    form.Handle,
                                                    ref desc1,
                                                    new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                    adapter.Outputs[0]);
                    }

            // Retrieve references to backbuffer and rendertargetview
            var backBuffer       = Texture2D.FromSwapChain <Texture2D>(swapChain1, 0);
            var renderTargetView = new RenderTargetView(device11_1, backBuffer);

            #endregion



            #region RenderLoop

            var clock     = new System.Diagnostics.Stopwatch();
            var clockFreq = System.Diagnostics.Stopwatch.Frequency;         // Timer tick count per second
            clock.Start();

            var deltaTime = 0.0f;
            var fpsTimer  = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();

            var fps       = 0.0;
            int fpsFrames = 0;

            SharpDX.Windows.RenderLoop.Run(form,
                                           () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFreq;

                #region FPS and title update
                fpsFrames++;
                if (fpsTimer.ElapsedMilliseconds > 1000)
                {
                    fps = 1000.0 * fpsFrames / fpsTimer.ElapsedMilliseconds;

                    // Update window title with FPS once every second
                    form.Text = string.Format("D3DRendering D3D 11.1 - FPS: {0:F2} ({1:F2}ms/frame)", fps, (float)fpsTimer.ElapsedMilliseconds / fpsFrames);

                    // Restart the FPS counter
                    fpsTimer.Reset();
                    fpsTimer.Start();
                    fpsFrames = 0;
                }
                #endregion

                // Execute rendering commends here...
                device11_1.ImmediateContext1.ClearRenderTargetView(renderTargetView, Color.Green);

                // Present the frame
                swapChain1.Present(0, PresentFlags.None, new PresentParameters());

                // Calculate the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFreq) - totalSeconds;
            });

            #endregion



            #region Cleanup Direct3D 11.1

            renderTargetView.Dispose();
            backBuffer.Dispose();
            swapChain1.Dispose();
            device11_1.Dispose();

            #endregion

            /*
             * Application.EnableVisualStyles();
             * Application.SetCompatibleTextRenderingDefault(false);
             * Application.Run(new Form1());
             */
        }
Пример #23
0
        static void Main()
        {
            #region d3d initialization
            // create winform
            Form1 form = new Form1();
            form.Text   = "D3D11.2Rendering";
            form.Width  = 800;
            form.Height = 600;

            // device & swapChain
            Device2    device;
            SwapChain1 swapChain;

            // First create a regular D3D11 device
            using (
                var device11 = new Device(
                    SharpDX.Direct3D.DriverType.Hardware,
                    DeviceCreationFlags.None,
                    new[] {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
            }))
            {
                // Query device for the Device1 interface (ID3D11Device1)
                device = device11.QueryInterfaceOrNull <Device2>();

                if (device == null)
                {
                    throw new NotSupportedException("SharpDX.Direct3D11.Device2 is not supported");
                }
            }


            // Rather than create a new DXGI Factory we should reuse
            // the one that has been used internally to create the device
            using (var dxgi = device.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = form.ClientSize.Width,
                            Height            = form.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = Scaling.Stretch,
                            SwapEffect        = SwapEffect.Discard,
                        };

                        swapChain = new SwapChain1(factory,
                                                   device,
                                                   form.Handle,
                                                   ref desc1,
                                                   new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                   // Restrict output to specific Output (monitor)
                                                   null);

                        swapChain.QueryInterfaceOrNull <SwapChain2>();
                    }

            // Create references to backBuffer and renderTargetView
            var backBuffer       = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var renderTargetView = new RenderTargetView(device, backBuffer);
            #endregion

            #region render loop

            // Create Clock and FPS counters
            var clock          = new System.Diagnostics.Stopwatch();
            var clockFrequency = (double)System.Diagnostics.Stopwatch.Frequency;
            clock.Start();
            var deltaTime = 0.0;
            var fpsTimer  = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();
            var fps       = 0.0;
            int fpsFrames = 0;

            RenderLoop.Run(form, () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFrequency;

                #region FPS and title update
                fpsFrames++;
                if (fpsTimer.ElapsedMilliseconds > 1000)
                {
                    fps = 1000.0 * fpsFrames / fpsTimer.ElapsedMilliseconds;

                    // Update window title with FPS once every second
                    form.Text = string.Format("D3D11.2Rendering - FPS: {0:F2} ({1:F2}ms/frame)", fps, (float)fpsTimer.ElapsedMilliseconds / fpsFrames);

                    // Restart the FPS counter
                    fpsTimer.Reset();
                    fpsTimer.Start();
                    fpsFrames = 0;
                }
                #endregion

                // clearcolor
                var lerpColor = SharpDX.Color.Lerp(Color.LightBlue, Color.DarkBlue, (float)(Math.Sin(totalSeconds) / 2.0 + 0.5));

                device.ImmediateContext.ClearRenderTargetView(renderTargetView, lerpColor);

                // rendering commands

                // Present the frams
                swapChain.Present(0, PresentFlags.None, new PresentParameters());

                // Determine the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFrequency) - totalSeconds;
            });
            #endregion

            #region d3d cleanup
            // release
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
            #endregion
        }
Пример #24
0
        static void Main()
        {
            // Enable object tracking

            #region Direct3D Initialization
            // Create the window to render to
            form.Text   = "D3DRendering - EmptyProject";
            form.Width  = 640;
            form.Height = 480;
            // Declare the device and swapChain vars
            Device    device;
            SwapChain swapChain;
            // Create the device and swapchain
            // First create a regular D3D11 device
            using (var device11 = new Device(
                       SharpDX.Direct3D.DriverType.Hardware,
                       DeviceCreationFlags.None,
                       new[] {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
            }))
            {
                // Query device for the Device1 interface (ID3D11Device1)
                device = device11.QueryInterfaceOrNull <Device1>();
                if (device == null)
                {
                    throw new NotSupportedException(
                              "SharpDX.Direct3D11.Device1 is not supported");
                }
            }// Rather than create a new DXGI Factory we reuse the
             // one that has been used internally to create the device
            using (var dxgi = device.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = form.ClientSize.Width,
                            Height            = form.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = Scaling.Stretch,
                            SwapEffect        = SwapEffect.Discard,
                        };
                        swapChain = new SwapChain1(factory,
                                                   device,
                                                   form.Handle,
                                                   ref desc1,
                                                   new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                   // Restrict output to specific Output (monitor)
                                                   adapter.Outputs[0]);
                    }

            // Create references for backBuffer and renderTargetView
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain,
                                                                 0);
            var renderTargetView = new RenderTargetView(device,
                                                        backBuffer);
            #endregion

            // Setup object debug names
            device.DebugName           = "The Device";
            swapChain.DebugName        = "The SwapChain";
            backBuffer.DebugName       = "The Backbuffer";
            renderTargetView.DebugName = "The RenderTargetView";

            #region Render loop
            // Create and run the render loop
            RenderLoop.Run(form, () =>
            {
                // Clear the render target with...
                var lerpColor = SharpDX.Color.Lerp(SharpDX.Color.White,
                                                   SharpDX.Color.DarkBlue,
                                                   (float)((timer.Time) / 10.0 % 1.0));
                device.ImmediateContext.ClearRenderTargetView(
                    renderTargetView,
                    lerpColor);

                // Execute rendering commands here...
                //...
                //I DO NOT HAVE ANY IDEA
                //...
                // Present the frame
                swapChain.Present(0, PresentFlags.RestrictToOutput);
            });
            #endregion

            #region Direct3D Cleanup
            // Release the device and any other resources created
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
            #endregion
        }