/// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="BackBuffer">Буффер на который будем рисовать, наш холст</param>
 /// <param name="Width">Ширина области в которую будем рисовать</param>
 /// <param name="Height">Высота объласти в которую будем рисовать</param>
 public TextWirter(SharpDX.Direct3D11.Texture2D BackBuffer, int Width, int Height)
 {
     _width = Width;
     _heght = Height;
     _sw    = new Stopwatch();
     _sw.Start();
     _Factory2D = new SharpDX.Direct2D1.Factory();
     using (var surface = BackBuffer.QueryInterface <Surface>())
     {
         _RenderTarget2D = new RenderTarget(_Factory2D, surface,
                                            new RenderTargetProperties(
                                                new PixelFormat(
                                                    Format.R8G8B8A8_UNorm,
                                                    AlphaMode.Premultiplied)));
     }
     _RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
     _FactoryDWrite   = new SharpDX.DirectWrite.Factory();
     _SceneColorBrush = new SolidColorBrush(_RenderTarget2D, Color.White);
     // Initialize a TextFormat
     _TextFormat = new TextFormat(_FactoryDWrite, "Calibri", 14)
     {
         TextAlignment      = TextAlignment.Leading,
         ParagraphAlignment = ParagraphAlignment.Near
     };
     _RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;
     // Initialize a TextLayout
     _TextLayout = new TextLayout(_FactoryDWrite, "SharpDX D2D1 - DWrite", _TextFormat, Width, Height);
 }
예제 #2
0
        private void Form1_Load(object sender, EventArgs e)
        {
            device   = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            c_device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_1);
            factory  = new SharpDX.DXGI.Factory1();

            int width  = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
            int height = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;

            target = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // creating CPU-accessible texture resource
            SharpDX.Direct3D11.Texture2DDescription texdes = new SharpDX.Direct3D11.Texture2DDescription();
            texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            texdes.Format                    = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            texdes.Height                    = height;
            texdes.Width                     = width;
            texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.Shared;
            texdes.MipLevels                 = 1;
            texdes.ArraySize                 = 1;
            texdes.SampleDescription.Count   = 1;
            texdes.SampleDescription.Quality = 0;
            texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;

            screenTexture        = new SharpDX.Direct3D11.Texture2D(c_device, texdes);
            sharedResourceHandle = screenTexture.QueryInterface <SharpDX.DXGI.Resource>().SharedHandle;
            sharedTexture        = device.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedResourceHandle);


            output           = new SharpDX.DXGI.Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
            duplicatedOutput = output.DuplicateOutput(c_device);
        }
예제 #3
0
        private IntPtr GetSharedHandle(SharpDX.Direct3D11.Texture2D Texture)
        {
            SharpDX.DXGI.Resource resource = Texture.QueryInterface <SharpDX.DXGI.Resource>();
            IntPtr result = resource.SharedHandle;

            resource.Dispose();
            return(result);
        }
예제 #4
0
        private void dislpayTimer_Tick(object sender, EventArgs ev)
        {
            // duplicate output stuff
            SharpDX.DXGI.Resource screenResource = null;
            SharpDX.DataStream    dataStream;
            SharpDX.DXGI.Surface  screenSurface;

            try
            {
                SharpDX.DXGI.OutputDuplicateFrameInformation duplicateFrameInformation;
                duplicatedOutput.AcquireNextFrame(1000, out duplicateFrameInformation, out screenResource);
            }
            catch (SharpDX.SharpDXException e)
            {
                if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                {
                    // keep retrying
                    return;
                }
                else
                {
                    throw e;
                }
            }

            // copy resource into memory that can be accessed by the CPU
            c_device.ImmediateContext.CopyResource(screenResource.QueryInterface <SharpDX.Direct3D11.Resource>(), screenTexture);
            // cast from texture to surface, so we can access its bytes
            screenSurface = screenTexture.QueryInterface <SharpDX.DXGI.Surface>();

            // map the resource to access it
            screenSurface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream);

            getImageFromDXStream(dataStream);

            captureBox.Image = target;

            // free resources
            dataStream.Close();
            screenSurface.Unmap();
            screenSurface.Dispose();
            screenResource.Dispose();
            duplicatedOutput.ReleaseFrame();

            // print how many frames we could process within the last second
            Console.WriteLine("fps: {0}", 1f / sw.Elapsed.TotalSeconds);
            sw.Reset();
            sw.Start();
        }
예제 #5
0
        public BackBuffer(Dx10Device device10, Dx11ChainedDevice device11)
        {
            try
            {
                _device10 = device10;
                _device11 = device11;

                _backBuffer = Resource.FromSwapChain <Texture2D>(device11.SwapChain, 0);
                _renderView = new RenderTargetView(device11.Device, _backBuffer);

                Texture2DDescription descriptor = _backBuffer.Description;
                {
                    descriptor.MipLevels         = 1;
                    descriptor.ArraySize         = 1;
                    descriptor.Format            = Format.B8G8R8A8_UNorm;
                    descriptor.SampleDescription = new SampleDescription(1, 0);
                    descriptor.Usage             = SharpDX.Direct3D11.ResourceUsage.Default;
                    descriptor.BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource;
                    descriptor.CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None;
                    descriptor.OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex;
                };

                _textureD3D11 = new Texture2D(device11.Device, descriptor);

                _factory2D = new Factory(FactoryType.MultiThreaded);

                using (SharpDX.DXGI.Resource sharedResource = _textureD3D11.QueryInterface <SharpDX.DXGI.Resource>())
                    using (SharpDX.Direct3D10.Texture2D backBuffer10 = device10.Device.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle))
                    {
                        _surface        = backBuffer10.QueryInterface <Surface>();
                        _renderTarget2D = new RenderTarget(_factory2D, _surface, GetRenderTargetProperties());
                    }
            }
            catch
            {
                Dispose();
                throw;
            }
        }
예제 #6
0
        public Direct2DOffscreenGraphics(int imageSizeX, int imageSizeY)
        {
            d3dDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);

            offscreenTexture = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
            {
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = imageSizeX,
                Height            = imageSizeY,
                MipLevels         = 1,
                ArraySize         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default
            });

            stagingTexture = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription
            {
                BindFlags         = SharpDX.Direct3D11.BindFlags.None,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.Read,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = imageSizeX,
                Height            = imageSizeY,
                MipLevels         = 1,
                ArraySize         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Staging
            });

            windowScaling = 1.0f; // No scaling for now in videos.
            factory       = new SharpDX.Direct2D1.Factory1();
            renderTarget  = new RenderTarget(factory, offscreenTexture.QueryInterface <SharpDX.DXGI.Surface>(), new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            Initialize();
        }
예제 #7
0
        public void OnResize(int width, int height)
        {
            if (mRealTexture != null)
                mRealTexture.Dispose();
            if (mTmpTexture != null)
                mTmpTexture.Dispose();

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

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

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

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

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

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

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

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

            // right now the texture is unowned and only a key of 0 will succeed.
            // after releasing it with a specific key said key then can be used for
            // further locking.
            mMutex10.Acquire(0, -1);
            mMutex10.Release(Key11);
        }
        private void _updateDimensions(double width, double height)
        {
            _appWidth = (float)width + 5;
            _appHeight = (float)height;

            if (_deviceManager == null) return ;
            if (_stagingTexture2D != null) _stagingTexture2D.Dispose();
            if (_stagingBitmap != null) _stagingBitmap.Dispose();
            if (_stagingBitmapSourceEffect != null) _stagingBitmapSourceEffect.Dispose();

            _stagingTexture2D = AllocateTextureReturnSurface((int)_appWidth, (int)_appHeight);
            _stagingBitmap = new SharpDX.Direct2D1.Bitmap1(_deviceManager.ContextDirect2D, _stagingTexture2D.QueryInterface<SharpDX.DXGI.Surface>());
            _stagingBitmapSourceEffect = new SharpDX.Direct2D1.Effects.BitmapSource(_deviceManager.ContextDirect2D);


        }
예제 #9
0
        private Bitmap GetDX11ScreenShot()
        {
            try
            {
                screenShot = null;
                screenShot = new Bitmap(WIDTH, HEIGHT, this.pixelFormat);
                if (dx11DuplicatedOutput != null)
                {
                    dx11DuplicatedOutput.AcquireNextFrame(NEXT_FRAME_TIMEOUT,
                                                          out dx11DuplFrameInfo, out dx11ScreenResource);

                    dx11Device.ImmediateContext
                    .CopyResource(dx11ScreenResource.QueryInterface <SharpDX.Direct3D11.Resource>(),
                                  dx11ScreenTexture);

                    // cast from texture to surface, so we can access its bytes
                    dx11ScreenSurface = dx11ScreenTexture.QueryInterface <SharpDX.DXGI.Surface>();
                    // map the resource to access it
                    dx11Map = dx11ScreenSurface.Map(SharpDX.DXGI.MapFlags.Read);
                    bmpData = screenShot.LockBits(boundsRect, ImageLockMode.WriteOnly, screenShot.PixelFormat);
                    var sourcePtr = dx11Map.DataPointer;
                    var destPtr   = bmpData.Scan0;
                    for (int y = 0; y < HEIGHT; y++)
                    {
                        // Copy a single line
                        Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH);
                        // Advance pointers
                        sourcePtr = IntPtr.Add(sourcePtr, dx11Map.Pitch);
                        destPtr   = IntPtr.Add(destPtr, bmpData.Stride);
                    }

                    dx11Device.ImmediateContext.UnmapSubresource(dx11ScreenTexture, 0);
                    screenShot.UnlockBits(bmpData);
                    dx11ScreenSurface.Unmap();
                    dx11ScreenSurface.Dispose();
                    dx11ScreenResource.Dispose();
                    dx11DuplicatedOutput.ReleaseFrame();
                }
                else
                {
                    return(screenShot = null);
                }

                dx11ScreenSurface = null;
                bmpData           = null;
                GC.Collect();

                return(screenShot);
            }
            catch (SharpDX.SharpDXException e)
            {
                if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                {
                    //screen does not changed
                    LdpLog.Warning("DX11 surface timeout.. Recursion is coming:)");
                    return(GetDX11ScreenShot());
                }
                else
                {
                    return(screenShot = null);
                }
            }
            catch (Exception ex)
            {
                LdpLog.Error("GetDX11ScreenShot\n" + ex.Message);
                return(screenShot = null);
            }
        }
예제 #10
0
        private void _updateDimensions(double width, double height)
        {
            _appWidth  = (float)width + 5;
            _appHeight = (float)height;

            if (_deviceManager == null)
            {
                return;
            }
            if (_stagingTexture2D != null)
            {
                _stagingTexture2D.Dispose();
            }
            if (_stagingBitmap != null)
            {
                _stagingBitmap.Dispose();
            }
            if (_stagingBitmapSourceEffect != null)
            {
                _stagingBitmapSourceEffect.Dispose();
            }

            _stagingTexture2D          = AllocateTextureReturnSurface((int)_appWidth, (int)_appHeight);
            _stagingBitmap             = new SharpDX.Direct2D1.Bitmap1(_deviceManager.ContextDirect2D, _stagingTexture2D.QueryInterface <SharpDX.DXGI.Surface>());
            _stagingBitmapSourceEffect = new SharpDX.Direct2D1.Effects.BitmapSource(_deviceManager.ContextDirect2D);
        }
예제 #11
0
        public VRRenderer(SharpDX.Direct3D11.Device d3d11Device, SharpDX.Direct3D11.Device unityDevice, VRRig rig)
        {
            instance = this;


            this.rig      = rig;
            device        = d3d11Device;
            unityRenderer = unityDevice;

            bounds      = new VRTextureBounds_t();
            bounds.vMin = bounds.uMin = 0;
            bounds.vMax = bounds.uMax = 1;

            var w           = rig.leftTexture.Description.Width;
            var h           = rig.leftTexture.Description.Height;
            var description = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width  = (int)w,
                Height = (int)h,

                MipLevels = 1,
                ArraySize = 1,

                SampleDescription = new SampleDescription()
                {
                    Count = 1
                },

                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format         = Format.R8G8B8A8_UNorm,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.Shared,
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default
            };

            System.Diagnostics.Trace.WriteLine("Creating D3D11 Textures");

            leftVRTexture  = new SharpDX.Direct3D11.Texture2D(d3d11Device, description);
            rightVRTexture = new SharpDX.Direct3D11.Texture2D(d3d11Device, description);

            leftEye = new Texture_t()
            {
                eColorSpace = EColorSpace.Gamma,
                eType       = ETextureType.DirectX,
                handle      = leftVRTexture.NativePointer
            };
            rightEye = new Texture_t()
            {
                eColorSpace = EColorSpace.Gamma,
                eType       = ETextureType.DirectX,
                handle      = rightVRTexture.NativePointer
            };


            var sharedHandleLeft  = leftVRTexture.QueryInterface <Resource>().SharedHandle;
            var sharedHandleRight = rightVRTexture.QueryInterface <Resource>().SharedHandle;

            leftHandle  = unityRenderer.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedHandleLeft);
            rightHandle = unityRenderer.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedHandleRight);

            var viewDesc = new SharpDX.Direct3D11.ShaderResourceViewDescription()
            {
                Format    = Format.R8G8B8A8_UNorm,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            };
            var leftView  = new SharpDX.Direct3D11.ShaderResourceView(unityDevice, leftHandle, viewDesc);
            var rightView = new SharpDX.Direct3D11.ShaderResourceView(unityDevice, rightHandle, viewDesc);

            leftUnityTexture  = Texture2D.CreateExternalTexture(w, h, TextureFormat.ARGB32, false, false, leftView.NativePointer);
            rightUnityTexture = Texture2D.CreateExternalTexture(w, h, TextureFormat.ARGB32, false, false, rightView.NativePointer);
        }
예제 #12
0
        public void Init(SharpDX.Direct3D11.Texture2D sharedTexture)
        {
            logger.Debug("D3DRenderer::Setup()");

            if (state != RendererState.Closed)
            {
                throw new InvalidOperationException("Invalid capture state " + State);
            }

            try
            {
                var descr = sharedTexture.Description;
                logger.Verb(string.Join(", ", descr.Width + "x" + descr.Height, descr.Format));

                if (descr.Format != SharpDX.DXGI.Format.B8G8R8A8_UNorm)
                {
                    throw new InvalidOperationException("Invalid renderer state " + State);
                }

                direct3D = new Direct3DEx();

                var hWnd = NativeAPIs.User32.GetDesktopWindow();

                var presentParams = new PresentParameters
                {
                    //Windowed = true,
                    //SwapEffect = SharpDX.Direct3D9.SwapEffect.Discard,
                    //DeviceWindowHandle = IntPtr.Zero,
                    //PresentationInterval = SharpDX.Direct3D9.PresentInterval.Default
                    //BackBufferCount = 1,

                    Windowed        = true,
                    MultiSampleType = MultisampleType.None,
                    SwapEffect      = SwapEffect.Discard,
                    PresentFlags    = PresentFlags.None,
                };

                var flags = CreateFlags.HardwareVertexProcessing |
                            CreateFlags.Multithreaded |
                            CreateFlags.FpuPreserve;

                int adapterIndex = 0;

                device = new DeviceEx(direct3D, adapterIndex, DeviceType.Hardware, hWnd, flags, presentParams);

                using (var resource = sharedTexture.QueryInterface <SharpDX.DXGI.Resource>())
                {
                    var handle = resource.SharedHandle;

                    if (handle == IntPtr.Zero)
                    {
                        throw new ArgumentNullException(nameof(handle));
                    }

                    // D3DFMT_A8R8G8B8 или D3DFMT_X8R8G8B8
                    // D3DUSAGE_RENDERTARGET
                    // D3DPOOL_DEFAULT
                    using (var texture3d9 = new SharpDX.Direct3D9.Texture(device,
                                                                          descr.Width, descr.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default,
                                                                          ref handle))
                    {
                        surface = texture3d9.GetSurfaceLevel(0);
                    };
                }

                this.texture2D11 = sharedTexture;
                var pSurface = surface.NativePointer;

                state = RendererState.Initialized;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Close();

                throw;
            }
        }