public PlotterGraphPaneEx()
        {
            memGraphics = new BackBuffer();

            InitializeComponent();

            this.Resize += new System.EventHandler(this.OnResizeForm);
            this.MouseDown += new MouseEventHandler(OnMouseDown);
            this.MouseUp += new MouseEventHandler(OnMouseUp);
            this.MouseMove += new MouseEventHandler(OnMouseMove);
        }
Exemplo n.º 2
0
        protected virtual void Initialize2D()
        {
#if DEBUG
            Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);
#else
            Factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded);
#endif
            using (var surface = BackBuffer.QueryInterface <Surface>())
            {
                RenderTarget = new RenderTarget(Factory2D, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            RenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;

            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            SceneColorBrush = new SolidColorBrush(RenderTarget, Color.White);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Copies any current content to the back buffer so that drawing should occur on the
        /// back buffer (instead of the fore-buffer). Calling draw methods without
        /// calling this may cause exceptions.
        /// </summary>
        /// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer
        /// where drawing will be taking place.</param>
        public void StartDrawing(bool preserve)
        {
            Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);

            if (Buffer != null && preserve && Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height)
            {
                Graphics g = Graphics.FromImage(backBuffer);
                g.DrawImageUnscaled(Buffer, 0, 0);
            }

            if (BackBuffer != null && BackBuffer != Buffer)
            {
                BackBuffer.Dispose();
            }
            BackBuffer = backBuffer;
            OnStartDrawing();
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public override void Destroy()
        {
            base.Destroy();

            lock (Renderer.Locker)
            {
                CanRender = false;

                _bloomEffect.Destroy();
                _ambientOcclusion.Destroy();

                RenderHandle = IntPtr.Zero;

                lock (Locker)
                {
                    LayerCollectors.Clear();
                }

                Constants.Dispose();

                RenderTarget2D?.Dispose();

                BackBuffer?.Dispose();
                Buffer0?.Dispose();
                Buffer1?.Dispose();
                Buffer2?.Dispose();
                Buffer3?.Dispose();

                BufferDownscaleHalf0?.Dispose();
                BufferDownscaleHalf1?.Dispose();
                BufferDownscaleQuarter0?.Dispose();
                BufferDownscaleQuarter1?.Dispose();

                DepthStencilBuffer?.Dispose();

                SwapChain?.Dispose();

                BackBuffer = null;
                Buffer0    = null;
                Buffer1    = null;
                Buffer2    = null;
                Buffer3    = null;
            }
        }
Exemplo n.º 5
0
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            if (RenderContext != null)
            {
                RenderContext.Dispose();
            }
            if (BackBuffer != null)
            {
                BackBuffer.Dispose();
            }
            if (DepthStencilBuffer != null)
            {
                DepthStencilBuffer.Dispose();
            }
            //if (Factory != null)
            //Factory.Dispose();
            if (swapChain != null)
            {
                swapChain.Dispose();
            }

            GraphicsObject[] created = CreatedObjects.ToArray();
            for (int i = 0; i < created.Length; i++)
            {
                if (!created[i].IsDisposed)
                {
                    Log.Warning("{0} was not disposed! Created at:\r\n{1}", created[i].GetType().Name, created[i].CreationStack);
                    created[i].Dispose();
                }
            }
            CreatedObjects.Clear();

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

            IsDisposed = true;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Resets the engine
        /// </summary>
        private void Reset()
        {
            // Set flag to prevent infinite loop of resets
            _isResetting = true;

            #region Cleanup
            Log.Info("Clearing Direct3D resources");
            BackBuffer.Dispose();
            DeviceLost?.Invoke();
            #endregion

            #region Wait
            // Wait in case the device isn't ready to be reset
            while (Device.TestCooperativeLevel() == ResultCode.DeviceLost)
            {
                Thread.Sleep(100);
                WinForms.Application.DoEvents();
            }

            // Catch internal driver errors
            var result = Device.TestCooperativeLevel();
            if (result != ResultCode.DeviceNotReset && result != ResultCode.Success)
            {
                throw new Direct3D9Exception(result);
            }
            #endregion

            #region Reset
            Log.Info("Resetting Direct3D device");
            Log.Info("Presentation parameters:\n" + PresentParams);
            Device.Reset(PresentParams);

            // Setup the default values for the Direct3D device and restore resources
            SetupTextureFiltering();
            RenderViewport = Device.Viewport;
            BackBuffer     = Device.GetBackBuffer(0, 0);
            DeviceReset?.Invoke();

            State.Reset();
            Performance.Reset();
            #endregion

            _isResetting = NeedsReset = false;
        }
Exemplo n.º 7
0
        public void Shutdown()
        {
            // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception.
            _swapChain?.SetFullscreenState(false, null);

            _alphaEnableBlendingState?.Dispose();
            _alphaEnableBlendingState = null;

            _alphaDisableBlendingState?.Dispose();
            _alphaDisableBlendingState = null;

            BackBuffer?.Dispose();
            BackBuffer = null;

            _depthDisabledStencilState?.Dispose();
            _depthDisabledStencilState = null;

            _rasterState?.Dispose();
            _rasterState = null;

            DepthStencilView?.Dispose();
            DepthStencilView = null;

            _depthStencilState?.Dispose();
            _depthStencilState = null;

            DepthStencilBuffer?.Dispose();
            DepthStencilBuffer = null;

            _renderTargetView?.Dispose();
            _renderTargetView = null;

            DeviceContext?.Dispose();
            DeviceContext = null;

            Device?.Dispose();
            Device = null;

            BackBuffer?.Dispose();
            BackBuffer = null;

            _swapChain?.Dispose();
            _swapChain = null;
        }
        public void UnloadDirect3D()
        {
            if (!Ready)
            {
                return;
            }

            TextureCache.Dispose();

            DefaultTextureView.Dispose();
            DefaultTexture.Dispose();
            SampleState.Dispose();
            DefaultEffect.Dispose();
            BackBufferView.Dispose();
            BackBuffer.Dispose();
            DepthBufferView.Dispose();
            DepthBuffer.Dispose();
            Device.Dispose();
        }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        private void InitializeD2D()
        {
            mFactory2D = new SharpDX.Direct2D1.Factory();
            using (var surface = BackBuffer.QueryInterface <DXGI.Surface>())
            {
                mRenderTarget2D = new RenderTarget(mFactory2D, surface, new RenderTargetProperties(new PixelFormat(DXGI.Format.Unknown, AlphaMode.Premultiplied)));
            }
            mRenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            mFactoryDWrite = new SharpDX.DirectWrite.Factory();

            SceneColorBrush = new SolidColorBrush(mRenderTarget2D, Color.White);

            // Initialize fonts
            foreach (eTextSize size in Enum.GetValues(typeof(eTextSize)))
            {
                mTextFormats.Add(size, new SharpDX.DirectWrite.TextFormat(mFactoryDWrite, "Arial", (int)size));
            }
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        protected override void RenderInternal()
        {
            var graphics = BackBuffer.Graphics;

            var t = DateTime.UtcNow.Millisecond / 1000.0;

            Color GetColor(int x, int y) => Color.FromArgb
            (
                byte.MaxValue,
                (byte)((double)x / BufferSize.Width * byte.MaxValue),
                (byte)((double)y / BufferSize.Height * byte.MaxValue),
                (byte)(Math.Sin(t * Math.PI) * byte.MaxValue)
            );

            Parallel.For(0, BackBuffer.Buffer.Length, index =>
            {
                BackBuffer.GetXY(index, out var x, out var y);
                BackBuffer.Buffer[index] = GetColor(x, y).ToArgb();
            });
Exemplo n.º 11
0
        /// <inheritdoc />
        protected override void RenderInternal(IEnumerable <IPrimitive> primitives)
        {
            // clear buffers
            BackBuffer.Clear(Color.Black);

            // render primitives
            RenderPrimitives(primitives);

            // draw fps
            BackBuffer.Graphics.DrawString(FpsCounter.FpsString, FontConsolas12, Brushes.Red, 0, 0);

            // flush and swap buffers
            BufferedGraphics.Graphics.DrawImage(
                BackBuffer.Bitmap,
                new RectangleF(PointF.Empty, HostSize),
                new RectangleF(new PointF(-0.5f, -0.5f), BufferSize),
                GraphicsUnit.Pixel);
            BufferedGraphics.Render(GraphicsHostDeviceContext);
        }
Exemplo n.º 12
0
        private void FullRender()
        {
            if (BackBuffer == null)
            {
                return;
            }

            if (_CurrentTable == null || _CurrentPalette == null || _CurrentDefiniton == null)
            {
                Graphics.FromImage(BackBuffer).Clear(Color.Black);
                return;
            }

            BitmapData data = BackBuffer.LockBits(new Rectangle(0, 0, BackBuffer.Width, BackBuffer.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            for (int i = 0; i < _CurrentWorld.Height; i++)
            {
                for (int j = 0; j < _CurrentWorld.Width; j++)
                {
                    int   tileValue    = CurrentWorld.LevelData[j, i];
                    int   PaletteIndex = tileValue / 0x40;
                    Block b            = CurrentDefiniton[tileValue];
                    RenderTile(_CurrentTable[b[0, 0]], j * 16, i * 16, PaletteIndex, data);
                    RenderTile(_CurrentTable[b[0, 1]], j * 16, i * 16 + 8, PaletteIndex, data);
                    RenderTile(_CurrentTable[b[1, 0]], j * 16 + 8, i * 16, PaletteIndex, data);
                    RenderTile(_CurrentTable[b[1, 1]], j * 16 + 8, i * 16 + 8, PaletteIndex, data);

                    if (_ShowPointers)
                    {
                        WorldPointer p = CurrentWorld.Pointers.Find(pt => (pt.X == j && pt.Y == i));
                        if (p != null)
                        {
                            RenderSpecialTileAlpha(_SpecialTable[0xA2], j * 16, i * 16, 5, data, 1.0);
                            RenderSpecialTileAlpha(_SpecialTable[0xB2], j * 16, i * 16 + 8, 5, data, 1.0);
                            RenderSpecialTileAlpha(_SpecialTable[0xA3], j * 16 + 8, i * 16, 5, data, 1.0);
                            RenderSpecialTileAlpha(_SpecialTable[0xB3], j * 16 + 8, i * 16 + 8, 5, data, 1.0);
                        }
                    }
                }
            }
            BackBuffer.UnlockBits(data);
        }
Exemplo n.º 13
0
        protected override void WindowResize(int width, int height)
        {
            base.WindowResize(width, height);


            Device.ImmediateContext.ClearState();

            _renderTarget2D.Dispose();
            BackBuffer.Dispose();
            RenderView.Dispose();
            _surface?.Dispose();

            SwapChain.ResizeBuffers(1, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

            BackBuffer      = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderView      = new RenderTargetView(Device, BackBuffer);
            _surface        = BackBuffer.QueryInterface <Surface>();
            _renderTarget2D = new RenderTarget(Factory2D, _surface,
                                               new RenderTargetProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)));
        }
Exemplo n.º 14
0
        public void Render()
        {
            lock (_updateLock)
            {
                FpsCounter.StartFrame();
                Task.Delay(10).Wait();
                var t = DateTime.UtcNow.Millisecond / 1000.0;
                Color GetColor(int x, int y) => Color.FromArgb
                (
                    byte.MaxValue,
                    (byte)((double)x / _bufferSize.Width * byte.MaxValue),
                    (byte)((double)y / _bufferSize.Height * byte.MaxValue),
                    (byte)(Math.Sin(t * Math.PI) * byte.MaxValue)
                );

                Parallel.For(0, BackBuffer.Buffer.Length, index =>
                {
                    BackBuffer.GetXY(index, out var x, out var y);
                    BackBuffer.Buffer[index] = GetColor(x, y).ToArgb();
                });
Exemplo n.º 15
0
        public void ExitAndRelease()
        {
            try
            {
                D2Ddevice.ImmediateContext.ClearState(); //设备即时上下文清理状态
                D2Ddevice.ImmediateContext.Flush();      //设备即时上下文刷新
                D2Ddevice.Dispose();                     //设备销毁
                D2Ddevice.Dispose();                     //设备销毁
                SwapChain.Dispose();                     //基础交换链销毁
                DXGIFactory.Dispose();                   //基础工厂销毁


                BackBufferView.Dispose();  //后备缓冲视图销毁
                BackBuffer.Dispose();      //后备缓冲销毁
            }
            catch (Exception)
            {
                return;
            }
        }
Exemplo n.º 16
0
        protected virtual void CreateResource()
        {
            //***
            using (var surface = BackBuffer.QueryInterface<DXGI.Surface>())
            {

                renderTarget = new D2D.RenderTarget(DirectX.Factory2D, surface, new D2D.RenderTargetProperties()
                {
                    PixelFormat = new D2D.PixelFormat(DXGI.Format.Unknown, D2D.AlphaMode.Premultiplied),

                });

            }
            renderTarget.AntialiasMode = D2D.AntialiasMode.PerPrimitive;
            
            /***/

            /***
            using (var surface = BackBuffer.QueryInterface<DXGI.Surface>())
            {
                deviceContext = new D2D.DeviceContext(surface, new SharpDX.Direct2D1.CreationProperties()
                {
                    DebugLevel = SharpDX.Direct2D1.DebugLevel.Information,
                    Options = SharpDX.Direct2D1.DeviceContextOptions.None,
                    ThreadingMode = SharpDX.Direct2D1.ThreadingMode.SingleThreaded
                }
                );
                bitmap = new SharpDX.Direct2D1.Bitmap1(deviceContext, surface, new SharpDX.Direct2D1.BitmapProperties1()
                {
                    BitmapOptions = SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw,
                    PixelFormat = new SharpDX.Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                    DpiX = (float)Dpi,
                    DpiY = (float)Dpi
                }
                );
                deviceContext.Target = bitmap;
            }
            
            deviceContext.AntialiasMode = D2D.AntialiasMode.PerPrimitive;
            /***/
        }
Exemplo n.º 17
0
        public Win32VtkRenderingSurface(IntPtr windowId, bool offscreen)
        {
            _imageBuffer   = new BitmapBuffer(PixelFormat.Format32bppRgb);
            _overlayBuffer = new BitmapBuffer(PixelFormat.Format32bppArgb);
            _finalBuffer   = new BackBuffer();

            _vtkRenderer = new vtkRenderer();
            _vtkRenderer.SetBackground(0.0f, 0.0f, 0.0f);

            _vtkRenderWindow = new vtkWin32OpenGLRenderWindow();
            _vtkRenderWindow.OffScreenRenderingOn();
            _vtkRenderWindow.DoubleBufferOff();
            _vtkRenderWindow.EraseOn();
            _vtkRenderWindow.SwapBuffersOff();
            _vtkRenderWindow.SetDesiredUpdateRate(_dynamicFrameRate);
            _vtkRenderWindow.AddRenderer(_vtkRenderer);

            _dynamicRenderEventPublisher = !offscreen ? new DelayedEventPublisher((s, e) => Render(true, null)) : null;

            WindowID = windowId;
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (Buffer != BackBuffer && Buffer != null)
                {
                    Buffer.Dispose();
                    Buffer = null;
                }
                if (BackBuffer != null)
                {
                    BackBuffer.Dispose();
                    BackBuffer = null;
                }

                BufferEnvelope  = null;
                BufferRectangle = Rectangle.Empty;
                IsInitialized   = false;
            }
            base.Dispose(disposing);
        }
		public Win32VtkRenderingSurface(IntPtr windowId, bool offscreen)
		{
			_imageBuffer = new BitmapBuffer(PixelFormat.Format32bppRgb);
			_overlayBuffer = new BitmapBuffer(PixelFormat.Format32bppArgb);
			_finalBuffer = new BackBuffer();

			_vtkRenderer = new vtkRenderer();
			_vtkRenderer.SetBackground(0.0f, 0.0f, 0.0f);

			_vtkRenderWindow = new vtkWin32OpenGLRenderWindow();
			_vtkRenderWindow.OffScreenRenderingOn();
			_vtkRenderWindow.DoubleBufferOff();
			_vtkRenderWindow.EraseOn();
			_vtkRenderWindow.SwapBuffersOff();
			_vtkRenderWindow.SetDesiredUpdateRate(_dynamicFrameRate);
			_vtkRenderWindow.AddRenderer(_vtkRenderer);

			_dynamicRenderEventPublisher = !offscreen ? new DelayedEventPublisher((s, e) => Render(true, null)) : null;

			WindowID = windowId;
		}
Exemplo n.º 20
0
        /// <summary>
        /// Updates the backbuffer
        /// </summary>
        public void UpdateBackBuffer()
        {
            if (BackBuffer != null)
            {
                BackBuffer.Dispose();
            }

            Size size = GetSize();

            BackBuffer = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppPArgb);
            Graphics gfx = Graphics.FromImage(BackBuffer);

            gfx.Clear(BackColor);
            if (_useHatch)
            {
                using (HatchBrush brush = new HatchBrush(_hatchStyle, _hatchForeColor, _hatchBackColor))
                {
                    gfx.FillRectangle(brush, new Rectangle(Point.Empty, size));
                }
            }

            Point origin = GetOrigin();

            if (_image != null && !UseCanvas)
            {
                gfx.DrawImage(ImageAlpha != 1 ? BitmapTransparency(_image, ImageAlpha) : _image, origin);
            }

            OnAfterDrawOnBackbuffer(ref gfx, ref origin);

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

            // Flip to screen
            Invalidate();
        }
Exemplo n.º 21
0
        /// <summary>
        /// On control paint
        /// </summary>
        protected override void OnPaint(PaintEventArgs e)
        {
            if (!Enabled || BackBuffer == null)
            {
                e.Graphics.FillRectangle(SystemBrushes.ControlDark, ClientRectangle);
                return;
            }

            Rectangle src = new Rectangle(0, 0, BackBuffer.Width, BackBuffer.Height);

            using (Bitmap image = BackBuffer.Clone(src, BackBuffer.PixelFormat))
            {
                Point srcPoint = GetTranslatePoint(Point.Empty);
                Size  size     = UseCanvas && _canvas != Size.Empty ? _canvas : _image != null ? _image.Size : BackBuffer.Size;
                AutoScrollMinSize            = new Size(size.Width * _scale, size.Height * _scale);
                e.Graphics.PixelOffsetMode   = PixelOffsetMode.Half;
                e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                e.Graphics.ScaleTransform(_scale, _scale);
                e.Graphics.DrawImage(image, ClientRectangle, srcPoint.X, srcPoint.Y, ClientSize.Width, ClientSize.Height, GraphicsUnit.Pixel);
                e.Graphics.ResetTransform();
                OnDrawAfterOnPaint(ref e);
            }
        }
Exemplo n.º 22
0
    void OnAudioFilterRead(float[] bufferData, int bufferChannels)
    {
        if (!IsReady || !_isPlaying)
        {
            return;
        }
        double samplesPerTick = _sampleRate * 60.0F / bpm * 4.0F / signatureLo;
        double sample         = AudioSettings.dspTime * _sampleRate;

        if (_newPercentage > -1)
        {
            UpdatePercentage();
            return;
        }

        if (isMuted)
        {
            int dataLeft = bufferData.Length;
            while (dataLeft > 0)
            {
                double newSample = sample + dataLeft;
                if (_nextTick < newSample)
                {
                    dataLeft   = (int)(newSample - _nextTick);
                    _nextTick += samplesPerTick;
                    if (++_currentStep > signatureLo)
                    {
                        _currentStep = 1;
                    }
                    _progress = _currentStep * samplesPerTick;
                    if (sequence[_currentStep - 1])
                    {
                        _index = 0;
                        if (OnBeat != null)
                        {
                            _fireBeatEvent++;
                        }
                    }
                    else
                    {
                        _index = -1;
                    }
                    if (OnAnyStep != null)
                    {
                        _fireAnyStepEvent++;
                    }
                }
                else
                {
                    break;
                }
            }
        }
        else
        {
            for (int dataIndex = 0; dataIndex < bufferData.Length / bufferChannels; dataIndex++)
            {
                if (_activeBackBuffers != null)
                {
                    for (int backBufferIndex = 0; backBufferIndex < _activeBackBuffers.Count; backBufferIndex++)
                    {
                        BackBuffer bb = _activeBackBuffers[backBufferIndex];

                        int clipChannel   = 0;
                        int sourceChannel = 0;
                        while (sourceChannel < bufferChannels)
                        {
                            bufferData[dataIndex * bufferChannels + sourceChannel] += bb.data[bb.index * _clipChannels + clipChannel];

                            sourceChannel++;
                            clipChannel++;
                            if (clipChannel == _clipChannels - 1)
                            {
                                clipChannel = 0;
                            }
                        }

                        bb.index++;
                        if (bb.index >= bb.data.Length / bufferChannels)
                        {
                            ReleaseBackBuffer(backBufferIndex);
                            backBufferIndex--;
                            if (log)
                            {
                                print("BackBuffer recycled. Total: " + _activeBackBuffers.Count);
                            }
                        }
                    }
                }

                if (_index != -1)
                {
                    int clipChannel   = 0;
                    int sourceChannel = 0;
                    while (sourceChannel < bufferChannels)
                    {
                        bufferData[dataIndex * bufferChannels + sourceChannel] += _clipData[_index * _clipChannels + clipChannel];

                        sourceChannel++;
                        clipChannel++;
                        if (clipChannel == _clipChannels - 1)
                        {
                            clipChannel = 0;
                        }
                    }

                    _index++;
                    if (_index >= _clipData.Length / _clipChannels)
                    {
                        _index = -1;
                    }
                }

                _progress = _currentStep * samplesPerTick + dataIndex;

                if (sample + dataIndex >= _nextTick)
                {
                    //Refactored to increase readability.
                    AddToBackBuffer(bufferChannels);

                    _nextTick += samplesPerTick;
                    if (++_currentStep > signatureLo)
                    {
                        _currentStep = 1;
                    }
                    _progress = _currentStep * samplesPerTick;
                    if (sequence[_currentStep - 1])
                    {
                        _index = 0;
                        if (OnBeat != null)
                        {
                            _fireBeatEvent++;
                        }
                    }
                    else
                    {
                        _index = -1;
                    }
                    if (OnAnyStep != null)
                    {
                        _fireAnyStepEvent++;
                    }
                    if (log)
                    {
                        Debug.Log("Tick: " + _currentStep + " (%" + GetPercentage() + ")");
                    }
                }
            }
        }
    }
Exemplo n.º 23
0
        /// <summary>
        /// Resizes the GBuffer.
        /// </summary>
        internal void Resize(Device device)
        {
            UpdateProjectionMatrix();
            RebuildFrustum(_frustumCulling);

            CanRender = false;

            var newWidth  = Math.Max(1, (int)_viewportSize.x);
            var newHeight = Math.Max(1, (int)_viewportSize.y);

            RenderTarget2D?.Dispose();
            RenderTarget2D = null;

            Renderer.Context2D.Target = null;

            _surface?.Dispose();
            BackBuffer?.Dispose();
            Buffer0?.Dispose();
            Buffer1?.Dispose();
            Buffer2?.Dispose();
            Buffer3?.Dispose();
            DepthStencilBuffer?.Dispose();

            Viewport = new ViewportF(0, 0, ViewportSize.x, ViewportSize.y);

            try
            {
                SwapChain.ResizeBuffers(RenderConstants.FrameCount, newWidth, newHeight,
                                        RenderConstants.BackBufferFormat, SwapChainFlags.None);
            }
            catch (SharpDXException e)
            {
                Logger.Error(e);
                throw;
            }

            var backBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0);

            BackBuffer = new Texture(backBufferTexture);

            Buffer0 = CreateCameraBuffer("Buffer0", 1f, RenderConstants.BackBufferFormat);
            Buffer1 = CreateCameraBuffer("Buffer1", 1f, Format.R8G8B8A8_UNorm);
            Buffer2 = CreateCameraBuffer("Buffer2", 1f, Format.R16G16B16A16_Float);
            Buffer3 = CreateCameraBuffer("Buffer3", 1f, Format.R8G8B8A8_UNorm);
            BufferDownscaleHalf0    = CreateCameraBuffer("BufferDownsampleHalf0", 1 / 2f, Format.R8G8B8A8_UNorm);
            BufferDownscaleHalf1    = CreateCameraBuffer("BufferDownsampleHalf1", 1 / 2f, Format.R8G8B8A8_UNorm);
            BufferDownscaleQuarter0 = CreateCameraBuffer("BufferDownsampleQuarter0", 1 / 4f, Format.R8G8B8A8_UNorm);
            BufferDownscaleQuarter1 = CreateCameraBuffer("BufferDownsampleQuarter1", 1 / 4f, Format.R8G8B8A8_UNorm);

            var depthStencilBuffer = new Texture2D(Renderer.Device, new Texture2DDescription
            {
                Format            = Format.R24G8_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = newWidth,
                Height            = newHeight,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            DepthStencilBuffer = new Texture(depthStencilBuffer, new DepthStencilViewDescription
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D
            }, new ShaderResourceViewDescription
            {
                Format    = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = -1
                }
            });

            _surface           = BackBuffer.QueryInterface <Surface>();
            _surface.DebugName = "BackBufferSurface";

            try
            {
                RenderTarget2D = new Bitmap1(Renderer.Context2D, _surface,
                                             new BitmapProperties1(new PixelFormat(_surface.Description.Format, AlphaMode.Premultiplied), 96,
                                                                   96, BitmapOptions.Target | BitmapOptions.CannotDraw));
            }
            catch (Exception)
            {
                _surface.Dispose();
                RenderTarget2D?.Dispose();
                Logger.Info("An exception occured while creating the GUI surface render target.");
                throw;
            }

            lock (Locker)
            {
                foreach (var collector in LayerCollectors)
                {
                    collector.Target = RenderTarget2D;
                }
            }

            lock (PostEffectsLocker)
            {
                foreach (var effect in PostEffects)
                {
                    effect.UpdateSize(this);
                }
            }

            var cb = Constants;

            cb.Data.ScreenParams.X = newWidth;
            cb.Data.ScreenParams.Y = newHeight;
            cb.Data.ScreenParams.Z = AspectRatio;
            cb.Data.ScreenParams.W = FieldOfView * 0.5f / newHeight;

            NeedsResize = false;
            CanRender   = true;
            //Logger.Trace("Camera resized.");
        }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new Configurator class.
 /// </summary>
 /// <param name="backbuffer">The BackBuffer.</param>
 /// <param name="gameInstance">The GameInstance.</param>
 /// <param name="renderTarget">The RenderTarget.</param>
 public Configurator(BackBuffer backbuffer, Game gameInstance, RenderTarget renderTarget)
     : this(60, backbuffer, gameInstance, renderTarget)
 {
 }
Exemplo n.º 25
0
 public virtual void Dispose()
 {
     BackBuffer?.Dispose();
     BackBuffer = null;
     Resource.Dispose();
 }
Exemplo n.º 26
0
 private void DisposeBuffers()
 {
     BackBuffer.Dispose();
     BackBuffer = default;
 }
Exemplo n.º 27
0
        protected override IResult Execute(CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(FormulaFile))
            {
                WriteHelp();
                return(Result.Success);
            }

            Log.Write("Preparing...");

            var formulaFileName = Path.GetFileName(FormulaFile);
            var directory       = new FileSystemStore(Path.GetDirectoryName(FormulaFile) ?? throw new FileNotFoundException("Unable to access formula file", FormulaFile));

            var size = Resolution <= 0 ? 512 : Resolution;

            using (var backBuffer = new BackBuffer(size, size))
            {
                using var bitmap      = new Bitmap(backBuffer.Width, backBuffer.Height, PixelFormat.Format32bppArgb);
                using var diagnostics = new DiagnosticsWindow();
                using var preview     = new PreviewControl(backBuffer, bitmap);

                var formula  = AttractorModel.FromJson(directory.Open(formulaFileName).AsText());
                var iterator = new Iterator(backBuffer).Configure(config => config
                                                                  .Statistics(s => s.SetEnabled(Trace))
                                                                  .PerformanceCounter(s => s.SetEnabled(Trace))
                                                                  .OnFinalize(WriteHeader)
                                                                  .Log(Log));

                iterator.AllowMultithreading = !ForceSingleThreading;

                var n = 0;

                using (var bitmapG = Graphics.FromImage(bitmap))
                {
                    bitmapG.FillRectangle(Brushes.Black, 0, 0, bitmap.Width, bitmap.Height);
                }

                preview.SampleCallback = (sample, stats) =>
                {
                    diagnostics.Invoke(new Action(
                                           () =>
                    {
                        diagnostics.brightness.Series[0].Points.AddXY(iterator.GetCurrentDensity(), stats.AverageBrightness);
                        diagnostics.peakPoint.Series[0].Points.AddXY(iterator.GetCurrentDensity(), stats.HighAccumulator);
                        diagnostics.peakPoint.Series[1].Points.AddXY(iterator.GetCurrentDensity(), stats.LowAccumulator);
                    }));
                };

                preview.RenderCallback = () =>
                {
                    var cd        = iterator.GetCurrentDensity();
                    var increment = cd < 10 ? 1 : GetDensity(++n) / 10.0;
                    // ReSharper disable once MethodSupportsCancellation
                    iterator.Iterate(formula, increment);
                    _totalDensity = iterator.GetCurrentDensity();
                };

                preview.Dock = DockStyle.Fill;
                diagnostics.histogramPanel.Controls.Add(preview);

                var thread = new Thread(() => preview.RenderLoop(() => !preview.Visible))
                {
                    IsBackground = true
                };

                diagnostics.Shown += (o, e) => thread.Start();
                diagnostics.ShowDialog();
            }

            return(Result.Success);
        }
Exemplo n.º 28
0
        public override void InitRenderTarget()
        {
            BackBuffer?.Dispose();
            RenderTargetViewRef?.Dispose();
            DepthStencilSRVRef?.Dispose();
            ZBuffer?.Dispose();
            DepthStencilViewRef?.Dispose();
            RenderTarget2D?.Dispose();

            SwapChainRef.ResizeBuffers(1, Width, Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

            using (Surface surface = SwapChainRef.GetBackBuffer <Surface>(0)) {
                RenderTarget2D = new RenderTarget(Factory2D, surface, RenderTarget2DProperites);
            }

            RenderTarget2D.AntialiasMode     = AntialiasMode.PerPrimitive;
            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            BackBuffer                    = SwapChainRef.GetBackBuffer <Texture2D>(0);
            BackBuffer.DebugName          = "BackBuffer";
            RenderTargetViewRef           = new RenderTargetView(DeviceRef, BackBuffer);
            RenderTargetViewRef.DebugName = "BackBufferRenderTargetView";

            ZBufferTextureDescription.Width  = Width;
            ZBufferTextureDescription.Height = Height;
            ZBuffer           = new Texture2D(DeviceRef, ZBufferTextureDescription);
            ZBuffer.DebugName = "ZBuffer";

            DepthStencilViewRef = new DepthStencilView(DeviceRef, ZBuffer, new DepthStencilViewDescription {
                Format    = Format.D32_Float,
                Dimension = MSamplesCount > 1 ? DepthStencilViewDimension.Texture2DMultisampled
                    : DepthStencilViewDimension.Texture2D,
                Flags = DepthStencilViewFlags.None,
            });
            DepthStencilViewRef.DebugName = "ZBufferDepthStencilView";

            ShaderResourceViewDescription SRVDesc = new ShaderResourceViewDescription()
            {
                Format = Format.R32_Float,
            };

            if (MSamplesCount > 1)
            {
                SRVDesc.Dimension   = ShaderResourceViewDimension.Texture2DMultisampled;
                SRVDesc.Texture2DMS = new ShaderResourceViewDescription.Texture2DMultisampledResource();
            }
            else
            {
                SRVDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                SRVDesc.Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MostDetailedMip = 0,
                    MipLevels       = 1,
                };
            }

            DepthStencilSRVRef           = new ShaderResourceView(DeviceRef, ZBuffer, SRVDesc);
            DepthStencilSRVRef.DebugName = "ZBufferDepthStencilSRV";

            SetUpViewport();
            OnInitRenderTarget?.Invoke();
        }
Exemplo n.º 29
0
        public DX11(RenderForm form, CoreSettings coreSettings)
        {
            _form = form;
            sw    = Stopwatch.StartNew();
            LoadedTexturesByName = new Dictionary <string, ShaderResourceView>();
            LoadedTexturesByPtrs = new Dictionary <IntPtr, ShaderResourceView>();

            var swapChainDesc = new SwapChainDescription
            {
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                BufferCount       = 1,
                IsWindowed        = true,
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
                SampleDescription = new SampleDescription(1, 0),
                ModeDescription   = new ModeDescription
                {
                    Format           = Format.R8G8B8A8_UNorm,
                    Width            = form.Width,
                    Height           = form.Height,
                    Scaling          = DisplayModeScaling.Unspecified,
                    RefreshRate      = new Rational(60, 1),
                    ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                }
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None,
                                       new[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_0 }, swapChainDesc, out var device,
                                       out var swapChain);

            D11Device     = device;
            DeviceContext = device.ImmediateContext;
            _swapChain    = swapChain;

            factory = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);
            BackBuffer       = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            RenderTargetView = new RenderTargetView(device, BackBuffer);

            using (new PerformanceTimer("Init ImGuiRender"))
            {
                ImGuiRender = new ImGuiRender(this, form, coreSettings);
            }

            using (new PerformanceTimer("Init SpriteRender"))
            {
                SpritesRender = new SpritesRender(this, form, coreSettings);
            }

            InitStates();

            form.UserResized += (sender, args) =>
            {
                RenderTargetView?.Dispose();
                BackBuffer.Dispose();

                swapChain.ResizeBuffers(1, form.Width, form.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);
                BackBuffer       = Resource.FromSwapChain <Texture2D>(swapChain, 0);
                RenderTargetView = new RenderTargetView(device, BackBuffer);
                ImGuiRender.Resize(form.Bounds);
                ImGuiRender.UpdateConstantBuffer();
                SpritesRender.ResizeConstBuffer(BackBuffer.Description);
                var descp = BackBuffer.Description;
                Viewport.Height = form.Height;
                Viewport.Width  = form.Width;
                DeviceContext.Rasterizer.SetViewport(Viewport);
                DeviceContext.OutputMerger.SetRenderTargets(RenderTargetView);
            };

            ImGuiDebug     = new DebugInformation("ImGui");
            SpritesDebug   = new DebugInformation("Sprites");
            SwapchainDebug = new DebugInformation("Swapchain");

            // Core.DebugInformations.Add(ImGuiDebug);
            // Core.DebugInformations.Add(ImGuiInputDebug);
            // Core.DebugInformations.Add(SpritesDebug);
            // Core.DebugInformations.Add(SwapchainDebug);
        }
		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (_dynamicRenderEventPublisher != null)
				{
					_dynamicRenderEventPublisher.Cancel();
					_dynamicRenderEventPublisher.Dispose();
					_dynamicRenderEventPublisher = null;
				}

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

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

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

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

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

				if (_finalBuffer != null)
				{
					_finalBuffer.Dispose();
					_finalBuffer = null;
				}
			}
		}
Exemplo n.º 31
0
        /// <summary>
        /// is called when the <see cref="WinControl"/> has changed his size.
        /// </summary>
        /// <param name="width">the new width of the Wincontrol</param>
        /// <param name="height">the new height of the Wincontrol</param>

        protected virtual void OnViewPortChanged(int width, int height)
        {
            //if (FirstViewPortChanged)
            //{ FirstViewPortChanged = false;
            //    OnCreated();
            //    if (this._RenderMode == Mode.Allways)
            //        SetTimer();
            //}
            //    return;
            //CheckError();
            if ((width == 0) || (height == 0))
            {
                return;
            }
            MakeCurrent();
            Matrix old = EyeMatrix(new Size((int)ViewPort.Width, (int)ViewPort.Height), FieldOfView).invert();
            double Fa  = ViewPort.Width / (float)width;
            double Fb  = ViewPort.Height / (float)height;

            ViewPort = new Rectangle(0, 0, width, height);
            ShadowFBO.InitForDepth(ShadowSetting.Width, ShadowSetting.Height);
            CheckError();
            Matrix New = EyeMatrix(new Size(width, height), FieldOfView);
            Matrix M   = ((Matrix.LookAt(Camera.Position, Camera.Position + Camera.Direction, Camera.UpVector)));//* Matrix.Scale(PerspektiveFactor, PerspektiveFactor, PerspektiveFactor));

            if (FieldOfView == 0)
            {
                Fa = 1; Fb = 1;
            }
            ProjectionMatrix = Matrix.Scale(Fa, Fb, 1) * ProjectionMatrix * M.invert() * old * New * M;

            Camera.MakeConsistent();
            if (FirstViewPortChanged)
            {
                Camera.setDefZoom();
                FirstViewPortChanged = false;
                Shader = SmallShader;



                OnCreated();
                SizeChanged();
                if (this._RenderMode == Mode.Allways)
                {
                    SetTimer();
                }
            }

            try
            {
                if (ForegroundDrawEnable)
                {
                    BackBuffer.Init(width, height);
                    RefreshBackGround();
                    CopyFromBackGround();
                }
            }
            catch (System.Exception)
            {
                _ForegroundDrawEnable = false;
            }

            CheckError();
        }
Exemplo n.º 32
0
    void ReleaseBackBuffer(BackBuffer bb)
    {
        _activeBackBuffers.Remove(bb);
        bb.ClearData();

        if (_backBufferPool == null) _backBufferPool = new List<BackBuffer>();
        _backBufferPool.Add(bb);
    }
Exemplo n.º 33
0
    BackBuffer BackBufferFactory()
    {
        BackBuffer bb = null;

        if (_activeBackBuffers == null && maxBackBufferSize > 0 && increaseBackBufferBy > 0) _activeBackBuffers = new List<BackBuffer>(increaseBackBufferBy);
        if (_activeBackBuffers != null && _activeBackBuffers.Count < maxBackBufferSize)
        {
            if (_activeBackBuffers.Count == _activeBackBuffers.Capacity)
            {
                int newCap = _activeBackBuffers.Capacity + increaseBackBufferBy;
                if (newCap > maxBackBufferSize) newCap = maxBackBufferSize;
                _activeBackBuffers.Capacity = newCap;
            }

            if (_backBufferPool != null && _backBufferPool.Count > 0)
            {
                bb = _backBufferPool[0];
                _backBufferPool.RemoveAt(0);
            }
            else
            {
                bb = new BackBuffer();
            }

            _activeBackBuffers.Add(bb);
        }

        return bb;
    }