private void SetDevice(ILogger logger, DX11DisplayManager displaymanager, int adapterid)
        {
            Adapter1 adapter = this.DisplayManager.FindAdapter(adapterid);

            logger.Log(LogType.Message, "Creating device for adapter " + adapter.Description.Description);

            DX11RenderContext context;

#if DEBUG
            try
            {
                context = new DX11RenderContext(adapter, this.flags);
            }
            catch
            {
                logger.Log(LogType.Warning, "Could not create Debug device, if you want debug informations make sure DirectX SDK is installed");
                logger.Log(LogType.Warning, "Creating default DirectX 11 device");
                this.flags = DeviceCreationFlags.BgraSupport;
                context    = new DX11RenderContext(adapter, this.flags);
            }
#else
            context = new DX11RenderContext(adapter, this.flags);
#endif

            context.Initialize();
            this.contexts.Add(adapterid, context);
        }
        /// <summary>
        /// Returns true if the specified adapter is software rendering adapter
        /// </summary>
        /// <param name="adapter">adapter</param>
        /// <returns>true if the specified adapter is software rendering adapter</returns>
        public static bool IsSoftwareRenderingAdapter(Adapter1 adapter)
        {
            var adapterDescription1 = adapter.Description1;

            return((((int)adapterDescription1.Flags & 2) != 0) ||                                     // SharpDX 2.5 does not have DXGI_ADAPTER_FLAG_SOFTWARE in AdapterFlags enum
                   (adapterDescription1.VendorId == 0x1414 && adapterDescription1.DeviceId == 0x8c)); // "Microsoft Basic Render Driver" is identified by by specified VendorId and DeviceId - it is the same as Software rendered (WARP) so we do not want to show it 2 times
        }
Example #3
0
        public CompositionDevice(Adapter1 adapter, Device2D device2D)
        {
            Contract.Requires(device2D != null);

            _DxgiFactory = new Lazy<Factory1>();

            Adapter1 newAdapter = adapter;

            if(adapter == null)
            {
                newAdapter = _DxgiFactory.Value.GetAdapter1(0);
            }
            #if DEBUG
            _Device3D = new Device1(
                newAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0);
            #else
            _Device3D = new Device1(
                newAdapter,
                DeviceCreationFlags.BgraSupport,
                FeatureLevel.Level_10_0);
            #endif
            if(adapter == null)
            {
                newAdapter.Dispose();
            }

            _Compositor = new Compositor(_Device3D, device2D);

            device2D.Resources.RegisterEffect<ColorOutputEffect>();
            device2D.Resources.RegisterEffect<GaussianBlurEffect>();
            device2D.Resources.RegisterEffect<DropShadowEffect>();
            device2D.Resources.RegisterEffect<BoxBlurEffect>();
        }
Example #4
0
 public Wiring()
 {
     _factory = new Factory1();
     // Only works as long as you're only using one graphics card. So, TODO to change this someday.
     _adapter = _factory.GetAdapter1(0);
     // Create device from Adapter
     Device = new Device(_adapter, DeviceCreationFlags.Debug);
     // Works only with a single monitor. I'm only using one monitor, so I'm ignoring this. But, TODO.
     _output  = _adapter.GetOutput(0);
     _output1 = _output.QueryInterface <Output1>();
     Height   = _output.Description.DesktopBounds.Bottom - _output.Description.DesktopBounds.Top;
     Width    = _output.Description.DesktopBounds.Right - _output.Description.DesktopBounds.Left;
     Texture  = new Texture2D(Device, new Texture2DDescription
     {
         CpuAccessFlags    = CpuAccessFlags.Read,
         BindFlags         = BindFlags.None,
         Format            = Format.B8G8R8A8_UNorm,
         Width             = Width,
         Height            = Height,
         OptionFlags       = ResourceOptionFlags.None,
         MipLevels         = 1,
         ArraySize         = 1,
         SampleDescription = { Count = 1, Quality = 0 },
         Usage             = ResourceUsage.Staging
     });
     OutputDuplication = _output1.DuplicateOutput(Device);
 }
Example #5
0
 public DX11RenderContext(Adapter1 adapter, DeviceCreationFlags flags = DeviceCreationFlags.None)
 {
     this.Device               = new Device(adapter, flags, GetFeatureLevels());
     this.Adapter              = adapter;
     this.Factory              = this.Device.Factory as Factory1;
     this.immediatecontext     = this.Device.ImmediateContext;
     this.CurrentDeviceContext = this.immediatecontext;
 }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the AdapterCapabilitiesBase class.
        /// </summary>
        protected AdapterCapabilitiesBase(Adapter1 adapter)
        {
            Adapter = adapter;

            if (adapter != null)
            {
                AdapterDescription1 = adapter.Description1; // Cache the Description1 struct
            }
        }
Example #7
0
 public DirectXOutput(Adapter1 adapter,
                      SharpDX.Direct3D11.Device device,
                      OutputDuplication outputDuplication,
                      Texture2D texture2D)
 {
     Adapter           = adapter;
     Device            = device;
     OutputDuplication = outputDuplication;
     Texture2D         = texture2D;
 }
Example #8
0
        private static void InitDevice()
        {
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(0);

            // Create device from Adapter
            //device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_1);
            device = new SharpDX.Direct3D11.Device(adapter);
        }
Example #9
0
 private void ChooseAdapter_FormClosing(object sender, FormClosingEventArgs e)
 {
     if ((e.CloseReason == CloseReason.UserClosing || e.CloseReason == CloseReason.None) && DialogResult == DialogResult.OK)
     {
         if (listViewMain.SelectedItems.Count > 0)
         {
             Adapter = (Adapter1)listViewMain.SelectedItems[0].Tag;
         }
     }
 }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        private GraphicsAdapter(int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter = ToDispose(Factory.GetAdapter1(adapterOrdinal));
            Description = adapter.Description1;
            var outputs = adapter.Outputs;

            outputs1 = new GraphicsOutput[outputs.Length];
            for (var i = 0; i < outputs.Length; i++)
                outputs1[i] = new GraphicsOutput(outputs[i]);
        }
 private static Output1 CreateOutput1(int whichOutputDevice, Adapter1 adapter)
 {
     try
     {
         return(adapter.GetOutput(whichOutputDevice).QueryInterface <Output1>());
     }
     catch (SharpDXException)
     {
         throw new DesktopDuplicationException("Could not find the specified output device.");
     }
 }
Example #12
0
 public DirectXOutput(Adapter1 adapter,
                      SharpDX.Direct3D11.Device device,
                      OutputDuplication outputDuplication,
                      Texture2D texture2D,
                      DisplayModeRotation rotation)
 {
     Adapter           = adapter;
     Device            = device;
     OutputDuplication = outputDuplication;
     Texture2D         = texture2D;
     Rotation          = rotation;
 }
Example #13
0
        public void Init()
        {
            Dispose();

            factory = new Factory1();

            //Get first adapter
            adapter = factory.Adapters1.FirstOrDefault(x => x.Outputs.Length > 0);
            //Get device from adapter
            device = new SharpDX.Direct3D11.Device(adapter);
            //Get front buffer of the adapter
            if (adapter.GetOutputCount() < SelectedScreen + 1)
            {
                SelectedScreen = 0;
            }
            output  = adapter.GetOutput(SelectedScreen);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            var bounds    = output1.Description.DesktopBounds;
            var newWidth  = bounds.Right - bounds.Left;
            var newHeight = bounds.Bottom - bounds.Top;

            CurrentScreenBounds = new Rectangle(bounds.Left, bounds.Top, newWidth, newHeight);
            if (newWidth != width || newHeight != height)
            {
                ScreenChanged?.Invoke(this, CurrentScreenBounds);
            }
            width  = newWidth;
            height = newHeight;

            CurrentFrame  = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            PreviousFrame = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture    = new Texture2D(device, textureDesc);
            duplicatedOutput = output1.DuplicateOutput(device);

            NeedsInit = false;
        }
        /// <summary>
        /// Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param>
        public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice)
        {
            this.mWhichOutputDevice = whichOutputDevice;
            Adapter1 adapter = null;

            try
            {
                adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            this.mDevice = new Device(adapter);
            Output output = null;

            try
            {
                output = adapter.GetOutput(whichOutputDevice);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            var output1 = output.QueryInterface <Output1>();

            this.mOutputDesc  = output.Description;
            this.mTextureDesc = new Texture2DDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = this.mOutputDesc.DesktopBounds.Right,
                Height            = this.mOutputDesc.DesktopBounds.Bottom,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                this.mDeskDupl = output1.DuplicateOutput(mDevice);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }
        }
Example #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            Connection1.ConnectionString = "Data Source=.;Initial Catalog=amlak;Integrated Security=True";

            Adapter1.SelectCommand.Connection  = Connection1;
            Adapter1.SelectCommand.CommandText = "SELECT * FROM jadidvilla WHERE adress like '%" + txtadress.Text.Trim() + "%'";

            DataTable dt = new DataTable();

            Adapter1.Fill(dt);
            grid1.DataSource = dt;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="defaultFactory">The default factory.</param>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        internal GraphicsAdapter(Factory1 defaultFactory, int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter = defaultFactory.GetAdapter1(adapterOrdinal).DisposeBy(this);
            description = adapter.Description1;
            //var nativeOutputs = adapter.Outputs;

            var count = adapter.GetOutputCount();
            outputs = new GraphicsOutput[count];
            for (var i = 0; i < outputs.Length; i++)
                outputs[i] = new GraphicsOutput(this, i).DisposeBy(this);
        }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        private GraphicsAdapter(int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter             = ToDispose(defaultFactory.GetAdapter1(adapterOrdinal));
            Description         = adapter.Description1;
            var outputs = adapter.Outputs;

            outputs1 = new GraphicsOutput[outputs.Length];
            for (var i = 0; i < outputs.Length; i++)
            {
                outputs1[i] = ToDispose(new GraphicsOutput(this, outputs[i]));
            }
        }
Example #18
0
        private void BindData()
        {
            //Connection1.ConnectionString = ConfigurationSettings.AppSettings["connectionstring"].ToString();
            Connection1.ConnectionString = "Data Source=(local);Initial Catalog=amlak;Integrated Security=True";

            Adapter1.SelectCommand.Connection  = Connection1;
            Adapter1.SelectCommand.CommandText = "SELECT * FROM  rahnimaghaze";

            DataTable dt = new DataTable();

            Adapter1.Fill(dt);
            grid1.DataSource = dt;
        }
        internal DeskDuplImageProvider(Adapter1 Adapter, Output1 Output, Rectangle Rectangle, bool IncludeCursor)
        {
            _adapter = Adapter;
            _output  = Output;

            _includeCursor = IncludeCursor;
            _rectangle     = Rectangle;

            Width  = Rectangle.Width;
            Height = Rectangle.Height;

            Reinit();
        }
Example #20
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Connection1.ConnectionString = ConfigurationSettings.AppSettings["connectionstring"].ToString();
            Connection1.ConnectionString = "Data Source=(local);Initial Catalog=amlak;Integrated Security=True";

            Adapter1.SelectCommand.Connection  = Connection1;
            Adapter1.SelectCommand.CommandText = "SELECT * FROM  foroshande WHERE family like '%" + txtfamily.Text.Trim() + "%'";

            DataTable dt = new DataTable();

            Adapter1.Fill(dt);
            grid1.DataSource = dt;
        }
Example #21
0
 /// <inheritdoc />
 /// <summary>
 ///   Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources
 /// </summary>
 public void Dispose()
 {
     // release resources
     Duplication.Dispose();
     Output.Dispose();
     Output1?.Dispose();
     Output6?.Dispose();
     Context.Dispose();
     DxgiDevice.Dispose();
     Device.Dispose();
     Texture.Dispose();
     Adapter1.Dispose();
 }
        /// <summary>
        /// CreateAdapterCapabilitiesFromGraphicsProfile creates appropriate AdapterCapabilities from the specified GraphicsProfile.
        /// </summary>
        /// <param name="graphicsProfile">GraphicsProfile</param>
        /// <returns>AdapterCapabilities</returns>
        public AdapterCapabilitiesBase CreateAdapterCapabilitiesFromGraphicsProfile(GraphicsProfile graphicsProfile)
        {
            AdapterCapabilitiesBase adapterCapabilities;

            if (graphicsProfile.DriverType == GraphicsProfile.DriverTypes.DirectXHardware)
            {
                Adapter1 hardwarAdapter = graphicsProfile.DefaultAdapter;

                if (hardwarAdapter == null)
                {
                    if (AllAdapters.Length > 0)
                    {
                        hardwarAdapter = AllAdapters[0];
                    }
                    else
                    {
                        throw new DXEngineException("Cannot create default adapter from GraphicsProfile " + graphicsProfile.Name ?? "");
                    }
                }
                else
                {
                    var hardwarAdapterDescription1 = hardwarAdapter.Description1;

                    // Check if the adapter is in the list of available adapters
                    if (AllAdapters.FirstOrDefault(a => a.Description1.Description == hardwarAdapterDescription1.Description) == null)
                    {
                        if (AllAdapters.Length > 0)
                        {
                            hardwarAdapter = AllAdapters[0]; // Just use the first adapter
                        }
                        else
                        {
                            throw new DXEngineException("Cannot create default adapter instead of adapter specified in GraphicsProfile " + graphicsProfile.Name ?? "");
                        }
                    }
                }

                adapterCapabilities = new HardwareAdapterCapabilities(hardwarAdapter);
            }
            else if (graphicsProfile.DriverType == GraphicsProfile.DriverTypes.DirectXSoftware)
            {
                adapterCapabilities = SoftwareAdapterCapabilities;
            }
            else
            {
                adapterCapabilities = WpfAdapterCapabilities;
            }

            return(adapterCapabilities);
        }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="defaultFactory">The default factory.</param>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        internal GraphicsAdapter(Factory1 defaultFactory, int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter             = defaultFactory.GetAdapter1(adapterOrdinal).DisposeBy(this);
            description         = adapter.Description1;
            //var nativeOutputs = adapter.Outputs;

            var count = adapter.GetOutputCount();

            outputs = new GraphicsOutput[count];
            for (var i = 0; i < outputs.Length; i++)
            {
                outputs[i] = new GraphicsOutput(this, i).DisposeBy(this);
            }
        }
        /// <summary>
        /// Init some variables one times to spend execution time.
        /// </summary>
        public DirectX()
        {
            try
            {
                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);
                device = new Device(adapter);
                output = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface<Output1>();
                // get screen wize

                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.Read,
                    BindFlags = BindFlags.None,
                    Format = Format.B8G8R8A8_UNorm,
                    Width = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left,
                    Height = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top,
                    OptionFlags = ResourceOptionFlags.None,
                    MipLevels = 1,
                    ArraySize = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage = ResourceUsage.Staging
                };

                screenTexture = new Texture2D(device, textureDesc);
                try
                {
                    duplicatedOutput = output1.DuplicateOutput(device);
                }
                catch (SharpDXException e)
                {
                    if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.Unsupported.Result.Code)
                    {
                        throw new System.ApplicationException("Your system does not support DirectX 11.2 (normally on windows 7). Please use 'Use GDI Capture' option to prevent this error!");

                    }
                    else {
                        throw e;
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #25
0
        public static DesktopInfo GetDesktopInfo()
        {
            List <DesktopScreen> listOfScreens = new List <DesktopScreen>();

            using (Factory1 factory = new Factory1())
            {
                Adapter1[] adapters = factory.Adapters1;
                try
                {
                    for (int adapterIdx = 0; adapterIdx < adapters.Length; adapterIdx++)
                    {
                        Adapter1 adapter = adapters[adapterIdx];
                        Output[] outputs = adapter.Outputs;
                        try
                        {
                            for (int outputIdx = 0; outputIdx < outputs.Length; outputIdx++)
                            {
                                using (Output1 screen = outputs[outputIdx].QueryInterface <Output1>())
                                {
                                    string adapterName = string.Join(" ", adapter.Description1.Description.Split(new char[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)).Trim();
                                    string outputName  = screen.Description.DeviceName.Trim();
                                    listOfScreens.Add(new DesktopScreen((byte)adapterIdx, (byte)outputIdx, adapterName, outputName
                                                                        , (short)screen.Description.DesktopBounds.Left
                                                                        , (short)screen.Description.DesktopBounds.Top
                                                                        , (ushort)(screen.Description.DesktopBounds.Right - screen.Description.DesktopBounds.Left)
                                                                        , (ushort)(screen.Description.DesktopBounds.Bottom - screen.Description.DesktopBounds.Top)));
                                }
                            }
                        }
                        finally
                        {
                            foreach (Output output in outputs)
                            {
                                output.Dispose();
                            }
                        }
                    }
                }
                finally
                {
                    foreach (Adapter1 adapter in adapters)
                    {
                        adapter.Dispose();
                    }
                }
            }
            return(new DesktopInfo(listOfScreens.ToArray()));
        }
Example #26
0
        public DirectScreenshot(GPGPU gpu, int screenWidth, int screenHeight)
        {
            OutputFileName = "ScreenCapture.bmp";
            const int numAdapter = 0;
            const int numOutput  = 0;

            _gpu      = gpu;
            rgbValues = gpu.Allocate <GPUColorBGRA>(screenWidth * screenHeight);
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            output  = adapter.GetOutput(numOutput);
            output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            width  = screenWidth;
            height = screenHeight;


            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture = new Texture2D(device, textureDesc);

            // Duplicate the output
            duplicatedOutput = output1.DuplicateOutput(device);

            var screenResource = BeginCapture(out var pp);

            screenResource.Dispose();
            duplicatedOutput.ReleaseFrame();
        }
Example #27
0
        public Adapter1 GetPrimaryAdapter()
        {
            if (this.PrimaryAdapter != null)
            {
                return(this.PrimaryAdapter);
            }

            var adapters = this.GetAdapters();

            if (adapters.Count > 0)
            {
                this.PrimaryAdapter = adapters[0];
            }

            return(this.PrimaryAdapter);
        }
Example #28
0
        internal static Output1 GetOutput1(this Adapter1 adapter, string display)
        {
            var count = adapter.GetOutputCount();

            for (var i = 0; i < count; i++)
            {
                using (var output = adapter.GetOutput(i))
                {
                    if (output.Description.DeviceName == display)
                    {
                        return(output.QueryInterface <Output1>());
                    }
                }
            }
            throw new ArgumentException($"Invalid display: {display}");
        }
        /// <summary>
        /// Init some variables one times to spend execution time.
        /// </summary>
        public DirectX()
        {
            try
            {
                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);
                device  = new Device(adapter);
                output  = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface <Output1>();
                // get screen wize

                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left,
                    Height            = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                };

                screenTexture = new Texture2D(device, textureDesc);
                try
                {
                    duplicatedOutput = output1.DuplicateOutput(device);
                }
                catch (SharpDXException e)
                {
                    if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.Unsupported.Result.Code)
                    {
                        throw new System.ApplicationException("Your system does not support DirectX 11.2 (normally on windows 7). Please use 'Use GDI Capture' option to prevent this error!");
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #30
0
        /*Multi-Thread Variable*/

        /// <summary>
        /// Create LocalCapture to capture screen (by DXGI.)
        /// </summary>
        /// <param name="bitmapBuffer">Communication pipe with other threads. It stores some processing Mat and some unused Mat</param>
        /// <param name="numOutput"># of output device (i.e. monitor).</param>
        /// <param name="numAdapter"># of output adapter (i.e. iGPU). </param>
        public LocalCapture(BitmapBuffer bitmapBuffer, int numOutput = 0, int numAdapter = 0)
        {
            // Create DXGI Factory1
            factory = new Factory1();
            adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            output  = adapter.GetOutput(numOutput);
            output1 = output.QueryInterface <Output1>();


            // Width/Height of desktop to capture
            width  = ((Rectangle)output.Description.DesktopBounds).Width;
            height = ((Rectangle)output.Description.DesktopBounds).Height;

            // Create Staging texture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            screenTexture = new Texture2D(device, textureDesc);

            // Duplicate the output
            duplicatedOutput = output1.DuplicateOutput(device);

            //Create enough UnusedMat
            for (int i = 0; i < PreCreateMatCount; ++i)
            {
                bitmapBuffer.PushUnusedMat(CreateSuitableMat());
            }

            //Save the buffer
            this.bitmapBuffer = bitmapBuffer;
        }
Example #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        private GraphicsAdapter(int adapterOrdinal)
        {
            this.adapterOrdinal   = adapterOrdinal;
            adapter               = ToDispose(Factory.GetAdapter1(adapterOrdinal));
            Description           = adapter.Description1;
            outputs               = adapter.Outputs;
            SupportedDisplayModes = new DisplayMode[0];

            // Enumerate outputs if any.
            if (outputs != null && outputs.Length > 0)
            {
                outputDescription     = outputs[0].Description;
                SupportedDisplayModes = GetSupportedDisplayModes();
                foreach (var output in outputs)
                {
                    ToDispose(output);
                }

                foreach (var supportedDisplayMode in SupportedDisplayModes)
                {
                    if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width &&
                        supportedDisplayMode.Height == outputDescription.DesktopBounds.Height &&
                        supportedDisplayMode.Format == Format.R8G8B8A8_UNorm)
                    {
                        // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                        CurrentDisplayMode = new DisplayMode(Format.R8G8B8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                        break;
                    }
                }

                if (CurrentDisplayMode == null)
                {
                    foreach (var supportedDisplayMode in SupportedDisplayModes)
                    {
                        if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width &&
                            supportedDisplayMode.Height == outputDescription.DesktopBounds.Height &&
                            supportedDisplayMode.Format == Format.B8G8R8A8_UNorm)
                        {
                            // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                            CurrentDisplayMode = new DisplayMode(Format.B8G8R8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                            break;
                        }
                    }
                }
            }
        }
Example #32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="adapter1"></param>
        /// <param name="output"></param>
        /// <param name="bitmap"></param>
        /// <param name="interval"></param>
        public void InitDuplication(Adapter1 adapter1, Output output, ref Bitmap bitmap, int interval)
        {
            SelectedAdapter = adapter1;
            SelectedOutput  = output;
            if (!(Enum.GetValues(typeof(DriverType)) is int[] drivertypes))
            {
                throw new NullReferenceException();
            }
            var featurelevels = new[]
            {
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_1
            };

            foreach (var dt in drivertypes)
            {
                try
                {
                    Device = new Device((DriverType)dt, DeviceCreationFlags.None, featurelevels);
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            TextureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = ScreenDpi.Width,
                Height            = ScreenDpi.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };
            ScreenTexture    = new Texture2D(Device, TextureDesc);
            DuplicatedOutput = SelectedOutput.QueryInterface <Output1>().DuplicateOutput(Device);
            _bitmap          = bitmap;
            Interval         = interval;
        }
Example #33
0
        /// <summary>
        ///     Finds the most capable graphics card.
        /// </summary>
        /// <returns></returns>
        private static Adapter1 GetBestAdapter(out int bestAdapterIndex)
        {
            using (var dxgiFactory = new Factory1())
            {
                Adapter1 bestAdapter = null;
                bestAdapterIndex = -1;
                var  adapterIndex     = -1;
                long bestVideoMemory  = 0;
                long bestSystemMemory = 0;

                foreach (var dxgiAdapter in dxgiFactory.Adapters1)
                {
                    adapterIndex++;

                    // not skip the render only WARP device
                    if (dxgiAdapter.Description.VendorId != 0x1414 || dxgiAdapter.Description.DeviceId != 0x8c)
                    {
                        if (dxgiAdapter.Outputs == null || dxgiAdapter.Outputs.Length == 0)
                        {
                            continue;
                        }
                    }

                    var level = Device.GetSupportedFeatureLevel(dxgiAdapter);

                    if (level < FeatureLevel.Level_11_0)
                    {
                        continue;
                    }
                    long videoMemory  = (uint)dxgiAdapter.Description.DedicatedVideoMemory;
                    long systemMemory = (uint)dxgiAdapter.Description.DedicatedSystemMemory;

                    if (bestAdapter != null && videoMemory <= bestVideoMemory &&
                        (videoMemory != bestVideoMemory || systemMemory <= bestSystemMemory))
                    {
                        continue;
                    }
                    bestAdapter      = dxgiAdapter;
                    bestAdapterIndex = adapterIndex;
                    bestVideoMemory  = videoMemory;
                    bestSystemMemory = systemMemory;
                }

                return(bestAdapter);
            }
        }
Example #34
0
        private void Init()
        {
            // # of graphics card adapter
            const int numAdapter = 0;

            // # of output device (i.e. monitor)
            const int numOutput = 0;

            // Create DXGI Factory1
            var      factory = new Factory1();
            Adapter1 adapter = factory.GetAdapter1(numAdapter);

            // Create device from Adapter
            device = new Device(adapter);

            // Get DXGI.Output
            Output output  = adapter.GetOutput(numOutput);
            var    output1 = output.QueryInterface <Output1>();

            // Width/Height of desktop to capture
            width  = output.Description.DesktopBounds.Width;
            height = output.Description.DesktopBounds.Height;

            // Create Staging screenTexture CPU-accessible
            textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            outputDescription = output.Description;

            // Demo the output
            duplicatedOutput = output1.DuplicateOutput(device);

            screenTexture = new Texture2D(device, textureDesc);
        }
        /// <summary>
        /// Init some variables one times to spend execution time.
        /// </summary>
        public DirectX()
        {

            try
            {

                factory = new Factory1();
                adapter = factory.GetAdapter1(numAdapter);
                device = new Device(adapter);
                output = adapter.GetOutput(numOutput);
                output1 = output.QueryInterface<Output1>();
                // get screen wize

                textureDesc = new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.Read,
                    BindFlags = BindFlags.None,
                    Format = Format.B8G8R8A8_UNorm,
                    Width = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left,
                    Height = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top,

                    OptionFlags = ResourceOptionFlags.None,
                    MipLevels = 1,
                    ArraySize = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage = ResourceUsage.Staging
                };

                screenTexture = new Texture2D(device, textureDesc);
                duplicatedOutput = output1.DuplicateOutput(device);

           
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #36
0
 public DX11RenderContext(Adapter1 adapter, DeviceCreationFlags flags = DeviceCreationFlags.None)
 {
     this.Device = new Device(adapter, flags);
     this.immediatecontext = this.Device.ImmediateContext;
     this.CurrentDeviceContext = this.immediatecontext;
 }
Example #37
0
        public CAdapter(Adapter1 dxgiAdapter, int index)
        {
            this.dxgiAdapter = dxgiAdapter;
            this.index = index;

            AdapterDescription1 dxgiDesc = dxgiAdapter.Description1;
            desc = new AdapterDescription
            {
                Description = dxgiDesc.Description,
                VendorId = dxgiDesc.VendorId,
                DeviceId = dxgiDesc.DeviceId,
                SubSysId = dxgiDesc.SubsystemId,
                Revision = dxgiDesc.Revision,
                DedicatedVideoMemory = dxgiDesc.DedicatedVideoMemory,
                DedicatedSystemMemory = dxgiDesc.DedicatedSystemMemory,
                SharedSystemMemory = dxgiDesc.SharedSystemMemory,
                AdapterLuidHigh = (int)(dxgiDesc.Luid >> 32),
                AdapterLuidLow = (int)(dxgiDesc.Luid & 0x00000000FFFFFFFF),
                Flags = CtBeholder.AdapterFlags(dxgiDesc.Flags)
            };

            outputs = dxgiAdapter.Outputs.Select(o => new COutput(o)).ToArray();

            using (var d3dDevice = new Device(dxgiAdapter))
            {
                switch (d3dDevice.FeatureLevel)
                {
                    case FeatureLevel.Level_9_1: apiVersion = new ApiVersion(9, 1); break;
                    case FeatureLevel.Level_9_3: apiVersion = new ApiVersion(9, 3); break;
                    case FeatureLevel.Level_9_2: apiVersion = new ApiVersion(9, 2); break;
                    case FeatureLevel.Level_10_0: apiVersion = new ApiVersion(10, 0); break;
                    case FeatureLevel.Level_10_1: apiVersion = new ApiVersion(10, 1); break;
                    case FeatureLevel.Level_11_0: apiVersion = new ApiVersion(11, 0); break;
                    default: throw new ArgumentOutOfRangeException("d3dDevice.FeatureLevel");
                }

                restrictions = new AdapterRestrictions
                {
                    UniformBufferSlots = CommonShaderStage.ConstantBufferApiSlotCount,
                    SamplerSlots = CommonShaderStage.SamplerSlotCount,
                    ShaderResourceSlots = CommonShaderStage.InputResourceSlotCount,
                    UnorderedAccessResourceSlots = ComputeShaderStage.UnorderedAccessViewSlotCount,
                    MaxVertexStreams = InputAssemblerStage.VertexInputResourceSlotCount,
                    MaxVertexStreamElementCount = InputAssemblerStage.VertexInputStructureElementCount,
                    MaxStreamOutputTargets = 4,
                    MaxViewports = 16,
                    MaxRenderTargets = 8,
                    MaxThreadGroupsX = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumX : 768,
                    MaxThreadGroupsY = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumY : 768,
                    MaxThreadGroupsZ = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumZ : 1,
                    MaxThreadGroupsTotal = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumThreadsPerGroup : 768
                };

                var allFormats = ((ExplicitFormat[])Enum.GetValues(typeof(ExplicitFormat))).Select(x => (Format)x).ToArray();

                formatsSupport = allFormats.Select(d3dDevice.CheckFormatSupport).ToArray();
                formatInfos = allFormats.Where(f => f != 0).Select(CtBeholder.FormatInfo).ToArray();
                //depthStencilFormatInfos = allFormats.Where(f => (formatsSupport[(int)f] & DepthStencilSupportMask) != 0).Select(CtBeholder.DepthStencilFormatInfo).ToArray();
                vertexElementFormats = allFormats.Where(f => (formatsSupport[(int)f] & VertexElementSupportMask) != 0).Select(f => (ExplicitFormat)f).ToArray();

                multisampleQualityLevels = new int[allFormats.Length, MultisampleCountsToTry.Length];

                for (int i = 0; i < allFormats.Length; i++)
                    for (int j = 0; j < MultisampleCountsToTry.Length; j++)
                        multisampleQualityLevels[i, j] = d3dDevice.CheckMultisampleQualityLevels((Format)i, MultisampleCountsToTry[j]);
            }
            /*
            using (var writer = new System.IO.StreamWriter("Formats.txt"))
            {
                for (int i = 0; i < formatsSupport.Length; i++)
                {
                    writer.WriteLine(string.Format("{0, -30}:{1}", (Format)i, formatsSupport[i].ToString().Replace(", ", " | ")));
                }
            }*/
        }
Example #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        private GraphicsAdapter(int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter = ToDispose(Factory.GetAdapter1(adapterOrdinal));
            Description = adapter.Description1;
            outputs = adapter.Outputs;
            SupportedDisplayModes = new DisplayMode[0];

            // Enumerate outputs if any.
            if (outputs != null && outputs.Length > 0)
            {
                outputDescription = outputs[0].Description;
                SupportedDisplayModes = GetSupportedDisplayModes();
                foreach (var output in outputs)
                {
                    ToDispose(output);
                }

                foreach (var supportedDisplayMode in SupportedDisplayModes)
                {
                    if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width
                        && supportedDisplayMode.Height == outputDescription.DesktopBounds.Height
                        && supportedDisplayMode.Format == Format.R8G8B8A8_UNorm)
                    {
                        // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                        CurrentDisplayMode = new DisplayMode(Format.R8G8B8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                        break;
                    }
                }

                if (CurrentDisplayMode == null)
                {
                    foreach (var supportedDisplayMode in SupportedDisplayModes)
                    {
                        if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width
                            && supportedDisplayMode.Height == outputDescription.DesktopBounds.Height
                            && supportedDisplayMode.Format == Format.B8G8R8A8_UNorm)
                        {
                            // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                            CurrentDisplayMode = new DisplayMode(Format.B8G8R8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                            break;
                        }
                    }
                }
            }
        }
 private Output InitializeOutput(Adapter1 adapter, int outputIndex)
 {
     try
     {
         return adapter.GetOutput(outputIndex);
     }
     catch (SharpDXException)
     {
         throw new ScreenException("Unable to initialize the output device.");
     }
 }
Example #40
0
        public void Initialize()
        {
            DXGIAdapter = new Factory1().GetAdapter1(0);
            var swapDescription = new SwapChainDescription()
            {
                BufferCount = 1,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = Output.Handle,
                IsWindowed = true,
                ModeDescription =
                    new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };
            #if DEBUG
            Device.CreateWithSwapChain(DXGIAdapter, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, new[] { FeatureLevel.Level_10_0 }, swapDescription, out D3DDevice,
                                       out SChain);
            #else
            Device.CreateWithSwapChain(DXGIAdapter, DeviceCreationFlags.BgraSupport, new[] { FeatureLevel.Level_10_0 }, swapDescription, out D3DDevice,
                                       out SChain);
            #endif
            Context = D3DDevice.ImmediateContext;

            D2DInterop = new D2DInteropHandler(this);

            EnableWinEvents();
            InitOnce();
            InitDevice();
        }