Пример #1
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);
        }
Пример #2
0
        private void SurfaceUpdated(IntPtr surfaceHandle)
        {
            SharpDX.ComObject            sharedObject   = new SharpDX.ComObject(surfaceHandle);
            SharpDX.DXGI.Resource        sharedResource = sharedObject.QueryInterface <SharpDX.DXGI.Resource>();
            SharpDX.Direct3D11.Texture2D nativeRexture  = dX11GraphicsContext.DXDevice.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedResource.SharedHandle);

            var texture = DX11Texture.FromDirectXTexture(dX11GraphicsContext, nativeRexture);
            var rTDepthTargetDescription = new TextureDescription()
            {
                Type        = TextureType.Texture2D,
                Format      = PixelFormat.D24_UNorm_S8_UInt,
                Width       = texture.Description.Width,
                Height      = texture.Description.Height,
                Depth       = 1,
                ArraySize   = 1,
                Faces       = 1,
                Flags       = TextureFlags.DepthStencil,
                CpuAccess   = ResourceCpuAccess.None,
                MipLevels   = 1,
                Usage       = ResourceUsage.Default,
                SampleCount = TextureSampleCount.None,
            };

            var rTDepthTarget = this.dX11GraphicsContext.Factory.CreateTexture(ref rTDepthTargetDescription, "SwapChain_Depth");
            var frameBuffer   = this.dX11GraphicsContext.Factory.CreateFrameBuffer(new FrameBufferAttachment(rTDepthTarget, 0, 1), new[] { new FrameBufferAttachment(texture, 0, 1) });

            frameBuffer.SwapchainAssociated = true;
            display.FrameBuffer?.Dispose();
            display.UpdateFrameBuffer(frameBuffer);
        }
Пример #3
0
 private IntPtr GetSharedHandle(SharpDX.Direct3D11.Texture2D texture)
 {
     using (var resource = texture.QueryInterface <SharpDX.DXGI.Resource>())
     {
         return(resource.SharedHandle);
     }
 }
Пример #4
0
        public GpuTexture2D(
            Size size,
            GpuPixelFormat pixelFormat,
            GpuDevice device,
            GpuResourceInfo resourceInfo) :
            base(device, size.Width * size.Height * GpuConvert.SizeOfInBytes(pixelFormat), resourceInfo)
        {
            Size        = new Size(size.Width, size.Height);
            PixelFormat = pixelFormat;

            mRowPitch = Size.Width * GpuConvert.SizeOfInBytes(PixelFormat);

            mResource = new SharpDX.Direct3D11.Texture2D(GpuDevice.Device, new SharpDX.Direct3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = GpuConvert.ToBindUsage(ResourceInfo.BindUsage),
                CpuAccessFlags    = GpuConvert.ToCpuAccessFlag(ResourceInfo.CpuAccessFlag),
                Format            = GpuConvert.ToPixelFormat(PixelFormat),
                Width             = Size.Width,
                Height            = Size.Height,
                MipLevels         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = GpuConvert.ToHeapType(ResourceInfo.HeapType)
            });
        }
Пример #5
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);
        }
Пример #6
0
        public VRRig(int vpWidth, int vpHeight)
        {
            root = new GameObject("MSCVR Camera Rig");

            var left    = new GameObject("Left Eye");
            var leftCam = left.AddComponent <Camera>();

            left.transform.localPosition.Set(-0.05f, 0, 0);
            left.transform.SetParent(root.transform);

            var right    = new GameObject("Right Eye");
            var rightCam = right.AddComponent <Camera>();

            right.transform.SetParent(root.transform);
            right.transform.localPosition.Set(0.05f, 0, 0);

            leftRt           = new RenderTexture(vpWidth, vpHeight, 0, RenderTextureFormat.ARGB32);
            leftRt.useMipMap = false;
            leftRt.Create();
            leftCam.targetTexture = leftRt;

            rightRt           = new RenderTexture(vpWidth, vpHeight, 0, RenderTextureFormat.ARGB32);
            rightRt.useMipMap = false;
            rightRt.Create();
            rightCam.targetTexture = rightRt;

            leftTexture  = new SharpDX.Direct3D11.Texture2D(leftRt.GetNativeTexturePtr());
            rightTexture = new SharpDX.Direct3D11.Texture2D(rightRt.GetNativeTexturePtr());
        }
Пример #7
0
        private void InitializeBlankTexture(SizeInt32 size)
        {
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            _blankTexture = new SharpDX.Direct3D11.Texture2D(_d3dDevice, description);

            using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, _blankTexture))
            {
                _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
            }
        }
Пример #8
0
        public static SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, GraphicsDevice device)
        {

            SharpDX.Direct3D11.Texture2DDescription desc;
            desc.Width = bsource.Size.Width;
            desc.Height = bsource.Size.Height;
            desc.ArraySize = 1;
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None;
            desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
            desc.MipLevels = 1;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;

			SharpDX.Direct3D11.Texture2D dx11Texture;
			
            using(SharpDX.DataStream s = new SharpDX.DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true))
			{
				bsource.CopyPixels(bsource.Size.Width * 4, s);

				SharpDX.DataRectangle rect = new SharpDX.DataRectangle(s.DataPointer, bsource.Size.Width * 4);

				dx11Texture = new SharpDX.Direct3D11.Texture2D(device._d3dDevice, desc, rect);
			}
            
			return dx11Texture;
        }
Пример #9
0
        private void InitializeDeviceResources()
        {
            SharpDX.DXGI.ModeDescription      backBufferDesc = new SharpDX.DXGI.ModeDescription(Width, Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);
            SharpDX.DXGI.SwapChainDescription swapChainDesc  = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true
            };
            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            var factory = swapChain.GetParent <SharpDX.DXGI.Factory>();

            factory.MakeWindowAssociation(renderForm.Handle, SharpDX.DXGI.WindowAssociationFlags.IgnoreAll);
            d3dDeviceContext = d3dDevice.ImmediateContext;
            using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            // Set viewport
            viewport = new SharpDX.Viewport(0, 0, Width, Height);
            d3dDeviceContext.Rasterizer.SetViewport(viewport);
        }
 /// <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);
 }
Пример #11
0
        private void CustomSwapChainPanel_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            lock (d2d1DC)
            {
                Utilities.Dispose(ref d2d1DC);
                Utilities.Dispose(ref backBufferTexture);

                try
                {
                    swapChain.ResizeBuffers(0, (int)ActualWidth, (int)ActualHeight, Format.Unknown, SwapChainFlags.None);
                }
                catch (SharpDXException ex)
                {
                    Debug.WriteLine(ex.ToString());
                }

                backBufferTexture = SharpDX.Direct3D11.Resource.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0);

                using (var surface = backBufferTexture.QueryInterface <Surface2>())
                {
                    d2d1DC = new DeviceContext(surface);
                }
            }

            AdjustFontSize();
            DrawPTT();
        }
        private SharpDX.Direct3D11.Texture2D AllocateTextureReturnSurface(int drawingSizeWidth, int drawingSizeHeight)
        {
            
            // Setup local variables
            var d3dDevice = _deviceManager.DeviceDirect3D;
            var d3dContext = _deviceManager.ContextDirect3D;
            var d2dDevice = _deviceManager.DeviceDirect2D;
            var d2dContext = _deviceManager.ContextDirect2D;

            var desc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, //  D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = drawingSizeWidth,
                Height = drawingSizeHeight,
                Usage = SharpDX.Direct3D11.ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
            };

            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            var tex2D = new SharpDX.Direct3D11.Texture2D(d3dDevice, desc);
            return tex2D;


        }
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="BackBuffer">Буффер на который будем рисовать, наш холст</param>
 /// <param name="Width">Ширина области в которую будем рисовать</param>
 /// <param name="Height">Высота объласти в которую будем рисовать</param>
 public TextWirter(SharpDX.Direct3D11.Texture2D BackBuffer, int Width, int Height)
 {
     this.TextFont = "Calibri";
     this.TextSize = 14;
     _width        = Width;
     _heght        = Height;
     _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
     InitTextFormat();
     _RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;
     // Initialize a TextLayout
     // _TextLayout = new TextLayout(_FactoryDWrite, "SharpDX D2D1 - DWrite", _TextFormat, Width, Height);
 }
Пример #14
0
    private void UninitializeResources()
    {
      if (_renderTarget == null)
        return;

      // Unassign back buffer from D3DImage.
      Lock();

      SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero, true);
#else
      SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);

      Unlock();

      // Dispose resources.
      _query.SafeDispose();
      _query = null;
      _isFrameReady = true; // Set to true while nothing is being rendered.
      _stagingResource9.SafeDispose();
      _stagingResource9 = null;
      _surface9.SafeDispose();
      _surface9 = null;
      _texture9.SafeDispose();
      _texture9 = null;
      _stagingResource11.SafeDispose();
      _stagingResource11 = null;
      _texture11.SafeDispose();
      _texture11 = null;
      _renderTarget.SafeDispose();
      _renderTarget = null;
    }
Пример #15
0
        public static Texture GetSharedD3D9(this DeviceEx device, SharpDX.Direct3D11.Texture2D renderTarget)
        {
            if (renderTarget == null)
            {
                return(null);
            }

            if ((renderTarget.Description.OptionFlags & SharpDX.Direct3D11.ResourceOptionFlags.Shared) == 0)
            {
                throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");
            }

            Format format = ToD3D9(renderTarget.Description.Format);

            if (format == Format.Unknown)
            {
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");
            }

            using (var resource = renderTarget.QueryInterface <SharpDX.DXGI.Resource>())
            {
                IntPtr handle = resource.SharedHandle;
                if (handle == IntPtr.Zero)
                {
                    throw new ArgumentNullException("Handle");
                }
                return(new Texture(device, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle));
            }
        }
        private SharpDX.Direct3D11.Texture2D AllocateTextureReturnSurface(int drawingSizeWidth, int drawingSizeHeight)
        {
            // Setup local variables
            var d3dDevice  = _deviceManager.DeviceDirect3D;
            var d3dContext = _deviceManager.ContextDirect3D;
            var d2dDevice  = _deviceManager.DeviceDirect2D;
            var d2dContext = _deviceManager.ContextDirect2D;

            var desc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm, //  D24_UNorm_S8_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = drawingSizeWidth,
                Height            = drawingSizeHeight,
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
            };

            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            var tex2D = new SharpDX.Direct3D11.Texture2D(d3dDevice, desc);

            return(tex2D);
        }
        public override void Dispose()
        {
            if (dx11Device != null)
                dx11Device.Dispose();
            if (dx11Factory != null)
                dx11Factory.Dispose();
            if (dx11Output != null)
                dx11Output.Dispose();
            if (dx11DuplicatedOutput != null)
                dx11DuplicatedOutput.Dispose();
            if (dx11ScreenTexture != null)
                dx11ScreenTexture.Dispose();
            if (dx11ScreenResource != null)
                dx11ScreenResource.Dispose();
            if (dx11ScreenSurface != null)
                dx11ScreenSurface.Dispose();

            if (screenShot != null)
                screenShot.Dispose();

            dx11Device = null;
            dx11Factory = null;
            dx11Output = null;
            dx11DuplicatedOutput = null;
            dx11ScreenTexture = null;
            dx11ScreenResource = null;
            dx11ScreenSurface = null;
            screenShot = null;

            bmpData = null;
            GC.SuppressFinalize(this);
        }
Пример #18
0
        //public bool IsOk()
        //{
        //  ThrowIfDisposed();
        //  return _device.CheckDeviceState(IntPtr.Zero) == DeviceState.Ok;
        //}


        /// <summary>
        /// Creates a Direct3D 9 texture from the specified Direct3D 11 texture.
        /// (The content is shared between the devices.)
        /// </summary>
        /// <param name="texture">The Direct3D 11 texture.</param>
        /// <returns>The Direct3D 9 texture.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="texture"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// The Direct3D 11 texture is not a shared resource, or the texture format is not supported.
        /// </exception>
        public Texture CreateSharedTexture(SharpDX.Direct3D11.Texture2D texture)
        {
            ThrowIfDisposed();

            if (texture == null)
            {
                throw new ArgumentNullException("texture");
            }

            var format = ToD3D9(texture.Description.Format);

            IntPtr sharedHandle;

            using (var resource = texture.QueryInterface <SharpDX.DXGI.Resource>())
                sharedHandle = resource.SharedHandle;

            if (sharedHandle == IntPtr.Zero)
            {
                throw new ArgumentException("Unable to access resource. The texture needs to be created as a shared resource.", "texture");
            }

            int width  = texture.Description.Width;
            int height = texture.Description.Height;

            return(new Texture(_device, width, height, 1, Usage.RenderTarget, format, Pool.Default, ref sharedHandle));
        }
Пример #19
0
        protected void Draw()
        {
            HResult   hr;
            IMFSample mfsample = null;

            try
            {
                // 現在表示すべき IMFSample が TextureMediaSink の TMS_SAMPLE 属性に設定されているので、それを取得する。
                if ((hr = this.MediaSinkAttributes.GetUnknown(TMS_SAMPLE, out mfsample)).Failed())
                {
                    return;
                }
                if (null == mfsample)
                {
                    return;                                                                              // 未設定
                }
                var sample = new SharpDX.MediaFoundation.Sample(Marshal.GetIUnknownForObject(mfsample)); // MediaFoundation.NET to SharpDX.MediaFoundation

                // 注意:
                // 変数 mfsample は RCW(Runtime Callable Wrapper) オブジェクトであり、内部に COM (ネイティブIMFSample) への参照を保持している。
                // このあと mfsample への参照が 0 になっても、内部の COM は mfsample が GC によりファイナライズされるまで Release されないことに注意。(RCW の仕様)
                // D3D11TextureMediaSink.dll では、mfsample の内包する COM の実体がこのプログラム(とdll)が終了するまで不変であるよう設計されているため、直接の問題はない。
                // (RCW による同一の COM への AddRef は1回しか行われないので、mfsample に何度値を設定しても、内部の COM 参照カウンタは初回以降増加しない。)

                // IMFSample からメディアバッファを取得。
                using (var mediaBuffer = sample.GetBufferByIndex(0))
                {
                    // メディアバッファからDXGIバッファを取得。
                    using (var dxgiBuffer = mediaBuffer.QueryInterfaceOrNull <SharpDX.MediaFoundation.DXGIBuffer>())
                    {
                        // DXGIバッファから転送元 Texture2D を取得。
                        dxgiBuffer.GetResource(typeof(SharpDX.Direct3D11.Texture2D).GUID, out IntPtr ppv);
                        using (var texture = new SharpDX.Direct3D11.Texture2D(ppv))
                        {
                            // 転送元 Texture2D のサブリソースインデックスを取得。
                            int subIndex = dxgiBuffer.SubresourceIndex;

                            //
                            // これで、IMFSample から ID3D11Texture2D を取得することができた。
                            // 今回のデモでは、これを単純に SwapChain に矩形描画することにする。
                            //

                            // SwapChain から転送先 Texture2D を取得。
                            using (var dst = this.DXGISwapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
                            {
                                // 転送。
                                this.D3DDevice.ImmediateContext.CopySubresourceRegion(texture, subIndex, null, dst, 0);
                            }
                        }
                    }
                }
            }
            finally
            {
                // GetUnknown で TMS_SAMPLE を得たとき、その IMFSample は TextureMediaSink から更新されないよう lock されている。
                // この lock を解除するために、TMS_SAMPLE 属性に何か(なんでもいい)を SetUnknwon する。これで IMFSample が TextureMediaSink から更新可能になる。
                this.MediaSinkAttributes.SetUnknown(TMS_SAMPLE, mfsample);
            }
        }
Пример #20
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);
        }
Пример #21
0
        public static SharpDX.Direct3D11.Texture2D CreateSharpDXTexture2D(IDirect3DSurface surface)
        {
            var access     = (IDirect3DDxgiInterfaceAccess)surface;
            var d3dPointer = access.GetInterface(ID3D11Texture2D);
            var d3dSurface = new SharpDX.Direct3D11.Texture2D(d3dPointer);

            return(d3dSurface);
        }
Пример #22
0
        private Direct2DOffscreenGraphics(int imageSizeX, int imageSizeY, bool allowReadback)
        {
            try
            {
                if (d3dDevice == null)
                {
                    d3dDevice    = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);
                    d3dDeviceRef = 1;
                }
                else
                {
                    d3dDeviceRef++;
                }

                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
                });

                if (allowReadback)
                {
                    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.
                CreateFactory();
                renderTarget = new RenderTarget(factory, offscreenTexture.QueryInterface <SharpDX.DXGI.Surface>(), new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            catch (Exception e)
            {
                Log.LogMessage(LogSeverity.Error, e.Message);
                Log.LogMessage(LogSeverity.Error, "Error initializing D3D11. This can happen on Windows 7 system that are missing some D3D11 components such as the KB2670838 update.");
                return;
            }

            Initialize();
        }
Пример #23
0
        public SharpDX.DataStream CaptureScreen()
        {
            // try to get duplicated frame within given time
            try
            {
                OutputDuplicateFrameInformation duplicateFrameInformation;
                duplicatedOutput.AcquireNextFrame(1000, out duplicateFrameInformation, out screenResource);

                // copy resource into memory that can be accessed by the CPU
                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(MapFlags.Read, out dataStream);

                // seek within the stream and read one byte
                //dataStream.Position = 4;
                //dataStream.ReadByte();

                // free resources
                //dataStream.Close();
                screenSurface.Unmap();
                screenSurface.Dispose();
                screenResource.Dispose();
                duplicatedOutput.ReleaseFrame();
                return(dataStream);
            }
            catch (SharpDX.SharpDXException e)
            {
                device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                factory = new Factory1();
                // creating CPU-accessible texture resource
                texdes = new SharpDX.Direct3D11.Texture2DDescription();
                texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
                texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
                texdes.Format                    = Format.B8G8R8A8_UNorm;
                texdes.Height                    = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;
                texdes.Width                     = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
                texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
                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(device, texdes);

                // duplicate output stuff
                output = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
                try
                {
                    duplicatedOutput = output.DuplicateOutput(device);
                }
                catch { }
                return(CaptureScreen());
            }
        }
Пример #24
0
 private static Format TranslateFormat(SharpDX.Direct3D11.Texture2D texture)
 {
     return(texture.Description.Format switch
     {
         SharpDX.DXGI.Format.R10G10B10A2_UNorm => Format.A2B10G10R10,
         SharpDX.DXGI.Format.R16G16B16A16_Float => Format.A16B16G16R16F,
         SharpDX.DXGI.Format.B8G8R8A8_UNorm => Format.A8R8G8B8,
         _ => Format.Unknown
     });
Пример #25
0
 public void Dispose()
 {
     this.Stop();
     this.CleanupItem();
     this.device    = null;
     this.d3dDevice = null;
     this.blankTexture?.Dispose();
     this.blankTexture = null;
 }
        /// <summary>
        /// Saves the contents of a <see cref="SharpDX.Direct3D11.Texture2D"/> to a file with name contained in <paramref name="filename"/> using the specified <see cref="System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="texture">The <see cref="SharpDX.Direct3D11.Texture2D"/> containing the data to save.</param>
        /// <param name="filename">The filename on disk where the output image should be saved.</param>
        /// <param name="imageFormat">The format to use when saving the output file.</param>
        public void SaveTextureToFile(SharpDX.Direct3D11.Texture2D texture, string filename, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            // If the existing debug texture doesn't exist, or the incoming texture is different than the existing debug texture...
            if (m_pDebugTexture == null || !TextureCanBeCopied(m_pDebugTexture, texture))
            {
                // Dispose of any existing texture
                if (m_pDebugTexture != null)
                {
                    m_pDebugTexture.Dispose();
                }

                // Copy the original texture's description...
                SharpDX.Direct3D11.Texture2DDescription newDescription = texture.Description;

                // Then modify the parameters to create a CPU-readable staging texture
                newDescription.BindFlags      = SharpDX.Direct3D11.BindFlags.None;
                newDescription.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
                newDescription.OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None;
                newDescription.Usage          = SharpDX.Direct3D11.ResourceUsage.Staging;

                // Re-generate the debug texture by copying the new texture's description
                m_pDebugTexture = new SharpDX.Direct3D11.Texture2D(m_pDevice, newDescription);
            }

            // Copy the texture to our debug texture
            m_pDevice.ImmediateContext.CopyResource(texture, m_pDebugTexture);

            // Map the debug texture's resource 0 for read mode
            SharpDX.DataStream data;
            SharpDX.DataBox    dbox = m_pDevice.ImmediateContext.MapSubresource(m_pDebugTexture, 0, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out data);

            // Create a bitmap that's the same size as the debug texture
            Bitmap b = new Bitmap(m_pDebugTexture.Description.Width, m_pDebugTexture.Description.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            // Lock the bitmap data to get access to the native bitmap pointer
            System.Drawing.Imaging.BitmapData bd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            // Use the native pointers to do a native-to-native memory copy from the mapped subresource to the bitmap data
            // WARNING: This might totally blow up if you're using a different color format than B8G8R8A8_UNorm, I don't know how planar formats are structured as D3D textures!
            //
            // You can use Win32 CopyMemory to do the below copy if need be, but you have to do it in a loop to respect the Stride and RowPitch parameters in case the texture width
            // isn't on an aligned byte boundary.
            MediaFoundation.MFExtern.MFCopyImage(bd.Scan0, bd.Stride, dbox.DataPointer, dbox.RowPitch, bd.Width * 4, bd.Height);

            /// Unlock the bitmap
            b.UnlockBits(bd);

            // Unmap the subresource mapping, ignore the SharpDX.DataStream because we don't need it.
            m_pDevice.ImmediateContext.UnmapSubresource(m_pDebugTexture, 0);
            data = null;

            // Save the bitmap to the desired filename
            b.Save(filename, imageFormat);
            b.Dispose();
            b = null;
        }
Пример #27
0
    private void InitializeResources(GraphicsDevice graphicsDevice, int width, int height)
    {
      try
      {
        Debug.Assert(_renderTarget == null, "Dispose previous back buffer before creating a new back buffer.");

        // MonoGame
        var format = _enableAlpha ? SurfaceFormat.Bgra32 : SurfaceFormat.Bgr32;
        _renderTarget = new RenderTarget2D(graphicsDevice, width, height, false, format, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents);

        // Direct3D 11
        var device11 = (SharpDX.Direct3D11.Device)graphicsDevice.Handle;
        var formatDXGI = D3D11Helper.ToD3D11(format);
        _texture11 = D3D11Helper.CreateSharedResource(device11, width, height, formatDXGI);
        _stagingResource11 = D3D11Helper.CreateStagingResource(device11, _texture11);

        // Direct3D 9
        _texture9 = _d3D9.CreateSharedTexture(_texture11);
        _surface9 = _texture9.GetSurfaceLevel(0);
        _stagingResource9 = _d3D9.CreateStagingResource(_texture11);

        // Direct3D 11 event query.
        Debug.Assert(_isFrameReady, "_isFrameReady should be true when uninitialized.");
        var queryDescription = new SharpDX.Direct3D11.QueryDescription
        {
          Flags = SharpDX.Direct3D11.QueryFlags.None,
          Type = SharpDX.Direct3D11.QueryType.Event
        };
        _query = new SharpDX.Direct3D11.Query(device11, queryDescription);

        // Assign back buffer to D3DImage.
        // The back buffer is still empty, however we need to set a valid back buffer
        // for the layout logic. Otherwise, the size of the D3D11Image is (0, 0).
        Lock();

        SetBackBuffer(D3DResourceType.IDirect3DSurface9, _surface9.NativePointer, true);
#else
        SetBackBuffer(D3DResourceType.IDirect3DSurface9, _surface9.NativePointer);

        Unlock();

        if (IsSynchronized)
        {
          // Issue a copy of the surface into the staging resource to see when the
          // resource is no longer used by Direct3D 9.
          _d3D9.Copy(_surface9, _stagingResource9);
          _isAvailable9 = _d3D9.TryAccess(_stagingResource9);
        }
      }
      catch
      {
        // GPU may run out of memory.
        UninitializeResources();
        throw;
      }
    }
Пример #28
0
        public void CreateDirectXSwapChain()
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                // Want Transparency.
                AlphaMode = SharpDX.DXGI.AlphaMode.Premultiplied,
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(ActualHeight),
                Width  = (int)(ActualWidth),
                // Default multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
            };

            using (SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport))
            {
                this.device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device2>();
            }

            // Save the context instance
            //this.d3d11DC = this.device.ImmediateContext2;

            using (SharpDX.DXGI.Device3 dxgiDevice3 = device.QueryInterface <SharpDX.DXGI.Device3>())
            {
                using (SharpDX.DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <SharpDX.DXGI.Factory3>())
                {
                    using (SwapChain1 swapChain1 = new SwapChain1(dxgiFactory3, device, ref swapChainDescription))
                    {
                        swapChain = swapChain1.QueryInterface <SwapChain2>();
                    }
                }
            }

            using (ISwapChainPanelNative nativeObject = ComObject.As <ISwapChainPanelNative>(this))
            {
                nativeObject.SwapChain = swapChain;
            }

            backBufferTexture = SharpDX.Direct3D11.Resource.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0);

            using (var surface = backBufferTexture.QueryInterface <Surface2>())
            {
                d2d1DC = new DeviceContext(surface);
            }
        }
Пример #29
0
        /// <summary>
        /// Update all resources
        /// </summary>
        /// <param name="backBuffer">BackBuffer</param>
        internal void UpdateResources(SharpDX.Direct3D11.Texture2D backBuffer)
        {
            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var d2dSurface = backBuffer.QueryInterface <Surface>();

            _direct2DRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
            d2dSurface.Dispose();
            d2dFactory.Dispose();

            InitFont();
        }
Пример #30
0
 /// <summary>
 /// Update all resources
 /// </summary>
 /// <param name="backBuffer">BackBuffer</param>
 internal void UpdateResources(Texture2D11 backBuffer)
 {
     using (var surface2D = backBuffer.QueryInterface <Surface>())
     {
         var dpi = NativeFactory.DesktopDpi;
         Target = new Bitmap1(NativeDeviceContext, surface2D,
                              new BitmapProperties1(new PixelFormat(
                                                        Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target));
         NativeDeviceContext.Target = Target;
     }
 }
Пример #31
0
        private static Format TranslateFormat(SharpDX.Direct3D11.Texture2D texture)
        {
            switch (texture.Description.Format)
            {
            case SharpDX.DXGI.Format.R10G10B10A2_UNorm: return(SharpDX.Direct3D9.Format.A2B10G10R10);

            case SharpDX.DXGI.Format.R16G16B16A16_Float: return(SharpDX.Direct3D9.Format.A16B16G16R16F);

            case SharpDX.DXGI.Format.B8G8R8A8_UNorm: return(SharpDX.Direct3D9.Format.A8R8G8B8);

            default: return(SharpDX.Direct3D9.Format.Unknown);
            }
        }
Пример #32
0
        public byte[] GetPixelBytes(int left, int top, int width, int height)
        {
            if (width <= 0 || height <= 0)
            {
                return(new byte[] { });
            }
            var device      = _texture.Device;
            var description =
                new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                ArraySize         = 1,
                MipLevels         = 1,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Staging,
                BindFlags         = SharpDX.Direct3D11.BindFlags.None,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.Read,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            byte[] result = new byte[width * height * 4];
            using (var staging = new SharpDX.Direct3D11.Texture2D(device, description))
            {
                var textureWidth  = _texture.Description.Width;
                var textureHeight = _texture.Description.Height;
                var srcX0         = Math.Max(0, left);
                var srcY0         = Math.Max(0, top);
                var srcX1         = Math.Min(textureWidth, Math.Max(0, left + width));
                var srcY1         = Math.Min(textureHeight, Math.Max(0, top + height));
                if (srcX1 <= srcX0 || srcY1 <= srcY0)
                {
                    return(new byte[] { });
                }
                var region = new SharpDX.Direct3D11.ResourceRegion(srcX0, srcY0, 0, srcX1, srcY1, 1);
                var dstX0  = Math.Max(0, -left);
                var dstY0  = Math.Max(0, -top);
                device.ImmediateContext.CopySubresourceRegion(_texture, 0, region, staging, 0, dstX0, dstY0);
                var box = device.ImmediateContext.MapSubresource(
                    staging, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
                for (int i = 0; i < height; ++i)
                {
                    Marshal.Copy(box.DataPointer + i * box.RowPitch, result, i * width * 4, width * 4);
                }
                device.ImmediateContext.UnmapSubresource(staging, 0);
            }
            return(result);
        }
Пример #33
0
 public Texture2D( IGraphicsDevice graphicsDevice, int width, int height, int mipmapLevel = 1, bool isRenderBuffer = false )
 {
     if ( width == 0 ) width = 1;
     if ( height == 0 ) height = 1;
     Size = new Vector2 ( width, height );
     texture = new SharpDX.Direct3D11.Texture2D ( graphicsDevice.Handle as SharpDX.Direct3D11.Device, new SharpDX.Direct3D11.Texture2DDescription ()
     {
         Width = width,
         Height = height,
         Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
         MipLevels = mipmapLevel,
         CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write,
         Usage = SharpDX.Direct3D11.ResourceUsage.Default,
         BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | ( isRenderBuffer ? ( SharpDX.Direct3D11.BindFlags.RenderTarget ) : 0 ),
         ArraySize = 1,
     } );
 }
Пример #34
0
 public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
     : base(graphicsDevice, width, height, 1, true)
 {
     targetView = new SharpDX.Direct3D11.RenderTargetView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.RenderTargetViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.RenderTargetViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Texture2D = new SharpDX.Direct3D11.RenderTargetViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     depthStencilBuffer = new SharpDX.Direct3D11.Texture2D ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         new SharpDX.Direct3D11.Texture2DDescription ()
         {
             ArraySize = 1,
             Width = width,
             Height = height,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             MipLevels = 0,
             BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
         }
     );
     depthStencil = new SharpDX.Direct3D11.DepthStencilView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         depthStencilBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             Texture2D = new SharpDX.Direct3D11.DepthStencilViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     shaderView = new SharpDX.Direct3D11.ShaderResourceView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.ShaderResourceViewDescription ()
         {
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
             Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource () { MipLevels = 1, MostDetailedMip = 0 }
         }
     );
 }
Пример #35
0
        public override void Initialize(DeviceManager deviceManager)
        {
            base.Initialize(deviceManager);

            // Save the context instance
            this.deviceContext = deviceManager.DeviceDirect3D.ImmediateContext1;

            // We have to take into account pixel scaling; Windows Phone 8.1 uses virtual resolutions smaller than the physical screen size.
            float pixelScale = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;

            // Properties of the swap chain
            SharpDX.DXGI.SwapChainDescription1 swapChainDescription = new SharpDX.DXGI.SwapChainDescription1()
            {
                // No transparency.
                AlphaMode = SharpDX.DXGI.AlphaMode.Ignore,
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(this.swapChainPanel.RenderSize.Height * pixelScale),
                Width = (int)(this.swapChainPanel.RenderSize.Width * pixelScale),
                // Default multisampling.
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = SharpDX.DXGI.Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
            };

            // Retrive the DXGI device associated to the Direct3D device.
            using (SharpDX.DXGI.Device3 dxgiDevice3 = deviceManager.DeviceDirect3D.QueryInterface<SharpDX.DXGI.Device3>())
            {
                // Get the DXGI factory automatically created when initializing the Direct3D device.
                using (SharpDX.DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent<SharpDX.DXGI.Factory3>())
                {
                    // Create the swap chain and get the highest version available.
                    using (SharpDX.DXGI.SwapChain1 swapChain1 = new SharpDX.DXGI.SwapChain1(dxgiFactory3, deviceManager.DeviceDirect3D, ref swapChainDescription))
                    {
                        this.swapChain = swapChain1.QueryInterface<SharpDX.DXGI.SwapChain2>();
                    }
                }
            }

            // Obtain a reference to the native COM object of the SwapChainPanel.
            using (SharpDX.DXGI.ISwapChainPanelNative nativeObject = SharpDX.ComObject.As<SharpDX.DXGI.ISwapChainPanelNative>(this.swapChainPanel))
            {
                // Set its swap chain.
                nativeObject.SwapChain = this.swapChain;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            // TODO: Recreate a DepthStencilBuffer is inefficient. We should only have one depth buffer. Shared depth buffer?
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(DeviceManager.DeviceDirect3D, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)swapChainDescription.Width,
                Height = (int)swapChainDescription.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))

            this.depthStencilView = Collect(new SharpDX.Direct3D11.DepthStencilView(DeviceManager.DeviceDirect3D, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D }));

            // Create a Texture2D from the existing swap chain to use as 
            this.backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(this.swapChain, 0);
            this.renderTargetView = new SharpDX.Direct3D11.RenderTargetView(deviceManager.DeviceDirect3D, this.backBuffer);

            var viewport = new SharpDX.ViewportF(0, 0, (float)swapChainDescription.Width, (float)swapChainDescription.Height, 0.0f, 1.0f);

            RenderTargetBounds = new Rect(viewport.X, viewport.Y, viewport.Width, viewport.Height);

            //DeviceManager.ContextDirect2D.Target = this.backBuffer.as;

            DeviceManager.ContextDirect3D.Rasterizer.SetViewport(viewport);
        }
Пример #36
0
        protected void InitializeRift()
        {

            // Initialize OVR Library
            OVR.Initialize();

            if (OVR.HmdDetect() < 1)
            {
                throw new IndexOutOfRangeException("No Rfft detected");
            }

            // Create our HMD
            hmd = OVR.HmdCreate(0);

            if (hmd == null)
            {
                throw new IndexOutOfRangeException("Can't create Rift");
            }

            SharpDX.Size2 left = hmd.GetFovTextureSize(EyeType.Left, hmd.DefaultEyeFov[0]);
            SharpDX.Size2 right = hmd.GetFovTextureSize(EyeType.Right, hmd.DefaultEyeFov[1]);

            leftEyeWidth = left.Width;
            leftEyeHeight = left.Height;
            rightEyeWidth = right.Width;
            rightEyeHeight = right.Height;

            // Create our render target
            eyeTexture[0] = hmd.CreateSwapTexture(RenderContext11.Device, riftFormat, left, false);
            eyeTexture[1] = hmd.CreateSwapTexture(RenderContext11.Device, riftFormat, right, false);

            swapTextures[0] = new SwapTextureSetD3D(eyeTexture[0].TextureSet);

            swapTextures[1] = new SwapTextureSetD3D(eyeTexture[1].TextureSet);

            // Create our layer
            layerEyeFov = new LayerEyeFov
            {
                Header = new LayerHeader(LayerType.EyeFov, LayerFlags.HighQuality),
                ColorTextureLeft = eyeTexture[0].TextureSet,
                ColorTextureRight = eyeTexture[1].TextureSet,
                ViewportLeft = new Rect(0, 0, eyeTexture[0].Size.Width, eyeTexture[0].Size.Height),
                ViewportRight = new Rect(0, 0, eyeTexture[1].Size.Width, eyeTexture[1].Size.Height),
                FovLeft = hmd.DefaultEyeFov[0],
                FovRight = hmd.DefaultEyeFov[1],
            };

            // Keep eye view offsets
            eyeRenderDesc[0] = hmd.GetRenderDesc(EyeType.Left, hmd.DefaultEyeFov[0]);
            eyeRenderDesc[1] = hmd.GetRenderDesc(EyeType.Right, hmd.DefaultEyeFov[1]);
            hmdToEyeViewOffset[0] = eyeRenderDesc[0].HmdToEyeViewOffset;
            hmdToEyeViewOffset[1] = eyeRenderDesc[1].HmdToEyeViewOffset;

            // Create a mirror texture
            mirrorTexture = hmd.CreateMirrorTexture(RenderContext11.Device, RenderContext11.BackBuffer.Description);
            mirror = new Texture11(mirrorTexture);
            
            // Configure tracking
            hmd.ConfigureTracking(TrackingCapabilities.Orientation | TrackingCapabilities.Position | TrackingCapabilities.MagYawCorrection, TrackingCapabilities.None);

            // Set enabled capabilities
            hmd.EnabledCaps = HMDCapabilities.LowPersistence | HMDCapabilities.DynamicPrediction;
            
            riftInit = true;
           
        }
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

                uint numAdapter = 0;   // # of graphics card adapter
                uint numOutput = 0;    // # of output device (i.e. monitor)

                // create device and factory
                dx11Device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                dx11Factory = new Factory1();
                dx11Output = new Output1(dx11Factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);

                // creating CPU-accessible texture resource
                dx11Texture2Ddescr = new SharpDX.Direct3D11.Texture2DDescription();
                dx11Texture2Ddescr.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
                dx11Texture2Ddescr.BindFlags = SharpDX.Direct3D11.BindFlags.None;
                dx11Texture2Ddescr.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                dx11Texture2Ddescr.Height = HEIGHT;
                dx11Texture2Ddescr.Width = WIDTH;
                dx11Texture2Ddescr.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;
                dx11Texture2Ddescr.MipLevels = 1;
                dx11Texture2Ddescr.ArraySize = 1;
                dx11Texture2Ddescr.SampleDescription.Count = 1;
                dx11Texture2Ddescr.SampleDescription.Quality = 0;
                dx11Texture2Ddescr.Usage = SharpDX.Direct3D11.ResourceUsage.Staging;
                dx11ScreenTexture = new SharpDX.Direct3D11.Texture2D(dx11Device, dx11Texture2Ddescr);

                // duplicate output stuff

                dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                string error = "Directx 11 initializer error.\n" + dxe.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                string error = "Directx 11 initializer error.\n" + ex.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #38
0
		public RenderTarget2D (GraphicsDevice graphicsDevice, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
			:base (graphicsDevice, width, height, mipMap, preferredFormat, true)
		{
			DepthStencilFormat = preferredDepthFormat;
			MultiSampleCount = preferredMultiSampleCount;
			RenderTargetUsage = usage;

#if DIRECTX
            // Create a view interface on the rendertarget to use on bind.
            _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(graphicsDevice._d3dDevice, _texture);
#endif

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

#if DIRECTX

            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
            if ( preferredMultiSampleCount > 1 )
            {
                multisampleDesc.Count = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)SharpDX.Direct3D11.StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))

            // Create the view for binding to the device.
            _depthStencilView = new SharpDX.Direct3D11.DepthStencilView(graphicsDevice._d3dDevice, depthBuffer,
                new SharpDX.Direct3D11.DepthStencilViewDescription() 
                { 
                    Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D 
                });

#elif OPENGL

#if GLES
			GL.GenRenderbuffers(1, ref glDepthStencilBuffer);
#else
			GL.GenRenderbuffers(1, out glDepthStencilBuffer);
#endif
            GraphicsExtensions.CheckGLError();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, this.glDepthStencilBuffer);
            GraphicsExtensions.CheckGLError();
            var glDepthStencilFormat = GLDepthComponent16;
			switch (preferredDepthFormat)
			{
			case DepthFormat.Depth16: glDepthStencilFormat = GLDepthComponent16; break;
			case DepthFormat.Depth24: glDepthStencilFormat = GLDepthComponent24; break;
			case DepthFormat.Depth24Stencil8: glDepthStencilFormat = GLDepth24Stencil8; break;
			}
			GL.RenderbufferStorage(GLRenderbuffer, glDepthStencilFormat, this.width, this.height);
            GraphicsExtensions.CheckGLError();
#endif
        }
Пример #39
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);
        }
        /// <summary>
        /// Called from parent when it closes to ensure this asset closes properly and leaves
        /// not possible memory leaks
        /// </summary>
        public void Unload()
        {

            WindowLayoutService.OnWindowLayoutRaised -= WindowLayoutService_OnWindowLayoutRaised;

            _root = null;
            _rootParent = null;

            _clearRenderTree();
            ClearAssets();

            _clock = null;
            _gt = null;
            _tweener = null;

            _deviceManager = null;
            _d2dContext = null;

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

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

            if (_stagingTexture2D != null) {
                _stagingTexture2D.Dispose();
                _stagingTexture2D = null;
            }
            
            _pathD2DConverter = null;

           

            //_graphicsDevice.Dispose();
            //_graphicsDevice = null;

        }
Пример #41
0
 /// <summary>
 /// 
 /// </summary>
 private static SharpDX.Direct3D11.Texture2D GetCopy(this SharpDX.Direct3D11.Texture2D tex)
 {
     var teximg = new SharpDX.Direct3D11.Texture2D(tex.Device, new SharpDX.Direct3D11.Texture2DDescription
     {
         Usage = SharpDX.Direct3D11.ResourceUsage.Staging,
         BindFlags = SharpDX.Direct3D11.BindFlags.None,
         CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read,
         Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
         OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
         ArraySize = tex.Description.ArraySize,
         Height = tex.Description.Height,
         Width = tex.Description.Width,
         MipLevels = tex.Description.MipLevels,
         SampleDescription = tex.Description.SampleDescription,
     });
     tex.Device.ImmediateContext.CopyResource(tex, teximg);
     return teximg;
 }
        /// <inveritdoc/>
        public override void RenderAll()
        {
            SurfaceViewData viewData = null;

            var regionToDraw = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);

            // Unlike other targets, we can only get the DXGI surface to render to
            // just before rendering.
            using (var surface = surfaceImageSourceNative.BeginDraw(regionToDraw, out position))
            {
                // Cache DXGI surface in order to avoid recreate all render target view, depth stencil...etc.
                // Is it the right way to do it?
                // It seems that ISurfaceImageSourceNative.BeginDraw is returning 2 different DXGI surfaces (when the application is in foreground)
                // or different DXGI surfaces (when the application is in background).
                foreach (var surfaceViewData in viewDatas)
                {
                    if (surfaceViewData.SurfacePointer == surface.NativePointer)
                    {
                        viewData = surfaceViewData;
                        break;
                    }
                }

                if (viewData == null)
                {
                    viewData = viewDatas[nextViewDataIndex];
                    nextViewDataIndex = (nextViewDataIndex + 1) % viewDatas.Length;

                    // Make sure that previous was disposed.
                    viewData.Dispose();
                    viewData.SurfacePointer = surface.NativePointer;

                    // Allocate a new renderTargetView if size is different
                    // Cache the rendertarget dimensions in our helper class for convenient use.
                    viewData.BackBuffer = surface.QueryInterface<SharpDX.Direct3D11.Texture2D>();
                    {
                        var desc = viewData.BackBuffer.Description;
                        viewData.RenderTargetSize = new Size(desc.Width, desc.Height);
                        viewData.RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(DeviceManager.DeviceDirect3D, viewData.BackBuffer);
                    }

                    // Create a descriptor for the depth/stencil buffer.
                    // Allocate a 2-D surface as the depth/stencil buffer.
                    // Create a DepthStencil view on this surface to use on bind.
                    // TODO: Recreate a DepthStencilBuffer is inefficient. We should only have one depth buffer. Shared depth buffer?
                    using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(DeviceManager.DeviceDirect3D, new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = (int)viewData.RenderTargetSize.Width,
                        Height = (int)viewData.RenderTargetSize.Height,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
                    }))
                        viewData.DepthStencilView = new SharpDX.Direct3D11.DepthStencilView(DeviceManager.DeviceDirect3D, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D });

                    // Now we set up the Direct2D render target bitmap linked to the swapchain. 
                    // Whenever we render to this bitmap, it will be directly rendered to the 
                    // swapchain associated with the window.
                    var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                        new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                        DeviceManager.Dpi,
                        DeviceManager.Dpi,
                        SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

                    // Direct2D needs the dxgi version of the backbuffer surface pointer.
                    // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
                    viewData.BitmapTarget = new SharpDX.Direct2D1.Bitmap1(DeviceManager.ContextDirect2D, surface, bitmapProperties);

                    // Create a viewport descriptor of the full window size.
                    viewData.Viewport = new SharpDX.ViewportF(position.X, position.Y, (float)viewData.RenderTargetSize.Width - position.X, (float)viewData.RenderTargetSize.Height - position.Y, 0.0f, 1.0f);
                }

                backBuffer = viewData.BackBuffer;
                renderTargetView = viewData.RenderTargetView;
                depthStencilView = viewData.DepthStencilView;
                RenderTargetBounds = new Rect(viewData.Viewport.X, viewData.Viewport.Y, viewData.Viewport.Width, viewData.Viewport.Height);
                bitmapTarget = viewData.BitmapTarget;

                DeviceManager.ContextDirect2D.Target = viewData.BitmapTarget;

                // Set the current viewport using the descriptor.
                DeviceManager.ContextDirect3D.Rasterizer.SetViewports(viewData.Viewport);

                // Perform the actual rendering of this target
                base.RenderAll();
            }

            surfaceImageSourceNative.EndDraw();
        }
        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);


        }
Пример #44
0
        protected virtual void CreateSizeDependentResources(TargetBase renderBase)
        {
            var d3dDevice = DeviceManager.DeviceDirect3D;
            var d3dContext = DeviceManager.ContextDirect3D;
            var d2dContext = DeviceManager.ContextDirect2D;

            d2dContext.Target = null;
            SafeDispose(ref renderTargetView);
            SafeDispose(ref depthStencilView);
            SafeDispose(ref bitmapTarget);

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain
                using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
                using (var dxgiAdapter = dxgiDevice2.Adapter)
                using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                {
                    swapChain = ToDispose(CreateSwapChain(dxgiFactory2, d3dDevice, desc));

                    // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                    // latency and ensures that the application will only render after each VSync, minimizing
                    // power consumption.
                    dxgiDevice2.MaximumFrameLatency = 1;
                }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            using (var backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(swapChain, 0))
            {
                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer));

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = backBuffer.Description;
                RenderTargetBounds = new Windows.Foundation.Rect(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D }));

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.Direct3D11.Viewport((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewports(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Пример #45
0
        public void Render(RenderFrame frame)
        {
            if (SwapChain == null) return;

            /////////////////////////////////////////////////
            // update
            /////////////////////////////////////////////////
            foreach (var resource in frame.Resources)
            {
                switch (resource.RenderResourceType)
                {
                    case RenderResourceType.Texture:
                        //TextureManager.Ensure(device, resource as TextureResource);
                        break;

                    case RenderResourceType.Sampler:
                        //SamplerManager.Ensure(device, resource as SamplerResource);
                        break;

                    case RenderResourceType.Shader:
                        m_shaderManager.Ensure(D3DDevice, resource as ShaderResource);
                        break;

                    case RenderResourceType.VertexBuffer:
                        m_vertexBufferManager.Ensure(D3DDevice, resource as VertexBufferResource);
                        break;

                    case RenderResourceType.BlendState:
                        //BlendStateManager.Ensure(device, resource as BlendStateResource);
                        break;

                    case RenderResourceType.DepthStencilState:
                        //DepthStencilStateManager.Ensure(device, resource as DepthStencilStateResource);
                        break;

                    default:
                        throw new NotImplementedException(resource.ToString());
                }
            }

            /////////////////////////////////////////////////
            // render
            /////////////////////////////////////////////////
            m_pass = new ShaderPass();
            using (Backbuffer = SwapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
            using (RTV = new SharpDX.Direct3D11.RenderTargetView(D3DDevice, Backbuffer))
            {
                var context = D3DDevice.ImmediateContext;
                foreach (var c in frame.Commands)
                {
                    switch (c.RenderCommandType)
                    {
                        /*
                        case RenderCommandType.RenderTargets_Set:
                            {
                                var command = c as RenderTargetsSetCommand;
                                var depthStencil = m_resources.TextureManager.Get(command.DepthStencil);
                                var renderTargets = m_resources.TextureManager.Get(command.RenderTargets);
                                context.OutputMerger.SetTargets(
                                    depthStencil != null ? depthStencil.DepthStencilView : null
                                    , renderTargets.Select(r => r.RenderTargetView).ToArray());

                            }
                            break;

                        case RenderCommandType.Viewport_Set:
                            {
                                var command = c as ViewportSetCommand;
                                context.Rasterizer.SetViewports(new SharpDX.ViewportF[] { command.Viewport });
                            }
                            break;
                            */

                        case RenderCommandType.Clear_Backbuffer:
                            {
                                var command = c as BackbufferClearCommand;
                                context.ClearRenderTargetView(RTV, command.Color.ToSharpDX());
                                context.OutputMerger.SetTargets((SharpDX.Direct3D11.DepthStencilView)null, new SharpDX.Direct3D11.RenderTargetView[] { RTV });
                                context.Rasterizer.SetViewports(new [] {
                                    new SharpDX.Mathematics.Interop.RawViewportF
                                    {
                                        X=0,
                                        Y=0,
                                        Width=Backbuffer.Description.Width,
                                        Height=Backbuffer.Description.Height,
                                    }
                                });
                            }
                            break;

                        /*
                    case RenderCommandType.Clear_Color:
                        {
                            var command = c as RenderTargetClearCommand;
                            var renderTarget = m_resources.TextureManager.Get(command.ResourceID);
                            if (renderTarget != null)
                            {
                                context.ClearRenderTargetView(renderTarget.RenderTargetView, command.Color);
                            }
                        }
                        break;

                    case RenderCommandType.Clear_Depth:
                        {
                            var command = c as DepthStencilClearCommand;
                            var depthStencil = m_resources.TextureManager.Get(command.ResourceID);
                            if (depthStencil != null)
                            {
                                context.ClearDepthStencilView(depthStencil.DepthStencilView
                                    , SharpDX.Direct3D11.DepthStencilClearFlags.Depth
                                    , command.Depth, command.Stencil);
                            }
                        }
                        break;
                        */

                        case RenderCommandType.VertexBuffer_Update:
                        {
                            var command = c as VertexBufferUpdateCommand;
                            var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID);
                            if (vertexBuffer != null)
                            {
                                if (command.Ptr != IntPtr.Zero)
                                {
                                    var data = new SharpDX.DataBox(command.Ptr);
                                    context.UpdateSubresource(data, vertexBuffer.Vertices);
                                }
                            }
                        }
                        break;

                        case RenderCommandType.VertexBuffer_Set:
                            {
                                var command = c as VertexBufferSetCommand;
                                var vertexBuffer = m_vertexBufferManager.Get(command.ResourceID);
                                if (vertexBuffer != null)
                                {
                                    context.InputAssembler.PrimitiveTopology = vertexBuffer.Topology;

                                    context.InputAssembler.SetVertexBuffers(0,
                                        new SharpDX.Direct3D11.VertexBufferBinding(vertexBuffer.Vertices
                                            , vertexBuffer.Stride, 0));
                                    if (vertexBuffer.Indices != null)
                                    {
                                        context.InputAssembler.SetIndexBuffer(vertexBuffer.Indices, SharpDX.DXGI.Format.R32_UInt, 0);
                                    }

                                    m_vertexBuffer = vertexBuffer;
                                }
                            }
                            break;

                        case RenderCommandType.ShaderVriable_Set:
                            {
                                var command = c as ShaderVariableSetCommand;
                                m_pass.SetConstantVariable(command);
                            }
                            break;

                        /*
                    case RenderCommandType.ShaderTexture_Set:
                        {
                            var command = c as ShaderTextureSetCommand;
                            var texture = m_resources.TextureManager.Get(command.ResourceID);
                            if (texture != null)
                            {
                                m_pass.SetSRV(context, command.Key, texture.ShaderResourceView);
                            }
                        }
                        break;

                    case RenderCommandType.ShaderSampler_Set:
                        {
                            var command = c as ShaderSamplerSetCommand;
                            Pass.SetSampler(command);
                        }
                        break;
                        */

                        case RenderCommandType.Shader_Set:
                            {
                                var command = c as ShaderSetCommand;
                                switch (command.ShaderStage)
                                {
                                    case ShaderStage.Vertex:
                                        {
                                            var vertexShader = m_shaderManager.Get(command.ResourceID) as VertexShaderStage;
                                            if (vertexShader != null)
                                            {
                                                context.VertexShader.Set(vertexShader.Shader);
                                                //context.InputAssembler.InputLayout = vertexShader.VertexLayout;
                                                m_pass.VertexShader = vertexShader;
                                            }
                                        }
                                        break;

                                    case ShaderStage.Geometry:
                                        {
                                            var geometryShader = m_shaderManager.Get(command.ResourceID) as GeometryShaderStage;
                                            if (geometryShader != null)
                                            {
                                                context.GeometryShader.Set(geometryShader.Shader);
                                                m_pass.GeometryShader = geometryShader;
                                            }
                                        }
                                        break;

                                    case ShaderStage.Pixel:
                                        {
                                            var pixelShader = m_shaderManager.Get(command.ResourceID) as PixelShaderStage;
                                            if (pixelShader != null)
                                            {
                                                context.PixelShader.Set(pixelShader.Shader);
                                                m_pass.PixelShader = pixelShader;
                                            }
                                        }
                                        break;

                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                            break;

                        case RenderCommandType.Shader_DrawSubMesh:
                            {
                                var command = c as ShaderDrawSubMeshCommand;
                                if (m_pass.VertexShader != null)
                                {
                                    context.InputAssembler.InputLayout = m_pass.VertexShader.VertexLayout;
                                    // 定数バッファの適用
                                    m_pass.Apply(context);

                                    if (m_vertexBuffer != null)
                                    {
                                        if (m_vertexBuffer.Indices != null)
                                        {
                                            context.DrawIndexed(command.Count, command.Offset, 0);
                                        }
                                        else
                                        {
                                            context.Draw(command.Count, command.Offset);
                                        }
                                    }
                                }
                            }
                            break;

                            /*
                        case RenderCommandType.BlendState_Set:
                            {
                                var command = c as BlendStateSetCommand;
                                var blendState = m_resources.BlendStateManager.Get(command.ResourceID);
                                if (blendState == null)
                                {
                                    return;
                                }
                                context.OutputMerger.SetBlendState(blendState.State, SharpDX.Color4.White);
                            }
                            break;

                        case RenderCommandType.DepthStencilState_Set:
                            {
                                var command = c as DepthStencilStateSetCommand;
                                var depthStencilState = m_resources.DepthStencilStateManager.Get(command.ResourceID);
                                if (depthStencilState == null)
                                {
                                    return;
                                }
                                context.OutputMerger.SetDepthStencilState(depthStencilState.State);
                            }
                            break;
                            */
                    }
                }
                context.Flush();
            }
            Backbuffer = null;
            RTV = null;

            /////////////////////////////////////////////////
            // flip
            /////////////////////////////////////////////////
            var flags = SharpDX.DXGI.PresentFlags.None;
            flags|=SharpDX.DXGI.PresentFlags.DoNotWait;
            SwapChain.Present(0, flags, new SharpDX.DXGI.PresentParameters());
        }