Example #1
0
        /// <summary>
        /// Creates a default D3D11 Texture with forced Shared-Flag
        /// </summary>
        /// <param name="device"></param>
        /// <param name="description"></param>
        /// <param name="D3D10Dev"> </param>
        /// <param name="D2DFactory"> </param>
        public SharedTexture(D2DInteropHandler handler, Texture2DDescription description)
        {
            As11Tex = new Texture2D(handler.D3DDevice11, new Texture2DDescription()
                {
                    ArraySize = description.ArraySize,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = description.CpuAccessFlags,
                    Format = description.Format,
                    Height = description.Height,
                    MipLevels = description.MipLevels,
                    OptionFlags = ResourceOptionFlags.KeyedMutex,
                    SampleDescription = description.SampleDescription,
                    Usage = description.Usage,
                    Width = description.Width
                });

            Mutex11 = new KeyedMutex(As11Tex);
            AsResource = new SlimDX.DXGI.Resource(As11Tex);

            As10Tex = handler.D3DDevice10.OpenSharedResource<SlimDX.Direct3D10.Texture2D>(AsResource.SharedHandle);
            Mutex10 = new KeyedMutex(As10Tex);
            AsSurface = As10Tex.AsSurface();
            As2DTarget = SlimDX.Direct2D.RenderTarget.FromDXGI(handler.D2DFactory, AsSurface, new RenderTargetProperties()
                                                                                                            {
                                                                                                                MinimumFeatureLevel = FeatureLevel.Direct3D10,
                                                                                                                Usage = RenderTargetUsage.None,
                                                                                                                Type = RenderTargetType.Hardware,
                                                                                                                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                                                                                                            });
        }
Example #2
0
 private void InitRenderTarget()
 {
     using (Dx11.Texture2D backBuffer
                = Dx11.Resource.FromSwapChain <Dx11.Texture2D>(SwapChain, 0)
                )
     {
         RenderTarget = new Dx11.RenderTargetView(GraphicsDevice, backBuffer);
         GraphicsDevice.ImmediateContext.OutputMerger.SetTargets(RenderTarget);
     }
 }
Example #3
0
        /// <summary>
        ///     レンダーターゲットを初期化します.
        /// </summary>
        private void InitializeTargets()
        {
            {
                // Direct3D レンダーターゲットの作成
                var desc = new D3D.Texture2DDescription
                {
                    Width             = size.Width,
                    Height            = size.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.B8G8R8A8_UNorm,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = D3D.ResourceUsage.Default,
                    BindFlags         = D3D.BindFlags.RenderTarget,
                    CpuAccessFlags    = D3D.CpuAccessFlags.None,
                    OptionFlags       = D3D.ResourceOptionFlags.GdiCompatible
                };
                d3dRenderTarget = new D3D.Texture2D(deviceManager.Device, desc);
            }
            {
                // レンダーターゲットビューの作成
                D3D.Texture2D target = D3DRenderTarget;
                var           desc   = new D3D.RenderTargetViewDescription
                {
                    Format    = target.Description.Format,
                    Dimension =
                        target.Description.SampleDescription.Count > 1
                            ? D3D.RenderTargetViewDimension.Texture2DMultisampled
                            : D3D.RenderTargetViewDimension.Texture2D,
                    MipSlice = 0
                };
                d3dRenderTargetView = new D3D.RenderTargetView(deviceManager.Device, target, desc);
            }
            // DXGIサーフェスの取得
            dxgiSurface = d3dRenderTarget.AsSurface();
            {
                // レンダーターゲットの作成
                var properties = new D2D.RenderTargetProperties
                {
                    Type                = D2D.RenderTargetType.Default,
                    PixelFormat         = new D2D.PixelFormat(dxgiSurface.Description.Format, D2D.AlphaMode.Premultiplied),
                    HorizontalDpi       = 0,
                    VerticalDpi         = 0,
                    Usage               = D2D.RenderTargetUsage.GdiCompatible,
                    MinimumFeatureLevel = D2D.FeatureLevel.Direct3D10
                };
                d2dRenderTarget           = D2D.RenderTarget.FromDXGI(deviceManager.D2DFactory, dxgiSurface, properties);
                d2dGdiInteropRenderTarget = new D2D.GdiInteropRenderTarget(d2dRenderTarget);
            }

            if (TargetsInitialized != null)
            {
                TargetsInitialized(this, new EventArgs());
            }
        }
Example #4
0
        public void Initialize()
        {
            maxParticles = parameters.size * parameters.size;
            particles    = new float[maxParticles];
            renderData   = new ParticleVertex[maxParticles * 6];
            simulater.Initialize();
            //allParticlesRTV =new RenderTarget2D(game.GraphicsDevice, game.GraphicsDevice.Viewport.Width, game.GraphicsDevice.Viewport.Height, 1, SurfaceFormat.Color);
            allParticles = new Texture2D(game.Device, new Texture2DDescription()
            {
                ArraySize      = 1,
                CpuAccessFlags = CpuAccessFlags.None,
                BindFlags      =
                    BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = height,
                Width             = width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription =
                    new SlimDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            });
            allParticlesRTV = new RenderTargetView(game.Device, allParticles);
            allParticlesSRV = new ShaderResourceView(game.Device, allParticles);


            //game.GraphicsDevice.SetRenderTarget(0, allParticlesRTV);
            //game.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0f, 0);
            //game.GraphicsDevice.SetRenderTarget(0, null);
            //allParticles = allParticlesRTV.GetTexture();

            timeTexture = new Texture2D(game.Device, new Texture2DDescription()
            {
                ArraySize         = 1,
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.R32_Float,
                Height            = parameters.size,
                Width             = parameters.size,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription =
                    new SlimDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            });
            timeTextureRSV = new ShaderResourceView(game.Device, timeTexture);
            timeTarget     = new RenderTargetView(game.Device, timeTexture);
        }
        // Inicializácia zariadenia a ďalších potrebných zdrojov pre rendering. Metóda vráti true, ak skončí bez chyby.
        private bool Initialize3D()
        {
            try
            {
                //Vytvorenie objektu typu SwapChainDescription a nastavenie jeho vlastností
                m_swapChainDesc = new DXGI.SwapChainDescription();
                m_swapChainDesc.OutputHandle    = panelVykresli.Handle;
                m_swapChainDesc.IsWindowed      = true;
                m_swapChainDesc.BufferCount     = 1;
                m_swapChainDesc.Flags           = DXGI.SwapChainFlags.AllowModeSwitch;
                m_swapChainDesc.ModeDescription = new DXGI.ModeDescription(
                    panelVykresli.Width,
                    panelVykresli.Height,
                    new Rational(60, 1),
                    DXGI.Format.R8G8B8A8_UNorm);
                m_swapChainDesc.SampleDescription = new DXGI.SampleDescription(1, 0);
                m_swapChainDesc.SwapEffect        = DXGI.SwapEffect.Discard;
                m_swapChainDesc.Usage             = DXGI.Usage.RenderTargetOutput;

                ///Vytvorenie objektu zariadenie a SwapChain spoločne jednou metódou
                DX11.Device.CreateWithSwapChain(
                    DriverType.Warp,                //Typ renderovacieho zariadenia: SW renderer: Reference, Warp, Hardware - hardvérový renderer:  http://slimdx.org/tutorials/DeviceCreation.php
                    DeviceCreationFlags.None,       //Žiadne extra návestia
                    m_levels,                       //Kompatibilita s verziami DX
                    m_swapChainDesc,                //Objekt typu SwapChainDescription
                    out m_device,                   //vráti Direct3D zariadenie reprezentujúce virtuálny graf. HW
                    out m_swapChain);               //vráti SwapChain pre prácu s baframi

                //Vytvorenie zobrazovacej plochy - celé okno ap.
                var m_viewPort = new Viewport(0.0f, 0.0f, panelVykresli.Width, panelVykresli.Height);

                //Vytvorenie objektu zadného bafra a cieľa renderovania
                DX11.Texture2D m_backBuffer = Texture2D.FromSwapChain <Texture2D>(m_swapChain, 0);
                m_renderTarget = new RenderTargetView(m_device, m_backBuffer);

                m_deviceContext = m_device.ImmediateContext;             //Nastavenie kontextu zariadenia, ktorý obsahuje nastavenia pre D3D zariadenie, tu priame renderovanie bez vytvárania príkazového zoznamu. Pozri: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476880%28v=vs.85%29.aspx
                m_deviceContext.Rasterizer.SetViewports(m_viewPort);     //Nastavenie zobrazovacej plochy
                m_deviceContext.OutputMerger.SetTargets(m_renderTarget); //Nastavenie cieľa renderovania
            }
            catch (Exception ex)
            {
                MessageBox.Show("Chyba počas inicializácie Direct3D11: \n" + ex.Message);
                m_initialized = false;
            }

            return(m_initialized);
        }
Example #6
0
 private void InitializeDepthStencil()
 {
     using (var depthBuffer = new Dx11.Texture2D(device,
                                                 new Dx11.Texture2DDescription()
     {
         ArraySize = 1, BindFlags = Dx11.BindFlags.DepthStencil,
         Format = Dxgi.Format.D32_Float,
         Width = ClientSize.Width, Height = ClientSize.Height,
         MipLevels = 1, SampleDescription = new Dxgi.SampleDescription(count, qual - 1),
     })) {
         depthStencil = new Dx11.DepthStencilView(device, depthBuffer,
                                                  new Dx11.DepthStencilViewDescription()
         {
             Format = Dxgi.Format.D32_Float, Dimension = Dx11.DepthStencilViewDimension.Texture2DMultisampled,
         });
     }
     device.ImmediateContext.OutputMerger.SetTargets(depthStencil, renderTarget);
 }
Example #7
0
        private void InitDepthStencil()
        {
            Dx11.Texture2DDescription depthBufferDesc = new Dx11.Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = Dx11.BindFlags.DepthStencil,
                Format            = Dxgi.Format.D32_Float,
                Width             = ClientSize.Width,
                Height            = ClientSize.Height,
                MipLevels         = 1,
                SampleDescription = new Dxgi.SampleDescription(1, 0)
            };

            using (Dx11.Texture2D depthBuffer = new Dx11.Texture2D(GraphicsDevice, depthBufferDesc))
            {
                DepthStencil = new Dx11.DepthStencilView(GraphicsDevice, depthBuffer);
            }
        }
Example #8
0
        /// <summary>
        ///     レンダーターゲットを破棄します.
        /// </summary>
        private void DestroyTargets()
        {
            if (DXGISurface != null && TargetsDestroying != null)
            {
                TargetsDestroying(this, new EventArgs());
            }

            SafeRelease(d2dGdiInteropRenderTarget);
            SafeRelease(d2dRenderTarget);
            SafeRelease(dxgiSurface);
            SafeRelease(d3dRenderTargetView);
            SafeRelease(d3dRenderTarget);

            d2dGdiInteropRenderTarget = null;
            d2dRenderTarget           = null;
            dxgiSurface         = null;
            d3dRenderTargetView = null;
            d3dRenderTarget     = null;
        }
Example #9
0
        /// <summary>
        /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="syncInterval"></param>
        /// <param name="flags"></param>
        /// <returns>The HRESULT of the original method</returns>
        int PresentHook(IntPtr swapChainPtr, int syncInterval, SlimDX.DXGI.PresentFlags flags)
        {
            if (swapChainPtr != _swapChainPointer)
            {
                _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
            }
            SwapChain swapChain = _swapChain;

            //using (SlimDX.DXGI.SwapChain swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr))
            {
                try
                {
                    #region Screenshot Request
                    if (this.Request != null)
                    {
                        this.DebugMessage("PresentHook: Request Start");
                        DateTime startTime = DateTime.Now;
                        using (Texture2D texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0))
                        {

                            System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height);
                            if (this.Request.RegionToCapture.Width > 0) { regionToCapture = this.Request.RegionToCapture; }
                            var theTexture = texture;

                            // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture
                            Texture2D textureResolved = null;
                            if (texture.Description.SampleDescription.Count > 1)
                            {
                                this.DebugMessage("PresentHook: resolving multi-sampled texture");
                                // texture is multi-sampled, lets resolve it down to single sample
                                textureResolved = new Texture2D(texture.Device, new Texture2DDescription()
                                {
                                    CpuAccessFlags = CpuAccessFlags.None,
                                    Format = texture.Description.Format,
                                    Height = texture.Description.Height,
                                    Usage = ResourceUsage.Default,
                                    Width = texture.Description.Width,
                                    ArraySize = 1,
                                    SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample
                                    BindFlags = BindFlags.None,
                                    MipLevels = 1,
                                    OptionFlags = texture.Description.OptionFlags
                                });
                                // Resolve into textureResolved
                                texture.Device.ImmediateContext.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format);

                                // Make "theTexture" be the resolved texture
                                theTexture = textureResolved;
                            }

                            // Create destination texture
                            Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription()
                            {
                                CpuAccessFlags = CpuAccessFlags.None,// CpuAccessFlags.Write | CpuAccessFlags.Read,
                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG
                                Height = regionToCapture.Height,
                                Usage = ResourceUsage.Default,// ResourceUsage.Staging,
                                Width = regionToCapture.Width,
                                ArraySize = 1,//texture.Description.ArraySize,
                                SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),// texture.Description.SampleDescription,
                                BindFlags = BindFlags.None,
                                MipLevels = 1,//texture.Description.MipLevels,
                                OptionFlags = texture.Description.OptionFlags
                            });

                            // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
                            theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
                            {
                                Top = regionToCapture.Top,
                                Bottom = regionToCapture.Bottom,
                                Left = regionToCapture.Left,
                                Right = regionToCapture.Right,
                                Front = 0,
                                Back = 1 // Must be 1 or only black will be copied
                            }, textureDest, 0, 0, 0, 0);

                            // Note: it would be possible to capture multiple frames and process them in a background thread

                            // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
                            Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
                            ThreadPool.QueueUserWorkItem(delegate
                            {
                                //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
                                //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);

                                DateTime startCopyToSystemMemory = DateTime.Now;
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
                                    ms.Position = 0;
                                    this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());

                                    DateTime startSendResponse = DateTime.Now;
                                    SendResponse(ms, requestId);
                                    this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
                                }

                                // Free the textureDest as we no longer need it.
                                textureDest.Dispose();
                                textureDest = null;
                                this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
                            });

                            // Prevent the request from being processed a second time
                            this.Request = null;

                            // Make sure we free up the resolved texture if it was created
                            if (textureResolved != null)
                            {
                                textureResolved.Dispose();
                                textureResolved = null;
                            }
                        }
                        this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
                        this.DebugMessage("PresentHook: Request End");
                    }
                    #endregion

                    #region overlay
                    if (idxhookUpdateimg != null)
                    {
                        imag = Image.FromStream(new MemoryStream(idxhookUpdateimg));
                        if (imag.Height == 1) { imag = null; }
                        idxhookUpdateimg = null;
                        this.DebugMessage("HOOKED");
                        this.DebugMessage("HWND: " + _swapChain.Description.OutputHandle.ToString());

                        if (imag != null)
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {
                                imag.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                                stream.Position = 0;

                                Texture2D working_texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
                                Texture2D new_texture = new Texture2D(working_texture.Device, new Texture2DDescription()
                                {
                                    CpuAccessFlags = CpuAccessFlags.None,// CpuAccessFlags.Write | CpuAccessFlags.Read,
                                    Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG
                                    Height = imag.Height,
                                    Usage = ResourceUsage.Default,// ResourceUsage.Staging,
                                    Width = imag.Width,
                                    ArraySize = 1,//texture.Description.ArraySize,
                                    SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),// texture.Description.SampleDescription,
                                    BindFlags = BindFlags.None,
                                    MipLevels = 1,//texture.Description.MipLevels,
                                    OptionFlags = working_texture.Description.OptionFlags
                                });
                                tx = Texture2D.FromStream(new_texture.Device, stream, (int)stream.Length);
                                working_texture.Dispose(); working_texture = null;
                                new_texture.Dispose(); new_texture = null;
                            }
                        }
                    }

                    if (imag != null && tx != null)
                    {
                        //Texture2D working_texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
                        using (Texture2D working_texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0))
                        {
                            Texture2D new_texture = new Texture2D(working_texture.Device, new Texture2DDescription()
                            {
                                CpuAccessFlags = CpuAccessFlags.None,// CpuAccessFlags.Write | CpuAccessFlags.Read,
                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG
                                Height = imag.Height,
                                Usage = ResourceUsage.Default,// ResourceUsage.Staging,
                                Width = imag.Width,
                                ArraySize = 1,//texture.Description.ArraySize,
                                SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),// texture.Description.SampleDescription,
                                BindFlags = BindFlags.None,
                                MipLevels = 1,//texture.Description.MipLevels,
                                OptionFlags = working_texture.Description.OptionFlags
                            });

                            new_texture.Device.ImmediateContext.CopySubresourceRegion(new_texture, 0, new ResourceRegion() { Top = 0, Bottom = 300, Left = 0, Right = 400, Front = 0, Back = 1 }, working_texture, 0, 0, 0, 0);
                            new_texture.Device.ImmediateContext.CopySubresourceRegion(tx, 0, new ResourceRegion() { Top = 0, Bottom = imag.Height, Left = 0, Right = imag.Width, Front = 0, Back = 1 }, working_texture, 0, 0, 0, 0);
                            working_texture.Dispose(); new_texture.Dispose(); new_texture = null;
                        }
                    }
                    #endregion

                    //globalSyncInterval = syncInterval;
                    //globalFlags = flags;

                }
                catch (Exception e)
                {
                    // If there is an error we do not want to crash the hooked application, so swallow the exception
                    this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.Message);
                    //return unchecked((int)0x8000FFFF); //E_UNEXPECTED
                }

                // As always we need to call the original method, note that EasyHook has already repatched the original method
                // so calling it here will not cause an endless recursion to this function
                return swapChain.Present(syncInterval, flags).Code;
            }
        }