public D3D11GraphicsDevice(GraphicsDeviceOptions options, SwapchainDescription?swapchainDesc)
        {
#if DEBUG
            DeviceCreationFlags creationFlags = DeviceCreationFlags.Debug;
#else
            DeviceCreationFlags creationFlags = options.Debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None;
#endif
            _device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags);
            if (swapchainDesc != null)
            {
                SwapchainDescription desc = swapchainDesc.Value;
                _mainSwapchain = new D3D11Swapchain(_device, ref desc);
            }
            _immediateContext = _device.ImmediateContext;
            _device.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists);

            Features = new GraphicsDeviceFeatures(
                computeShader: true,
                geometryShader: true,
                tessellationShaders: true,
                multipleViewports: true,
                samplerLodBias: true,
                drawBaseVertex: true,
                drawBaseInstance: true,
                fillModeWireframe: true,
                samplerAnisotropy: true,
                depthClipDisable: true,
                texture1D: true,
                independentBlend: true);

            _d3d11ResourceFactory = new D3D11ResourceFactory(this);

            PostDeviceCreated();
        }
Esempio n. 2
0
        /// <summary>
        /// Function to determine if a device supports creating resources from multiple threads.
        /// </summary>
        /// <returns>TRUE if support is available, FALSE if not.</returns>
        public bool SupportsMultithreadedCreation()
        {
            if (SupportedFeatureLevel < DeviceFeatureLevel.SM5)
            {
                return(false);
            }

            D3D.Device device = (Graphics != null) ? Graphics.D3DDevice : null;
            Tuple <GI.Factory1, GI.Adapter1, D3D.Device> tempInterfaces = null;

            try
            {
                if (device == null)
                {
                    tempInterfaces = GetDevice(VideoDeviceType, HardwareFeatureLevel);
                    device         = tempInterfaces.Item3;
                }

                bool result;
                bool dummy;

                device.CheckThreadingSupport(out result, out dummy);

                return(result);
            }
            finally
            {
                ReleaseInterfaces(tempInterfaces);
            }
        }
Esempio n. 3
0
        internal DeviceFeatures(Device device)
        {
            mapFeaturesPerFormat = new FeaturesPerFormat[256];

            // Check global features
            level              = device.FeatureLevel;
            hasComputeShaders  = device.CheckFeatureSupport(Feature.ComputeShaders);
            hasDoublePrecision = device.CheckFeatureSupport(Feature.ShaderDoubles);
            device.CheckThreadingSupport(out hasMultiThreadingConcurrentResources, out hasDriverCommandLists);

            // Check features for each DXGI.Format
            foreach (var format in Enum.GetValues(typeof(Format)))
            {
                var dxgiFormat  = (Format)format;
                var maximumMSAA = MSAALevel.None;
                var computeShaderFormatSupport = ComputeShaderFormatSupport.None;
                var formatSupport = FormatSupport.None;

                if (!ObsoleteFormatToExcludes.Contains(dxgiFormat))
                {
                    maximumMSAA = GetMaximumMSAASampleCount(device, dxgiFormat);
                    if (hasComputeShaders)
                    {
                        computeShaderFormatSupport = device.CheckComputeShaderFormatSupport(dxgiFormat);
                    }

                    formatSupport = device.CheckFormatSupport(dxgiFormat);
                }

                mapFeaturesPerFormat[(int)dxgiFormat] = new FeaturesPerFormat(dxgiFormat, maximumMSAA, computeShaderFormatSupport, formatSupport);
            }
        }
Esempio n. 4
0
        public D3D11GraphicsDevice(IntPtr hwnd, int width, int height)
        {
            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = 1,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

#if DEBUG
            DeviceCreationFlags creationFlags = DeviceCreationFlags.Debug;
#else
            DeviceCreationFlags creationFlags = DeviceCreationFlags.None;
#endif
            SharpDX.Direct3D11.Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                creationFlags,
                swapChainDescription,
                out _device,
                out _swapChain);
            _immediateContext = _device.ImmediateContext;
            _device.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists);

            Factory factory = _swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAll);

            ResourceFactory = new D3D11ResourceFactory(this);
            RecreateSwapchainFramebuffer(width, height);

            PostContextCreated();
        }
        public D3D11GraphicsDevice(GraphicsDeviceOptions options, SwapchainDescription?swapchainDesc)
        {
            DeviceCreationFlags flags = DeviceCreationFlags.None;
            bool debug = options.Debug;

#if DEBUG
            debug = true;
#endif
            if (debug)
            {
                flags = DeviceCreationFlags.Debug;
            }

            try
            {
                _device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, flags);
            }
            catch (SharpDXException ex) when(debug && (uint)ex.HResult == 0x887A002D)
            {
                // The D3D11 debug layer is not installed. Create a normal device without debug support, instead.
                _device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None);
            }

            if (swapchainDesc != null)
            {
                SwapchainDescription desc = swapchainDesc.Value;
                _mainSwapchain = new D3D11Swapchain(_device, ref desc);
            }
            _immediateContext = _device.ImmediateContext;
            _device.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists);

            Features = new GraphicsDeviceFeatures(
                computeShader: true,
                geometryShader: true,
                tessellationShaders: true,
                multipleViewports: true,
                samplerLodBias: true,
                drawBaseVertex: true,
                drawBaseInstance: true,
                drawIndirect: true,
                drawIndirectBaseInstance: true,
                fillModeWireframe: true,
                samplerAnisotropy: true,
                depthClipDisable: true,
                texture1D: true,
                independentBlend: true,
                structuredBuffer: true,
                subsetTextureView: true,
                commandListDebugMarkers: _device.FeatureLevel >= SharpDX.Direct3D.FeatureLevel.Level_11_1);

            _d3d11ResourceFactory = new D3D11ResourceFactory(this);

            PostDeviceCreated();
        }
Esempio n. 6
0
        /// <summary>
        /// Updates the subresource safe method.
        /// </summary>
        /// <param name="dstResourceRef">The DST resource ref.</param>
        /// <param name="dstSubresource">The DST subresource.</param>
        /// <param name="dstBoxRef">The DST box ref.</param>
        /// <param name="pSrcData">The p SRC data.</param>
        /// <param name="srcRowPitch">The SRC row pitch.</param>
        /// <param name="srcDepthPitch">The SRC depth pitch.</param>
        /// <param name="srcBytesPerElement">The size in bytes per pixel/block element.</param>
        /// <param name="isCompressedResource">if set to <c>true</c> the resource is a block/compressed resource</param>
        /// <returns></returns>
        /// <remarks>
        /// This method is implementing the <a href="http://blogs.msdn.com/b/chuckw/archive/2010/07/28/known-issue-direct3d-11-updatesubresource-and-deferred-contexts.aspx">workaround for deferred context</a>.
        /// </remarks>
        internal unsafe bool UpdateSubresourceSafe(SharpDX.Direct3D11.Resource dstResourceRef, int dstSubresource, SharpDX.Direct3D11.ResourceRegion?dstBoxRef, System.IntPtr pSrcData, int srcRowPitch, int srcDepthPitch, int srcBytesPerElement, bool isCompressedResource)
        {
            bool needWorkaround = false;

            // Check thread support just once as it won't change during the life of this instance.
            if (!isCheckThreadingSupport)
            {
                bool supportsConcurrentResources;
                Device.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                isCheckThreadingSupport = true;
            }

            if (dstBoxRef.HasValue)
            {
                if (TypeInfo == DeviceContextType.Deferred)
                {
                    // If this deferred context doesn't support command list, we need to perform the workaround
                    needWorkaround = !supportsCommandLists;
                }
            }

            // Adjust the pSrcData pointer if needed
            IntPtr pAdjustedSrcData = pSrcData;

            if (needWorkaround)
            {
                var alignedBox = dstBoxRef.Value;

                // convert from pixels to blocks
                if (isCompressedResource)
                {
                    alignedBox.Left   /= 4;
                    alignedBox.Right  /= 4;
                    alignedBox.Top    /= 4;
                    alignedBox.Bottom /= 4;
                }

                pAdjustedSrcData = (IntPtr)(((byte *)pSrcData) - (alignedBox.Front * srcDepthPitch) - (alignedBox.Top * srcRowPitch) - (alignedBox.Left * srcBytesPerElement));
            }

            UpdateSubresource(dstResourceRef, dstSubresource, dstBoxRef, pAdjustedSrcData, srcRowPitch, srcDepthPitch);

            return(needWorkaround);
        }
Esempio n. 7
0
        public D3D11GraphicsDevice(GraphicsDeviceOptions options, SwapchainDescription?swapchainDesc)
        {
#if DEBUG
            DeviceCreationFlags creationFlags = DeviceCreationFlags.Debug;
#else
            DeviceCreationFlags creationFlags = options.Debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None;
#endif
            _device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags);
            if (swapchainDesc != null)
            {
                SwapchainDescription desc = swapchainDesc.Value;
                _mainSwapchain = new D3D11Swapchain(_device, ref desc);
            }
            _immediateContext = _device.ImmediateContext;
            _device.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists);

            _d3d11ResourceFactory = new D3D11ResourceFactory(this);
            PostDeviceCreated();
        }
        unsafe static MyAdapterInfo[] CreateAdaptersList()
        {
            List <MyAdapterInfo> adaptersList = new List <MyAdapterInfo>();

            var factory = GetFactory();

            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI(Log);
            LogInfoFromWMI(MyLog.Default);

            for (int i = 0; i < factory.Adapters.Length; i++)
            {
                var    adapter           = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch (SharpDXException)
                {
                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists        = false;
                if (supportedDevice)

                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                // DedicatedSystemMemory = bios or DVMT preallocated video memory, that cannot be used by OS - need retest on pc with only cpu/chipset based graphic
                // DedicatedVideoMemory = discrete graphic video memory
                // SharedSystemMemory = aditional video memory, that can be taken from OS RAM when needed
                void * vramptr  = ((IntPtr)(adapter.Description.DedicatedSystemMemory != 0 ? adapter.Description.DedicatedSystemMemory : adapter.Description.DedicatedVideoMemory)).ToPointer();
                UInt64 vram     = (UInt64)vramptr;
                void * svramptr = ((IntPtr)adapter.Description.SharedSystemMemory).ToPointer();
                UInt64 svram    = (UInt64)svramptr;

                // microsoft software renderer allocates 256MB shared memory, cpu integrated graphic on notebooks has 0 preallocated, all shared
                supportedDevice = supportedDevice && (vram > 500000000 || svram > 500000000);

                var deviceDesc = String.Format("{0}, dev id: {1}, mem: {2}, shared mem: {3}, Luid: {4}, rev: {5}, subsys id: {6}, vendor id: {7}",
                                               adapter.Description.Description,
                                               adapter.Description.DeviceId,
                                               vram,
                                               svram,
                                               adapter.Description.Luid,
                                               adapter.Description.Revision,
                                               adapter.Description.SubsystemId,
                                               adapter.Description.VendorId
                                               );

                var info = new MyAdapterInfo
                {
                    Name            = adapter.Description.Description,
                    DeviceName      = adapter.Description.Description,
                    VendorId        = adapter.Description.VendorId,
                    DeviceId        = adapter.Description.DeviceId,
                    Description     = deviceDesc,
                    IsDx11Supported = supportedDevice,
                    AdapterDeviceId = i,
                    Priority        = VendorPriority(adapter.Description.VendorId),
                    HDRSupported    = true,
                    MaxTextureSize  = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,
                    VRAM            = vram > 0 ? vram : svram,
                    Has512MBRam     = (vram > 500000000 || svram > 500000000),
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                if (info.VRAM >= 2000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.HIGH;
                }
                else if (info.VRAM >= 1000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.MEDIUM;
                }
                else
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.LOW;
                }

                info.MaxAntialiasingModeSupported = MyAntialiasingMode.FXAA;
                if (supportedDevice)
                {
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 2) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_2;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 4) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_4;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 8) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_8;
                    }
                }

                LogAdapterInfoBegin(ref info);

                if (supportedDevice)
                {
                    bool outputsAttached = adapter.Outputs.Length > 0;

                    if (outputsAttached)
                    {
                        for (int j = 0; j < adapter.Outputs.Length; j++)
                        {
                            var output = adapter.Outputs[j];

                            info.Name       = String.Format("{0} + {1}", adapter.Description.Description, output.Description.DeviceName);
                            info.OutputName = output.Description.DeviceName;
                            info.OutputId   = j;

                            var displayModeList     = output.GetDisplayModeList(MyRender11Constants.DX11_BACKBUFFER_FORMAT, DisplayModeEnumerationFlags.Interlaced);
                            var adapterDisplayModes = new MyDisplayMode[displayModeList.Length];
                            for (int k = 0; k < displayModeList.Length; k++)
                            {
                                var displayMode = displayModeList[k];

                                adapterDisplayModes[k] = new MyDisplayMode
                                {
                                    Height                 = displayMode.Height,
                                    Width                  = displayMode.Width,
                                    RefreshRate            = displayMode.RefreshRate.Numerator,
                                    RefreshRateDenominator = displayMode.RefreshRate.Denominator
                                };
                            }
                            Array.Sort(adapterDisplayModes, m_refreshRatePriorityComparer);

                            info.SupportedDisplayModes = adapterDisplayModes;
                            info.CurrentDisplayMode    = adapterDisplayModes[adapterDisplayModes.Length - 1];
                            LogOutputDisplayModes(ref info);

                            m_adapterModes[adapterIndex] = displayModeList;

                            // add one entry per every adapter-output pair
                            adaptersList.Add(info);
                            adapterIndex++;
                        }
                    }
                    else
                    {
                        // FALLBACK MODES

                        MyDisplayMode[] fallbackDisplayModes = new MyDisplayMode[] {
                            new MyDisplayMode(640, 480, 60000, 1000),
                            new MyDisplayMode(720, 576, 60000, 1000),
                            new MyDisplayMode(800, 600, 60000, 1000),
                            new MyDisplayMode(1024, 768, 60000, 1000),
                            new MyDisplayMode(1152, 864, 60000, 1000),
                            new MyDisplayMode(1280, 720, 60000, 1000),
                            new MyDisplayMode(1280, 768, 60000, 1000),
                            new MyDisplayMode(1280, 800, 60000, 1000),
                            new MyDisplayMode(1280, 960, 60000, 1000),
                            new MyDisplayMode(1280, 1024, 60000, 1000),
                            new MyDisplayMode(1360, 768, 60000, 1000),
                            new MyDisplayMode(1360, 1024, 60000, 1000),
                            new MyDisplayMode(1440, 900, 60000, 1000),
                            new MyDisplayMode(1600, 900, 60000, 1000),
                            new MyDisplayMode(1600, 1024, 60000, 1000),
                            new MyDisplayMode(1600, 1200, 60000, 1000),
                            new MyDisplayMode(1680, 1200, 60000, 1000),
                            new MyDisplayMode(1680, 1050, 60000, 1000),
                            new MyDisplayMode(1920, 1080, 60000, 1000),
                            new MyDisplayMode(1920, 1200, 60000, 1000),
                        };

                        info.OutputName = "FallbackOutput";

                        info.Name               = String.Format("{0}", adapter.Description.Description);
                        info.OutputId           = 0;
                        info.CurrentDisplayMode = fallbackDisplayModes[fallbackDisplayModes.Length - 1];

                        info.SupportedDisplayModes = fallbackDisplayModes;
                        info.FallbackDisplayModes  = true;

                        // add one entry for adapter-fallback output pair
                        adaptersList.Add(info);
                        adapterIndex++;
                    }
                }
                else
                {
                    info.SupportedDisplayModes = new MyDisplayMode[0];
                }

                Log.WriteLine("Fallback display modes = " + info.FallbackDisplayModes);

                LogAdapterInfoEnd();

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

            return(adaptersList.ToArray());
        }
        unsafe static MyAdapterInfo[] GetAdapters()
        {
            List <MyAdapterInfo> adaptersList = new List <MyAdapterInfo>();

            var factory = GetFactory();

            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI(Log);
            LogInfoFromWMI(MyLog.Default);

            for (int i = 0; i < factory.Adapters.Length; i++)
            {
                var    adapter           = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch (SharpDXException)
                {
                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists        = false;
                if (supportedDevice)
                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                // DedicatedSystemMemory = bios or DVMT preallocated video memory, that cannot be used by OS - need retest on pc with only cpu/chipset based graphic
                // DedicatedVideoMemory = discrete graphic video memory
                // SharedSystemMemory = aditional video memory, that can be taken from OS RAM when needed
                void *vramptr =
                    ((IntPtr)
                     (adapter.Description.DedicatedSystemMemory != 0
                            ? adapter.Description.DedicatedSystemMemory
                            : adapter.Description.DedicatedVideoMemory)).ToPointer();
                UInt64 vram     = (UInt64)vramptr;
                void * svramptr = ((IntPtr)adapter.Description.SharedSystemMemory).ToPointer();
                UInt64 svram    = (UInt64)svramptr;

                // microsoft software renderer allocates 256MB shared memory, cpu integrated graphic on notebooks has 0 preallocated, all shared
                supportedDevice = supportedDevice && (vram > 500000000 || svram > 500000000);

                var deviceDesc =
                    String.Format(
                        "{0}, dev id: {1}, mem: {2}, shared mem: {3}, Luid: {4}, rev: {5}, subsys id: {6}, vendor id: {7}",
                        adapter.Description.Description,
                        adapter.Description.DeviceId,
                        vram,
                        svram,
                        adapter.Description.Luid,
                        adapter.Description.Revision,
                        adapter.Description.SubsystemId,
                        adapter.Description.VendorId
                        );

                var info = new MyAdapterInfo
                {
                    Name            = adapter.Description.Description,
                    DeviceName      = adapter.Description.Description,
                    VendorId        = adapter.Description.VendorId,
                    DeviceId        = adapter.Description.DeviceId,
                    Description     = deviceDesc,
                    IsDx11Supported = supportedDevice,
                    AdapterDeviceId = i,
                    Priority        = VendorPriority(adapter.Description.VendorId),
                    HDRSupported    = true,
                    MaxTextureSize  = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,
                    VRAM            = vram > 0 ? vram : svram,
                    Has512MBRam     = (vram > 500000000 || svram > 500000000),
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                adaptersList.Add(info);
                adapterIndex++;
            }

            return(adaptersList.ToArray());
        }
Esempio n. 10
0
        unsafe static MyAdapterInfo[] CreateAdaptersList()
        {
            List <MyAdapterInfo> adaptersList = new List <MyAdapterInfo>();

            var factory = GetFactory();

            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI();

            for (int i = 0; i < factory.Adapters.Length; i++)
            {
                var    adapter           = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch (SharpDXException e)
                {
                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists        = false;
                if (supportedDevice)
                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                void *ptr  = ((IntPtr)adapter.Description.DedicatedVideoMemory).ToPointer();
                ulong vram = (ulong)ptr;

                var deviceDesc = String.Format("{0}, dev id: {1}, shared mem: {2}, Luid: {3}, rev: {4}, subsys id: {5}, vendor id: {6}",
                                               adapter.Description.Description,
                                               adapter.Description.DeviceId,
                                               vram,
                                               adapter.Description.Luid,
                                               adapter.Description.Revision,
                                               adapter.Description.SubsystemId,
                                               adapter.Description.VendorId
                                               );

                var info = new MyAdapterInfo
                {
                    Name            = adapter.Description.Description,
                    DeviceName      = adapter.Description.Description,
                    Description     = deviceDesc,
                    IsSupported     = supportedDevice,
                    AdapterDeviceId = i,

                    Has512MBRam    = vram > 500000000,
                    HDRSupported   = true,
                    MaxTextureSize = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,

                    VRAM = vram,
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                if (vram >= 2000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.HIGH;
                }
                else if (vram >= 1000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.MEDIUM;
                }
                else
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.LOW;
                }

                info.MaxAntialiasingModeSupported = MyAntialiasingMode.FXAA;
                if (supportedDevice)
                {
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 2) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_2;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 4) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_4;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 8) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_8;
                    }
                }

                LogAdapterInfoBegin(ref info);

                if (supportedDevice)
                {
                    for (int j = 0; j < factory.Adapters[i].Outputs.Length; j++)
                    {
                        var output = factory.Adapters[i].Outputs[j];

                        info.Name       = String.Format("{0} + {1}", adapter.Description.Description, output.Description.DeviceName);
                        info.OutputName = output.Description.DeviceName;
                        info.OutputId   = j;

                        var displayModeList     = factory.Adapters[i].Outputs[j].GetDisplayModeList(MyRender11Constants.BACKBUFFER_FORMAT, DisplayModeEnumerationFlags.Interlaced);
                        var adapterDisplayModes = new MyDisplayMode[displayModeList.Length];
                        for (int k = 0; k < displayModeList.Length; k++)
                        {
                            var displayMode = displayModeList[k];

                            adapterDisplayModes[k] = new MyDisplayMode
                            {
                                Height                 = displayMode.Height,
                                Width                  = displayMode.Width,
                                RefreshRate            = displayMode.RefreshRate.Numerator,
                                RefreshRateDenominator = displayMode.RefreshRate.Denominator
                            };
                        }
                        Array.Sort(adapterDisplayModes, m_refreshRatePriorityComparer);

                        info.SupportedDisplayModes = adapterDisplayModes;
                        info.CurrentDisplayMode    = adapterDisplayModes[adapterDisplayModes.Length - 1];


                        adaptersList.Add(info);
                        m_adapterModes[adapterIndex] = displayModeList;
                        adapterIndex++;

                        LogOutputDisplayModes(ref info);
                    }
                }
                else
                {
                    info.SupportedDisplayModes = new MyDisplayMode[0];
                    adaptersList.Add(info);
                    adapterIndex++;
                }

                LogAdapterInfoEnd();

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

            return(adaptersList.ToArray());
        }
Esempio n. 11
0
        unsafe static MyAdapterInfo[] CreateAdaptersList()
        {
            List<MyAdapterInfo> adaptersList = new List<MyAdapterInfo>();

            var factory = GetFactory();
            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI();

            for(int i=0; i<factory.Adapters.Length; i++)
            {
                var adapter = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch(SharpDXException e)
                {

                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists = false;
                if (supportedDevice)
                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                // DedicatedSystemMemory = bios or DVMT preallocated video memory, that cannot be used by OS - need retest on pc with only cpu/chipset based graphic
                // DedicatedVideoMemory = discrete graphic video memory
                // SharedSystemMemory = aditional video memory, that can be taken from OS RAM when needed
                void * vramptr = ((IntPtr)(adapter.Description.DedicatedSystemMemory != 0 ? adapter.Description.DedicatedSystemMemory : adapter.Description.DedicatedVideoMemory)).ToPointer();
                UInt64 vram = (UInt64)vramptr;
                void * svramptr = ((IntPtr)adapter.Description.SharedSystemMemory).ToPointer();
                UInt64 svram = (UInt64)svramptr;

                // microsoft software renderer allocates 256MB shared memory, cpu integrated graphic on notebooks has 0 preallocated, all shared
                supportedDevice = supportedDevice && (vram > 500000000 || svram > 500000000);

                var deviceDesc = String.Format("{0}, dev id: {1}, mem: {2}, shared mem: {3}, Luid: {4}, rev: {5}, subsys id: {6}, vendor id: {7}",
                    adapter.Description.Description,
                    adapter.Description.DeviceId,
                    vram,
                    svram,
                    adapter.Description.Luid,
                    adapter.Description.Revision,
                    adapter.Description.SubsystemId,
                    adapter.Description.VendorId
                    );

                var info = new MyAdapterInfo
                {
                    Name = adapter.Description.Description,
                    DeviceName = adapter.Description.Description,
                    Description = deviceDesc,
                    IsDx11Supported = supportedDevice,
                    AdapterDeviceId = i,
                    Priority = VendorPriority(adapter.Description.VendorId),
                    HDRSupported = true,
                    MaxTextureSize = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,
                    VRAM = vram > 0 ? vram : svram,
                    Has512MBRam = (vram > 500000000 || svram > 500000000),
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                if(info.VRAM >= 2000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.HIGH;
                }
                else if (info.VRAM >= 1000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.MEDIUM;
                }
                else
                { 
                    info.MaxTextureQualitySupported = MyTextureQuality.LOW;
                }

                info.MaxAntialiasingModeSupported = MyAntialiasingMode.FXAA;
                if (supportedDevice)
                {
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 2) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_2;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 4) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_4;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 8) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_8;
                    }
                }

                LogAdapterInfoBegin(ref info);

                if(supportedDevice)
                {
                    bool outputsAttached = adapter.Outputs.Length > 0;

                    if (outputsAttached)
                    {
                        for (int j = 0; j < adapter.Outputs.Length; j++)
                        {
                            var output = adapter.Outputs[j];

                            info.Name = String.Format("{0} + {1}", adapter.Description.Description, output.Description.DeviceName);
                            info.OutputName = output.Description.DeviceName;
                            info.OutputId = j;

                            var displayModeList = output.GetDisplayModeList(MyRender11Constants.BACKBUFFER_FORMAT, DisplayModeEnumerationFlags.Interlaced);
                            var adapterDisplayModes = new MyDisplayMode[displayModeList.Length];
                            for (int k = 0; k < displayModeList.Length; k++)
                            {
                                var displayMode = displayModeList[k];

                                adapterDisplayModes[k] = new MyDisplayMode
                                {
                                    Height = displayMode.Height,
                                    Width = displayMode.Width,
                                    RefreshRate = displayMode.RefreshRate.Numerator,
                                    RefreshRateDenominator = displayMode.RefreshRate.Denominator
                                };
                            }
                            Array.Sort(adapterDisplayModes, m_refreshRatePriorityComparer);

                            info.SupportedDisplayModes = adapterDisplayModes;
                            info.CurrentDisplayMode = adapterDisplayModes[adapterDisplayModes.Length - 1];
                            LogOutputDisplayModes(ref info);

                            m_adapterModes[adapterIndex] = displayModeList;

                            // add one entry per every adapter-output pair
                            adaptersList.Add(info);
                            adapterIndex++;
                        }
                    }
                    else
                    {
                        // FALLBACK MODES

                        MyDisplayMode[] fallbackDisplayModes = new MyDisplayMode[] {
                            new MyDisplayMode(640, 480, 60000, 1000),
                            new MyDisplayMode(720, 576, 60000, 1000),
                            new MyDisplayMode(800, 600, 60000, 1000),
                            new MyDisplayMode(1024, 768, 60000, 1000),
                            new MyDisplayMode(1152, 864, 60000, 1000),
                            new MyDisplayMode(1280, 720, 60000, 1000),
                            new MyDisplayMode(1280, 768, 60000, 1000),
                            new MyDisplayMode(1280, 800, 60000, 1000),
                            new MyDisplayMode(1280, 960, 60000, 1000),
                            new MyDisplayMode(1280, 1024, 60000, 1000),
                            new MyDisplayMode(1360, 768, 60000, 1000),
                            new MyDisplayMode(1360, 1024, 60000, 1000),
                            new MyDisplayMode(1440, 900, 60000, 1000),
                            new MyDisplayMode(1600, 900, 60000, 1000),
                            new MyDisplayMode(1600, 1024, 60000, 1000),
                            new MyDisplayMode(1600, 1200, 60000, 1000),
                            new MyDisplayMode(1680, 1200, 60000, 1000),
                            new MyDisplayMode(1680, 1050, 60000, 1000),
                            new MyDisplayMode(1920, 1080, 60000, 1000),
                            new MyDisplayMode(1920, 1200, 60000, 1000),
                        };

                        info.OutputName = "FallbackOutput";
                        info.Name = String.Format("{0}", adapter.Description.Description);
                        info.OutputId = 0;
                        info.CurrentDisplayMode = fallbackDisplayModes[fallbackDisplayModes.Length - 1];

                        info.SupportedDisplayModes = fallbackDisplayModes;
                        info.FallbackDisplayModes = true;

                        // add one entry for adapter-fallback output pair
                        adaptersList.Add(info);
                        adapterIndex++;
                    }
                }
                else
                {
                    info.SupportedDisplayModes = new MyDisplayMode[0];
                }

                MyRender11.Log.WriteLine("Fallback display modes = " + info.FallbackDisplayModes);

                LogAdapterInfoEnd();

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

            return adaptersList.ToArray();
        }
        unsafe static MyAdapterInfo[] CreateAdaptersList()
        {
            List<MyAdapterInfo> adaptersList = new List<MyAdapterInfo>();

            var factory = GetFactory();
            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI();

            for(int i=0; i<factory.Adapters.Length; i++)
            {
                var adapter = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch(SharpDXException e)
                {

                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists = false;
                if (supportedDevice)
                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                void* ptr = ((IntPtr)adapter.Description.DedicatedVideoMemory).ToPointer();
                ulong vram = (ulong)ptr;

                var deviceDesc = String.Format("{0}, dev id: {1}, shared mem: {2}, Luid: {3}, rev: {4}, subsys id: {5}, vendor id: {6}",
                    adapter.Description.Description,
                    adapter.Description.DeviceId,
                    vram,
                    adapter.Description.Luid,
                    adapter.Description.Revision,
                    adapter.Description.SubsystemId,
                    adapter.Description.VendorId
                    );

                var info = new MyAdapterInfo
                {
                    Name = adapter.Description.Description,
                    DeviceName = adapter.Description.Description,
                    Description = deviceDesc,
                    IsSupported = supportedDevice,
                    AdapterDeviceId = i,

                    Has512MBRam = vram > 500000000,
                    HDRSupported = true,
                    MaxTextureSize = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,

                    VRAM = vram,
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                if(vram >= 2000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.HIGH;
                }
                else if (vram >= 1000000000)
                {
                    info.MaxTextureQualitySupported = MyTextureQuality.MEDIUM;
                }
                else
                { 
                    info.MaxTextureQualitySupported = MyTextureQuality.LOW;
                }

                info.MaxAntialiasingModeSupported = MyAntialiasingMode.FXAA;
                if (supportedDevice)
                {
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 2) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_2;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 4) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_4;
                    }
                    if (adapterTestDevice.CheckMultisampleQualityLevels(Format.R11G11B10_Float, 8) > 0)
                    {
                        info.MaxAntialiasingModeSupported = MyAntialiasingMode.MSAA_8;
                    }
                }

                LogAdapterInfoBegin(ref info);

                if(supportedDevice)
                {
                    for(int j=0; j<factory.Adapters[i].Outputs.Length; j++)
                    {
                        var output = factory.Adapters[i].Outputs[j];

                        info.Name = String.Format("{0} + {1}", adapter.Description.Description, output.Description.DeviceName);
                        info.OutputName = output.Description.DeviceName;
                        info.OutputId = j;

                        var displayModeList = factory.Adapters[i].Outputs[j].GetDisplayModeList(MyRender11Constants.BACKBUFFER_FORMAT, DisplayModeEnumerationFlags.Interlaced);
                        var adapterDisplayModes = new MyDisplayMode[displayModeList.Length];
                        for (int k = 0; k < displayModeList.Length; k++)
                        {
                            var displayMode = displayModeList[k];

                            adapterDisplayModes[k] = new MyDisplayMode 
                            { 
                                Height = displayMode.Height, 
                                Width = displayMode.Width, 
                                RefreshRate = displayMode.RefreshRate.Numerator, 
                                RefreshRateDenominator = displayMode.RefreshRate.Denominator 
                            }; 
                        }
                        Array.Sort(adapterDisplayModes, m_refreshRatePriorityComparer);

                        info.SupportedDisplayModes = adapterDisplayModes;
                        info.CurrentDisplayMode = adapterDisplayModes[adapterDisplayModes.Length - 1];


                        adaptersList.Add(info);
                        m_adapterModes[adapterIndex] = displayModeList;
                        adapterIndex++;

                        LogOutputDisplayModes(ref info);
                    }
                }
                else
                {
                    info.SupportedDisplayModes = new MyDisplayMode[0];
                    adaptersList.Add(info);
                    adapterIndex++;
                }

                LogAdapterInfoEnd();

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

            return adaptersList.ToArray();
        }
        unsafe static MyAdapterInfo[] GetAdapters()
        {
            List<MyAdapterInfo> adaptersList = new List<MyAdapterInfo>();

            var factory = GetFactory();
            FeatureLevel[] featureLevels = { FeatureLevel.Level_11_0 };

            int adapterIndex = 0;

            LogInfoFromWMI(Log);
            LogInfoFromWMI(MyLog.Default);

            for (int i = 0; i < factory.Adapters.Length; i++)
            {
                var adapter = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch (SharpDXException)
                {

                }

                bool supportedDevice = adapterTestDevice != null;

                bool supportsConcurrentResources = false;
                bool supportsCommandLists = false;
                if (supportedDevice)
                {
                    adapterTestDevice.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                }

                // DedicatedSystemMemory = bios or DVMT preallocated video memory, that cannot be used by OS - need retest on pc with only cpu/chipset based graphic
                // DedicatedVideoMemory = discrete graphic video memory
                // SharedSystemMemory = aditional video memory, that can be taken from OS RAM when needed
                void* vramptr =
                    ((IntPtr)
                        (adapter.Description.DedicatedSystemMemory != 0
                            ? adapter.Description.DedicatedSystemMemory
                            : adapter.Description.DedicatedVideoMemory)).ToPointer();
                UInt64 vram = (UInt64) vramptr;
                void* svramptr = ((IntPtr) adapter.Description.SharedSystemMemory).ToPointer();
                UInt64 svram = (UInt64) svramptr;

                // microsoft software renderer allocates 256MB shared memory, cpu integrated graphic on notebooks has 0 preallocated, all shared
                supportedDevice = supportedDevice && (vram > 500000000 || svram > 500000000);

                var deviceDesc =
                    String.Format(
                        "{0}, dev id: {1}, mem: {2}, shared mem: {3}, Luid: {4}, rev: {5}, subsys id: {6}, vendor id: {7}",
                        adapter.Description.Description,
                        adapter.Description.DeviceId,
                        vram,
                        svram,
                        adapter.Description.Luid,
                        adapter.Description.Revision,
                        adapter.Description.SubsystemId,
                        adapter.Description.VendorId
                        );

                var info = new MyAdapterInfo
                {
                    Name = adapter.Description.Description,
                    DeviceName = adapter.Description.Description,
                    VendorId = adapter.Description.VendorId,
                    DeviceId = adapter.Description.DeviceId,
                    Description = deviceDesc,
                    IsDx11Supported = supportedDevice,
                    AdapterDeviceId = i,
                    Priority = VendorPriority(adapter.Description.VendorId),
                    HDRSupported = true,
                    MaxTextureSize = SharpDX.Direct3D11.Texture2D.MaximumTexture2DSize,
                    VRAM = vram > 0 ? vram : svram,
                    Has512MBRam = (vram > 500000000 || svram > 500000000),
                    MultithreadedRenderingSupported = supportsCommandLists
                };

                adaptersList.Add(info);
                adapterIndex++;
            }

            return adaptersList.ToArray();
        }
Esempio n. 14
0
        public static void SetupDisplay(Control control)
        {
            Display.Width  = control.ClientSize.Width;
            Display.Height = control.ClientSize.Height;

            var description = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = control.Handle,
                IsWindowed        = !Display.Fullscreen,
                ModeDescription   = new ModeDescription(0, 0, new Rational(), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(Antialias, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            var factory = new Factory();

            Logger.Log("D3D11 Factory initialized.");

            int adapterCount = factory.GetAdapterCount();

            Logger.Log("D3D11 Amount of adapters: " + adapterCount);

            if (adapterCount == 0)
            {
                Logger.Log("ERROR : No adapters found !");
                throw new Exception("ERROR : No adapters found !");
            }

            bool    perfHUDenabled = false;
            Adapter adapter        = null;

            for (int i = 0; i < adapterCount; i++)
            {
                Adapter ad = factory.GetAdapter(i);
                Logger.Log("D3D11 Adapter " + i + " : (" + ad.Description.DeviceId + ") " + ad.Description.Description);
                if (ad.Description.Description == "NVIDIA PerfHUD")
                {
                    perfHUDenabled = true;
                    adapter        = ad;
                }
            }
            if (adapter == null)
            {
                adapter = factory.GetAdapter(0);
            }

            Logger.Log("D3D11 Adapter chosen : " + adapter.Description.Description);

            if (perfHUDenabled)
            {
                Device.CreateWithSwapChain(adapter, DeviceCreationFlags.None, description, out device, out swapChain);
            }
            else
            {
                try {
#if DEBUG
                    try {
                        device = new Device(adapter, DeviceCreationFlags.Debug);
                    } catch (Exception e) {
                        Logger.Log("! Warning : D3D11 Could not init DEBUG Device. (" + e.Message + ")");
                        device = new Device(adapter, DeviceCreationFlags.None);
                    }
#else
                    device = new Device(adapter, DeviceCreationFlags.None);
#endif
                } catch (Exception e) {
                    Logger.Log("! ERROR : D3D11 Could not init the Device at all ! (" + e.Message + ")");
                    device = new Device(adapter, DeviceCreationFlags.None);
                }
            }
            Logger.Log("D3D11 Device initialized.");

            bool supConcurrentRess, supCommandList;
            device.CheckThreadingSupport(out supConcurrentRess, out supCommandList);
            Logger.Log("D3D11 Concurrent ressource load supported : " + supConcurrentRess);
            Logger.Log("D3D11 Command lists supported : " + supCommandList);

            // Main textures
            Logger.Log("D3D11 Format R8G8B8A8_UNorm supported : " + device.CheckFormatSupport(Format.R8G8B8A8_UNorm).HasFlag(FormatSupport.RenderTarget));
            Logger.Log("D3D11 Format D24_UNorm_S8_UInt supported : " + device.CheckFormatSupport(Format.D24_UNorm_S8_UInt).HasFlag(FormatSupport.DepthStencil));
            Logger.Log("D3D11 Format D32_Float supported : " + device.CheckFormatSupport(Format.D32_Float).HasFlag(FormatSupport.DepthStencil));

            //Shadow textures
            Logger.Log("D3D11 Format R16_Typeless supported : " + device.CheckFormatSupport(Format.R16_Typeless).HasFlag(FormatSupport.Texture2D));
            Logger.Log("D3D11 Format D16_UNorm supported : " + device.CheckFormatSupport(Format.D16_UNorm).HasFlag(FormatSupport.Texture2D));
            Logger.Log("D3D11 Format R16_UNorm supported : " + device.CheckFormatSupport(Format.R16_UNorm).HasFlag(FormatSupport.Texture2D));

            swapChain = new SwapChain(factory, device, description);
            factory.MakeWindowAssociation(Main.Form.Handle, WindowAssociationFlags.IgnoreAll);

            //device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 1);
            //swapChain.
            Logger.Log("D3D11 SwapChain initialized.");

            Display.context = device.ImmediateContext;

            //Display.width = Main.Form.ClientSize.Width;
            //Display.height = Main.Form.ClientSize.Height;
            //Global.Viewport = new Rectangle(0, 0, (int)Display.width, (int)Display.height);


            Result res = Display.device.DeviceRemovedReason;
            if (res.Failure)
            {
                Logger.Log("! ERROR : a weird one : " + res.Code);
                throw new Exception("ERROR, this is weird, here's the reason why : " + res.ToString());
            }

            if (device.IsDisposed)
            {
                Logger.Log("! ERROR : a REALLY weird one.");
                throw new Exception("DISPOSED ERROR, this is F*****G weird ... ");
            }

            backBuffer   = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderTarget = new RenderTargetView(device, backBuffer);

            Logger.Log("D3D11 Backbuffer initialized.");

            backBufferCopyDesc = new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                Width             = Display.Width,
                Height            = Display.Height,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
            };

            backBufferCopy    = new Texture2D(Display.device, backBufferCopyDesc);
            backBufferCopySRV = new ShaderResourceView(Display.device, backBufferCopy);

            Logger.Log("D3D11 Backbuffer copy initialized.");

            depthBufferDesc = new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.D24_UNorm_S8_UInt,
                Width             = Display.Width,
                Height            = Display.Height,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = description.SampleDescription,
                Usage             = ResourceUsage.Default,
            };

            using (var depthBuffer = new Texture2D(device, depthBufferDesc))
                depthStencil = new DepthStencilView(device, depthBuffer);

            Logger.Log("D3D11 Depthbuffer initialized.");

            DeviceStates.Initialize();

            Logger.Log("D3D11 Device states initialized.");

            context.OutputMerger.DepthStencilState = DeviceStates.depthDefaultState;
            context.Rasterizer.State        = DeviceStates.rastStateSolid;
            context.OutputMerger.BlendState = DeviceStates.blendStateSolid;

            context.OutputMerger.SetTargets(depthStencil, renderTarget);

            context.Rasterizer.SetViewports(new Viewport(0, 0, Display.Width, Display.Height, 0.0f, 1.0f));

            Logger.Log("D3D11 engine states set.");

            screenMatrix = Matrix.Scaling(2f / Display.Width, -2f / Display.Height, 0) * Matrix.Translation(-1, 1, 0);
            screenMatrix.Transpose();
            screenBuffer = new Buffer(device, DataStream.Create <Matrix>(new[] { screenMatrix }, false, false), 64, ResourceUsage.Immutable, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Logger.Log("D3D11 screen buffer created.");
        }
Esempio n. 15
0
        public D3D11GraphicsDevice(D3D11DeviceOptions options, SwapchainDescription?swapchainDesc)
        {
            var flags = (DeviceCreationFlags)options.DeviceCreationFlags;

#if DEBUG
            flags |= DeviceCreationFlags.Debug;
#endif
            // If debug flag set but SDK layers aren't available we can't enable debug.
            if (0 != (flags & DeviceCreationFlags.Debug) && !SdkLayersAvailable)
            {
                flags &= ~DeviceCreationFlags.Debug;
            }

            try
            {
                if (options.AdapterPtr != IntPtr.Zero)
                {
                    _dxgiAdapter = new Adapter(options.AdapterPtr);
                    _device      = new SharpDX.Direct3D11.Device(_dxgiAdapter,
                                                                 flags,
                                                                 SharpDX.Direct3D.FeatureLevel.Level_11_1);
                }
                else
                {
                    _device = new SharpDX.Direct3D11.Device(
                        SharpDX.Direct3D.DriverType.Hardware,
                        flags,
                        SharpDX.Direct3D.FeatureLevel.Level_11_1);
                }
            }
            catch (SharpDXException)
            {
                _device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, flags);
            }

            using (var dxgiDevice = _device.QueryInterface <SharpDX.DXGI.Device>())
            {
                // Store a pointer to the DXGI adapter.
                // This is for the case of no preferred DXGI adapter, or fallback to WARP.
                _dxgiAdapter = dxgiDevice.Adapter;
            }

            if (swapchainDesc != null)
            {
                SwapchainDescription desc = swapchainDesc.Value;
                _mainSwapchain = new D3D11Swapchain(_device, ref desc);
            }
            _immediateContext = _device.ImmediateContext;
            _device.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists);

            Features = new GraphicsDeviceFeatures(
                computeShader: true,
                geometryShader: true,
                tessellationShaders: true,
                multipleViewports: true,
                samplerLodBias: true,
                drawBaseVertex: true,
                drawBaseInstance: true,
                drawIndirect: true,
                drawIndirectBaseInstance: true,
                fillModeWireframe: true,
                samplerAnisotropy: true,
                depthClipDisable: true,
                texture1D: true,
                independentBlend: true,
                structuredBuffer: true,
                subsetTextureView: true,
                commandListDebugMarkers: _device.FeatureLevel >= SharpDX.Direct3D.FeatureLevel.Level_11_1,
                bufferRangeBinding: _device.FeatureLevel >= SharpDX.Direct3D.FeatureLevel.Level_11_1);

            _d3d11ResourceFactory = new D3D11ResourceFactory(this);
            _d3d11Info            = new BackendInfoD3D11(this);

            PostDeviceCreated();
        }
Esempio n. 16
0
 public void IsMultithreadingSupported(out bool supportsConcurrentResources, out bool supportsCommandLists)
 {
     _device.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
     logger.Info($"ConcurrentResources:{supportsConcurrentResources} CommandLists:{supportsCommandLists}");
 }
Esempio n. 17
0
        public virtual void Run()
        {
            // Create Form
            Form = new RenderForm(this.ToString());
            Form.AllowUserResizing = false;
            Form.ClientSize        = new Size(1280, 780);

            // Swap Chain Desc
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount     = 2,
                ModeDescription =
                    new ModeDescription(Form.ClientSize.Width, Form.ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = Form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

            // Swap with properties
            this.Device    = device;
            this.SwapChain = swapChain;

            // Check if driver is supporting natively CommandList
            bool supportConcurentResources, supportCommandList;

            Device.CheckThreadingSupport(out supportConcurentResources, out supportCommandList);

            // Ignore all windows events
            var factory = SwapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(Form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

            this.RenderTargetView = new RenderTargetView(Device, backBuffer);

            this.LoadContent();

            // Create Depth Buffer & View
            var depthBuffer = new Texture2D(Device, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = Form.ClientSize.Width,
                Height            = Form.ClientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            this.DepthStencilView = new DepthStencilView(Device, depthBuffer);

            this.OnInitialize();

            this.clock = new Stopwatch();
            this.clock.Start();

            RenderLoop.Run(Form, () =>
            {
                this.Update(this.clock.ElapsedMilliseconds / 1000.0f);
                this.OnDraw(this.clock.ElapsedMilliseconds / 1000.0f);
                swapChain.Present(0, PresentFlags.None);
            });
        }