internal EffectConstantBuffer(string name, int size, EffectParameterDescription[] paramDescription)
            : base(size)
        {
            _device = GraphicManager.Device;

            Name = name;
            Size = size;
            _hashCode = GetHashCode(name, size, paramDescription);

            if (paramDescription != null)
            {
                Parameters = new Dictionary<string, EffectParameter>(paramDescription.Length);

                for (int i = 0; i < paramDescription.Length; i++)
                {
                    EffectParameter parameter = new EffectParameter(paramDescription[i], this);
                    Parameters.Add(parameter.Name, parameter);
                }
            }

            Clear();

            _nativeBuffer = Buffer.NewConstantBuffer(size);

            IsDirty = true;

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

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

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

            bmpData = null;
            GC.SuppressFinalize(this);
        }
        public void Draw(Device device)
        {
            uint fullMask = 0;
            foreach (var attr in BasePart.Attributes)
                fullMask |= attr.AttributeMask;

            //var fromMask = (this.Mesh.Variant.ImcVariant.PartVisibilityMask & BasePart.Header.VisibilityMask) == BasePart.Header.VisibilityMask;
            var fromMask = (this.Mesh.Variant.ImcVariant.PartVisibilityMask & fullMask) == fullMask;
            if (VisibilityOverride.GetValueOrDefault(fromMask))
                device.ImmediateContext.DrawIndexed(BasePart.IndexCount, BasePart.IndexOffset - Mesh.Primitive.BaseMesh.Header.IndexBufferOffset, 0);
        }
 /// <summary>
 /// Check for SDK Layer support.
 /// </summary>
 internal static bool SdkLayersAvailable()
 {
     try
     {
         using (var device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Null, SharpDX.Direct3D11.DeviceCreationFlags.Debug))
         {
             return(true);
         }
     }
     catch
     {
         return(false);
     }
 }
Exemple #5
0
        public CaptureFrameWait(IDirect3DDevice device, Func <GraphicsCaptureItem> itemFactory)
        {
            this.device      = device;
            this.d3dDevice   = Direct3D11Helper.CreateSharpDXDevice(device);
            this.multithread = d3dDevice.QueryInterface <SharpDX.Direct3D11.Multithread>();
            this.multithread.SetMultithreadProtected(true);
            this.frameEvent  = new ManualResetEvent(false);
            this.closedEvent = new ManualResetEvent(false);
            this.events      = new[] { closedEvent, frameEvent };
            this.itemFactory = itemFactory;
            this.CurrentItem = this.itemFactory();

            InitializeBlankTexture(this.CurrentItem.Size);
            InitializeCapture();
        }
        private bool LoadTexture(SharpDX.Direct3D11.Device device, string textureFileName)
        {
            textureFileName = DSystemConfiguration.DataFilePath + textureFileName;

            // Create the texture object.
            Texture = new DTexture();

            // Initialize the texture object.
            if (!Texture.Initialize(device, textureFileName))
            {
                return(false);
            }

            return(true);
        }
Exemple #7
0
        public VertexBuffer GetNewBuffer(SharpDX.Direct3D11.Device dev, int L)
        {
            VertexBuffer vbuf = null;

            try {
                vbuf = new VertexBuffer(typeof(CustomVertex.PositionNormalColored), L, dev,
                                        Usage.WriteOnly, CustomVertex.PositionNormalColored.Format, Pool.SystemMemory);
            } catch (Exception _exc) {
                //bs.lib.Gen.LogWin.TraceError(_exc);
                vbuf = new VertexBuffer(typeof(CustomVertex.PositionNormalColored), L, dev,
                                        Usage.WriteOnly, CustomVertex.PositionNormalColored.Format, Pool.Managed);
            }

            return(vbuf);
        }
        public void CreateDeviceTest()
        {
            Adapter adapter;

            using (var factory = new Factory1())
            {
                adapter = factory.GetAdapter(0);
            }

            using (var device = new SharpDX.Direct3D11.Device(adapter, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0))
            {
                Console.WriteLine(adapter.Description.Description);
                Console.WriteLine(device.FeatureLevel);
            }
        }
Exemple #9
0
        public static void BuildChunk(Chunk chunk, Device device)
        {
            if (chunk.BuildingContext.IsChanged)
            {
                var bufferSolid  = BuildSolid(chunk, device);
                var bufferWater  = BuildWater(chunk, device);
                var bufferSprite = BuildSprite(chunk, device);

                chunk.Buffers = new ChunkBuffers(bufferSolid, bufferWater, bufferSprite);

                chunk.BuildingContext.IsSpriteChanged = false;
                chunk.BuildingContext.IsWaterChanged  = false;
                chunk.BuildingContext.IsSolidChanged  = false;
            }
        }
Exemple #10
0
        public override void Dispose()
        {
            if (dx11Device != null)
            {
                dx11Device.Dispose();
            }
            if (dx11Factory != null)
            {
                dx11Factory.Dispose();
            }
            if (dx11Output != null)
            {
                dx11Output.Dispose();
            }
            if (dx11DuplicatedOutput != null)
            {
                dx11DuplicatedOutput.Dispose();
            }
            if (dx11ScreenTexture != null)
            {
                dx11ScreenTexture.Dispose();
            }
            if (dx11ScreenResource != null)
            {
                dx11ScreenResource.Dispose();
            }
            if (dx11ScreenSurface != null)
            {
                dx11ScreenSurface.Dispose();
            }

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

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

            bmpData = null;
            GC.SuppressFinalize(this);
        }
Exemple #11
0
        D3D11Device(SharpDX.Direct3D11.Device device)
        {
            Device  = device;
            Context = Device.ImmediateContext;

            // D2D
            DXGIDevice       = Device.QueryInterface <Device2>();
            D2DDevice        = new SharpDX.Direct2D1.Device(DXGIDevice);
            D2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(D2DDevice,
                                                                   SharpDX.Direct2D1.DeviceContextOptions.None);

            using (var factroy = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded))
            {
                Dpi = factroy.DesktopDpi;
            }
        }
Exemple #12
0
        private void ReleaseDevice()
        {
            // Display D3D11 ref counting info
            NativeDevice.ImmediateContext.ClearState();
            NativeDevice.ImmediateContext.Flush();

            if (IsDebugMode)
            {
                var deviceDebug = new SharpDX.Direct3D11.DeviceDebug(NativeDevice);
                deviceDebug.ReportLiveDeviceObjects(SharpDX.Direct3D11.ReportingLevel.Detail);
                deviceDebug.Dispose();
            }

            nativeDevice.Dispose();
            nativeDevice = null;
        }
Exemple #13
0
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect       = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

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

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

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

                // duplicate output stuff

                dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                string error = "Directx 11 initializer error.\n" + dxe.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                string error = "Directx 11 initializer error.\n" + ex.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #14
0
        //Called when mod is loading
        public override void OnLoad()
        {
            ModConsole.Print("Initializing OpenVR");
            if (!OpenVRInit())
            {
                return;
            }


            mainCamera = Camera.main;

            /*ModConsole.Print(mainCamera.cullingMask);
             * mainCamera.cullingMask = ~mainCamera.cullingMask;
             *
             * mainCamera.enabled = false;*/

            ModConsole.Print(SystemInfo.graphicsDeviceVersion);


            System.Diagnostics.Trace.WriteLine("Initializing our own D3D11 device");
            d3d11Device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.Debug);


            hook = new D3D11Hook();
            hook.Create();

            System.Diagnostics.Trace.WriteLine("Getting RenderTarget Size");

            uint w = 0, h = 0;

            vrSystem.GetRecommendedRenderTargetSize(ref w, ref h);
            vrRig = new VRRig((int)w, (int)h);

            System.Diagnostics.Trace.WriteLine("Fetching Unity D3D11 Device");
            var devChild = vrRig.leftTexture.QueryInterface <SharpDX.Direct3D11.DeviceChild>();

            unityRenderer = devChild.Device;
            devChild.Dispose();

            ModConsole.Print(unityRenderer.CreationFlags & SharpDX.Direct3D11.DeviceCreationFlags.SingleThreaded);
            vrRenderer = new VRRenderer(d3d11Device, unityRenderer, vrRig);

            hook.OnRender += HookRender;

            System.Diagnostics.Trace.WriteLine("All done");
            ModConsole.Print("MSCVR initialized");
        }
Exemple #15
0
        internal Overlay(SharpDX.Direct3D11.Device Device3D, Texture2D BackBuffer)
        {
            using (var FontFactory = new SharpDX.DirectWrite.Factory())
            {
                TextFormat = new TextFormat(FontFactory, "Segoe UI", 16.0f);
            }

            using (var Device2D = new Device(Device3D.QueryInterface <SharpDX.DXGI.Device>()))
            {
                Context2D = new DeviceContext(Device2D, DeviceContextOptions.EnableMultithreadedOptimizations);
            }

            Context2D.PrimitiveBlend = PrimitiveBlend.SourceOver;
            Brush = new SolidColorBrush(Context2D, Color.White);

            SetBackBuffer(BackBuffer);
        }
        public bool Initialize(Device device, string heightMapFileName)
        {
            // Load the height map for the terrain
            if (!LoadHeightMapFilename(heightMapFileName))
                return false;

            // Normalize the height of the height map
            NormalizeHeightMap();

            // Set the number of vertices per quad (2 triangles)
            NumberOfVerticesPerQuad = 12;
            // Initialize the vertex and index buffer.
            if (!InitializeBuffers(device))
                return false;

            return true;
        }
        public void CreateWarpDevice()
        {
            using (var d3dDevice = new SharpDX.Direct3D11.Device(DriverType.Warp, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport))
            {
                using (var device = d3dDevice.QueryInterface <Device>())
                    using (var adapter = device.Adapter)
                    {
                        Console.WriteLine(adapter.Description.Description);

                        Console.WriteLine("\tOutputs:");
                        foreach (var output in adapter.Outputs)
                        {
                            Console.WriteLine("\t\t" + output.Description.DeviceName);
                        }
                    }
            }
        }
        internal void OnSwapChainResized(SharpDX.Direct3D11.Device device, SwapChain swapChain, SwapChainDescription desc)
        {
            foreach (var val in m_nameV4CameraIndex)
            {
                MCBaseCamera tmp;
                if (val.Value.TryGetTarget(out tmp))
                {
                    tmp.OnSwapChainResized(device, swapChain, desc);
                }
            }

            if (m_default != null)
            {
                m_default.SetTextureSize(desc.ModeDescription.Width, desc.ModeDescription.Height);
                m_default.SetTextureCameraPosition(new MCVector2(0, 0));
            }
        }
Exemple #19
0
        /// <summary>
        /// デバイス作成時の処理
        /// </summary>
        /// <returns></returns>
        internal int OnCreateDevice(SharpDX.Direct3D11.Device device)
        {
            MCBaseTexture tmpTx;

            //---- イメージの読み込み
            if (!App.ImageMgr.GetTexture("AsciiStringDraw", out tmpTx))
            {
                m_asciiTx = (MCTexture)MCTexture.CreateTextureFromFile(
                    App,
                    "AsciiStringDraw",
                    "UtilSharpDX.Resources.ascii.png"
                    );
                if (m_asciiTx == null)
                {
                    throw new Exception();
                }
            }
            else
            {
                throw new Exception();
            }
            //----
            MCBaseSprite tmpSprite;

            if (!App.SpriteMgr.GetSpriteData("AsciiStringDraw", out tmpSprite))
            {
                m_asciiSprite = MCAlphanumericSprite.CreateSprite(
                    App,
                    "AsciiStringDraw",
                    m_asciiTx,
                    12, 12,
                    MC_ANC.STR_ALL
                    );
                if (m_asciiSprite == null)
                {
                    throw new Exception();
                }
            }
            else
            {
                throw new Exception();
            }
            return(0);
        }
        SharpDX.Direct3D11.Device CreateDevice(bool useSoftwareRenderer = false)
        {
            
            // We try to get the existing MonoGame 3D11 Device first
            var device = CCDrawManager.SharedDrawManager.XnaGraphicsDevice.Handle as SharpDX.Direct3D11.Device;

            if (device != null)
                return device;

            // If we get here then we probably should error out but let's keep going anyway!!


            // Windows requires BGRA support out of DX.
            var deviceFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
#if DEBUG
            deviceFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif

            var driverType =  useSoftwareRenderer ? DriverType.Software : DriverType.Hardware;

#if DEBUG
            try
            {
#endif
                device = new SharpDX.Direct3D11.Device(
                    driverType,
                    deviceFlags);

#if DEBUG
            }
            catch (SharpDXException)
            {
                // Try again without the debug flag.  This allows debug builds to run
                // on machines that don't have the debug runtime installed.
                deviceFlags &= ~SharpDX.Direct3D11.DeviceCreationFlags.Debug;
                device = new SharpDX.Direct3D11.Device(
                        driverType,
                        deviceFlags);


            }
#endif
            return device;
        }
        SharpDX.Direct3D11.Device CreateDevice(bool useSoftwareRenderer = false)
        {
            // We try to get the existing MonoGame 3D11 Device first
            var device = CCDrawManager.SharedDrawManager.XnaGraphicsDevice.Handle as SharpDX.Direct3D11.Device;

            if (device != null)
            {
                return(device);
            }

            // If we get here then we probably should error out but let's keep going anyway!!


            // Windows requires BGRA support out of DX.
            var deviceFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

#if DEBUG
            deviceFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif

            var driverType = useSoftwareRenderer ? DriverType.Software : DriverType.Hardware;

#if DEBUG
            try
            {
#endif
            device = new SharpDX.Direct3D11.Device(
                driverType,
                deviceFlags);

#if DEBUG
        }
        catch (SharpDXException)
        {
            // Try again without the debug flag.  This allows debug builds to run
            // on machines that don't have the debug runtime installed.
            deviceFlags &= ~SharpDX.Direct3D11.DeviceCreationFlags.Debug;
            device       = new SharpDX.Direct3D11.Device(
                driverType,
                deviceFlags);
        }
#endif
            return(device);
        }
Exemple #22
0
        static public D3D11Device Create()
        {
            var flags =
                SharpDX.Direct3D11.DeviceCreationFlags.Debug
                | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport
            ;
            var device = new SharpDX.Direct3D11.Device(
                SharpDX.Direct3D.DriverType.Hardware, flags
                , SharpDX.Direct3D.FeatureLevel.Level_11_1
                , SharpDX.Direct3D.FeatureLevel.Level_11_0
                , SharpDX.Direct3D.FeatureLevel.Level_10_1
                , SharpDX.Direct3D.FeatureLevel.Level_10_0
                , SharpDX.Direct3D.FeatureLevel.Level_9_3
                , SharpDX.Direct3D.FeatureLevel.Level_9_2
                , SharpDX.Direct3D.FeatureLevel.Level_9_1
                );

            return(new D3D11Device(device));
        }
Exemple #23
0
        public static IDirect3DDevice CreateDevice()
        {
            using var d3dDevice = new SharpDX.Direct3D11.Device(
                      driverType: SharpDX.Direct3D.DriverType.Hardware,
                      flags: SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);

            // Acquire the DXGI interface for the Direct3D device.
            using var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device3>();

            // Wrap the native device using a WinRT interop object.
            var hr = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out IntPtr abi);

            if (hr != 0)
            {
                throw new InvalidProgramException($"CreateDirect3D11DeviceFromDXGIDevice failed with error code {hr}.");
            }

            return(MarshalInterface <IDirect3DDevice> .FromAbi(abi));
        }
Exemple #24
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="device"></param>
        /// <param name="range"></param>
        /// <returns></returns>
        public static SharpDX.Direct3D11.Buffer CreateBuffer <T>(this SharpDX.Direct3D11.Device device, T[] range)
            where T : struct
        {
            int sizeInBytes = Marshal.SizeOf(typeof(T));

            using (var stream = new DataStream(range.Length * sizeInBytes, true, true))
            {
                stream.WriteRange(range);
                return(new SharpDX.Direct3D11.Buffer(device, stream, new SharpDX.Direct3D11.BufferDescription
                {
                    BindFlags = SharpDX.Direct3D11.BindFlags.VertexBuffer,
                    SizeInBytes = (int)stream.Length,
                    CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                    OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
                    StructureByteStride = 0,
                    Usage = SharpDX.Direct3D11.ResourceUsage.Default,
                }));
            }
        }
        /// <summary>
        /// デバイス作成時の処理
        /// </summary>
        /// <returns></returns>
        internal int OnCreateDevice(SharpDX.Direct3D11.Device device)
        {
            //if (CreatePerthCamera("DebugPerth", m_spDebugPerth))
            //{
            //    Set4VCamera(m_spDebugPerth, 0);
            //}

            var          desc = App.SwapChain.Description.ModeDescription;
            MCBaseCamera defTmpCamera;

            if (MCTextureCamera.Create(App, "DefaultCamera", desc.Width, desc.Height, out defTmpCamera))
            {
                m_default = (MCTextureCamera)defTmpCamera;
                m_default.SetCameraPosition(new MCVector2(desc.Width * 0.5f, desc.Height * -0.5f));
                Set4VCamera(m_default, 0);
            }

            return(0);
        }
Exemple #26
0
        public GpuDevice(GpuAdapter adapter)
        {
            //set member to null
            mVertexShader = null;
            mPixelShader  = null;
            mInputLayout  = null;

            //set the adapter
            Adapter = adapter;

#if DEBUG
            //creation flag, we use debug flag
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#else
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.None;
#endif
            //fetuares level: 11_0, 12_0
            var fetuares = new SharpDX.Direct3D.FeatureLevel[2]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
                SharpDX.Direct3D.FeatureLevel.Level_12_0
            };

            try
            {
                //create device with current adapter
                mDevice = new SharpDX.Direct3D11.Device(Adapter.Adapter, creationFlags, fetuares);
            }
            catch (SharpDX.SharpDXException)
            {
                //try without debug layer
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.None;

                mDevice = new SharpDX.Direct3D11.Device(Adapter.Adapter, creationFlags, fetuares);

                LogEmitter.Apply(LogLevel.Warning, "[Enable Graphics Debug Layer Failed]");
            }

            mImmediateContext = Device.ImmediateContext;

            LogEmitter.Apply(LogLevel.Information, "[Initialize Graphics Device with {0}]", adapter.Description);
            LogEmitter.Apply(LogLevel.Information, "[Graphics Device Feature Level = {0}]", Device.FeatureLevel);
        }
Exemple #27
0
        public WinformsDevice(Factory1 dxgiFactory, WinformsEye eye, CAdapter adapter,
            ControlWindow primaryWindow, SwapChainDescription primarySwapChainDesc,
            DeviceInitializationFlags flags, IFileSystem fileSystem)
        {
            this.flags = flags;
            this.eye = eye;
            this.dxgiFactory = dxgiFactory;
            this.adapter = adapter;

            d3dDevice = new Device(adapter.DXGIAdapter, CtSharpDX11.DeviceCreationFlags(flags));

            primarySwapChain = new CSwapChain(this, primaryWindow, ref primarySwapChainDesc,
                pswc => { }, () => !primaryWindow.IsVisible && additionalSwapChains.All(aswc => !aswc.Window.IsVisible));

            creator = new CDeviceChildCreator(this);
            immediateContext = new CDeviceContext(this, d3dDevice.ImmediateContext);

            additionalSwapChains = new List<CSwapChain>();
        }
Exemple #28
0
        public static IDirect3DDevice CreateDirect3DDeviceFromSharpDXDevice(SharpDX.Direct3D11.Device d3dDevice)
        {
            IDirect3DDevice device = null;

            // Acquire the DXGI interface for the Direct3D device.
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device3>())
            {
                // Wrap the native device using a WinRT interop object.
                uint hr = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out IntPtr pUnknown);

                if (hr == 0)
                {
                    device = Marshal.GetObjectForIUnknown(pUnknown) as IDirect3DDevice;
                    Marshal.Release(pUnknown);
                }
            }

            return(device);
        }
Exemple #29
0
        private void ReleaseDevice()
        {
            // Display D3D11 ref counting info
            NativeDevice.ImmediateContext.ClearState();
            NativeDevice.ImmediateContext.Flush();

            if (IsDebugMode)
            {
                var debugDevice = NativeDevice.QueryInterfaceOrNull <SharpDX.Direct3D11.DeviceDebug>();
                if (debugDevice != null)
                {
                    debugDevice.ReportLiveDeviceObjects(SharpDX.Direct3D11.ReportingLevel.Detail);
                    debugDevice.Dispose();
                }
            }

            nativeDevice.Dispose();
            nativeDevice = null;
        }
Exemple #30
0
        // グラフィック

        /// <summary>
        ///		画像ファイルからシェーダリソースビューを作成して返す。
        /// </summary>
        /// <remarks>
        ///		(参考: http://qiita.com/oguna/items/c516e09ee57d931892b6 )
        /// </remarks>
        public static (SharpDX.Direct3D11.ShaderResourceView srv, Size2F viewSize, SharpDX.Direct3D11.Texture2D texture) CreateShaderResourceViewFromFile(
            SharpDX.Direct3D11.Device d3dDevice,
            SharpDX.Direct3D11.BindFlags bindFlags,
            VariablePath 画像ファイルパス)
        {
            var 出力 = (
                srv : (SharpDX.Direct3D11.ShaderResourceView)null,
                viewSize : new Size2F(0, 0),
                texture : (SharpDX.Direct3D11.Texture2D)null);

            using (var image = new System.Drawing.Bitmap(画像ファイルパス.数なしパス))
            {
                var 画像の矩形 = new System.Drawing.Rectangle(0, 0, image.Width, image.Height);

                using (var bitmap = image.Clone(画像の矩形, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
                {
                    var ロック領域       = bitmap.LockBits(画像の矩形, System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
                    var dataBox     = new[] { new DataBox(ロック領域.Scan0, bitmap.Width * 4, bitmap.Height) };
                    var textureDesc = new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        ArraySize         = 1,
                        BindFlags         = bindFlags,
                        CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                        Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        Height            = bitmap.Height,
                        Width             = bitmap.Width,
                        MipLevels         = 1,
                        OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        Usage             = SharpDX.Direct3D11.ResourceUsage.Default
                    };
                    var texture = new SharpDX.Direct3D11.Texture2D(d3dDevice, textureDesc, dataBox);
                    bitmap.UnlockBits(ロック領域);
                    出力.srv     = new SharpDX.Direct3D11.ShaderResourceView(d3dDevice, texture);
                    出力.texture = texture;
                }

                出力.viewSize = new Size2F(画像の矩形.Width, 画像の矩形.Height);
            }

            return(出力);
        }
Exemple #31
0
        /// <summary>
        /// <p> Creates a device that uses Direct3D 11 functionality in Direct3D 12, specifying a pre-existing D3D12 device to use for D3D11 interop. </p>
        /// </summary>
        /// <param name = "deviceRef"><dd>  <p> Specifies a pre-existing D3D12 device to use for D3D11 interop. May not be <c>null</c>. </p> </dd></param>
        /// <param name = "flags"><dd>  <p> One or more bitwise OR'ed flags from <strong><see cref = "SharpDX.Direct3D11.DeviceCreationFlags"/></strong>. These are the same flags as those used by <strong>D3D11CreateDeviceAndSwapChain</strong>. Specifies which runtime layers to enable. <em>Flags</em> must be compatible with device flags, and its <em>NodeMask</em> must be a subset of the <em>NodeMask</em> provided to the present API. </p> </dd></param>
        /// <param name = "featureLevelsRef"><dd>  <p> An array of any of the following: </p> <ul> <li>D3D_FEATURE_LEVEL_12_1</li> <li>D3D_FEATURE_LEVEL_12_0</li> <li>D3D_FEATURE_LEVEL_11_1</li> <li>D3D_FEATURE_LEVEL_11_0</li> <li>D3D_FEATURE_LEVEL_10_1</li> <li>D3D_FEATURE_LEVEL_10_0</li> <li>D3D_FEATURE_LEVEL_9_3</li> <li>D3D_FEATURE_LEVEL_9_2</li> <li>D3D_FEATURE_LEVEL_9_1</li> </ul> <p> The first feature level which is less than or equal to the D3D12 device's feature level will be used to perform D3D11 validation. Creation will fail if no acceptable feature levels are provided. Providing <c>null</c> will default to the D3D12 device's feature level. </p> </dd></param>
        /// <param name = "featureLevels"><dd>  <p> The size of the feature levels array, in bytes. </p> </dd></param>
        /// <param name = "commandQueuesOut"><dd>  <p> An array of unique queues for D3D11On12 to use. Valid queue types: 3D command queue. </p> </dd></param>
        /// <param name = "numQueues"><dd>  <p> The size of the command queue array, in bytes. </p> </dd></param>
        /// <param name = "nodeMask"><dd>  <p> Which node of the D3D12 device to use. Only 1 bit may be set. </p> </dd></param>
        /// <param name = "deviceOut"><dd>  <p> Pointer to the returned <strong><see cref = "SharpDX.Direct3D11.Device"/></strong>. May be <c>null</c>. </p> </dd></param>
        /// <param name = "immediateContextOut"><dd>  <p> A reference to the returned <strong><see cref = "SharpDX.Direct3D11.DeviceContext"/></strong>. May be <c>null</c>. </p> </dd></param>
        /// <param name = "chosenFeatureLevelRef"><dd>  <p> A reference to the returned feature level. May be <c>null</c>. </p> </dd></param>
        /// <returns><p> This method returns one of the Direct3D 12 Return Codes that are documented for <strong>D3D11CreateDevice</strong>. See Direct3D 12 Return Codes. </p><p> This method returns <strong><see cref = "SdkComponentMissing"/></strong> if you specify <strong>D3D11_CREATE_DEVICE_DEBUG</strong> in <em>Flags</em> and the incorrect version of the debug layer is installed on your computer. Install the latest Windows SDK to get the correct version. </p></returns>
        /// <remarks>
        /// <p> The function signature PFN_D3D11ON12_CREATE_DEVICE is provided as a typedef, so that you can use dynamic linking techniques (GetProcAddress) instead of statically linking. </p>
        /// </remarks>
        /// <doc-id>dn933209</doc-id>
        /// <unmanaged>HRESULT D3D11On12CreateDevice([In] IUnknown* pDevice,[In] unsigned int Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In, Buffer, Optional] const IUnknown** ppCommandQueues,[In] unsigned int NumQueues,[In] unsigned int NodeMask,[Out] ID3D11Device** ppDevice,[Out, Optional] ID3D11DeviceContext** ppImmediateContext,[Out, Optional] D3D_FEATURE_LEVEL* pChosenFeatureLevel)</unmanaged>
        /// <unmanaged-short>D3D11On12CreateDevice</unmanaged-short>
        public static unsafe void On12CreateDevice(SharpDX.IUnknown deviceRef, SharpDX.Direct3D11.DeviceCreationFlags flags, SharpDX.Direct3D.FeatureLevel[] featureLevelsRef, System.Int32 featureLevels, SharpDX.IUnknown[] commandQueuesOut, System.Int32 numQueues, System.Int32 nodeMask, out SharpDX.Direct3D11.Device deviceOut, out SharpDX.Direct3D11.DeviceContext immediateContextOut, out SharpDX.Direct3D.FeatureLevel chosenFeatureLevelRef)
        {
            System.IntPtr  deviceRef_ = System.IntPtr.Zero;
            System.IntPtr *commandQueuesOut_;
            commandQueuesOut_ = (System.IntPtr *) 0;
            if (commandQueuesOut != null)
            {
                System.IntPtr *_commandQueuesOut = stackalloc System.IntPtr[commandQueuesOut.Length];
                commandQueuesOut_ = _commandQueuesOut;
            }

            System.IntPtr  deviceOut_           = System.IntPtr.Zero;
            System.IntPtr  immediateContextOut_ = System.IntPtr.Zero;
            SharpDX.Result __result__;
            deviceRef_ = SharpDX.CppObject.ToCallbackPtr <SharpDX.IUnknown>(deviceRef);
            if (commandQueuesOut != null)
            {
                for (int i = 0; i < commandQueuesOut.Length; ++i)
                {
                    (commandQueuesOut_)[i] = SharpDX.CppObject.ToCallbackPtr <SharpDX.IUnknown>(commandQueuesOut[i]);
                }
                fixed(void *chosenFeatureLevelRef_ = &chosenFeatureLevelRef)
                fixed(void *featureLevelsRef_ = featureLevelsRef)
                __result__ = D3D11On12CreateDevice_((void *)deviceRef_, unchecked ((System.Int32)flags), featureLevelsRef_, featureLevels, (void *)commandQueuesOut_, numQueues, nodeMask, &deviceOut_, &immediateContextOut_, chosenFeatureLevelRef_);

                if (deviceOut_ != System.IntPtr.Zero)
                {
                    deviceOut = new SharpDX.Direct3D11.Device(deviceOut_);
                }
                else
                {
                    deviceOut = null;
                }
                if (immediateContextOut_ != System.IntPtr.Zero)
                    immediateContextOut = new SharpDX.Direct3D11.DeviceContext(immediateContextOut_); }
                else
                {
                    immediateContextOut = null;
                }
                __result__.CheckError();
        }
Exemple #32
0
        public BasicCapture(IDirect3DDevice d, GraphicsCaptureItem i)
        {
            __item      = i;
            __device    = d;
            __d3dDevice = Direct3D11Helper.CreateSharpDXDevice(__device);

            var dxgiFactory = new SharpDX.DXGI.Factory2();
            var description = new SharpDX.DXGI.SwapChainDescription1()
            {
                Width             = __item.Size.Width,
                Height            = __item.Size.Height,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage       = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount = 2,
                Scaling     = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
                AlphaMode   = SharpDX.DXGI.AlphaMode.Premultiplied,
                Flags       = SharpDX.DXGI.SwapChainFlags.None
            };

            __swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory, __d3dDevice, ref description);

            __framePool = Direct3D11CaptureFramePool.Create(
                __device,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                2,
                i.Size);
            __session  = __framePool.CreateCaptureSession(i);
            __lastSize = i.Size;

            // Disable mouse cursor to be visible
            __session.IsCursorCaptureEnabled = false;

            __framePool.FrameArrived += OnFrameArrived;
        }
Exemple #33
0
        public bool Initialize(Device device, string heightMapFileName)
        {
            // Load the height map for the terrain
            if (!LoadHeightMapFilename(heightMapFileName))
            {
                return(false);
            }

            // Normalize the height of the height map
            NormalizeHeightMap();

            // Set the number of vertices per quad (2 triangles)
            NumberOfVerticesPerQuad = 12;
            // Initialize the vertex and index buffer.
            if (!InitializeBuffers(device))
            {
                return(false);
            }

            return(true);
        }
Exemple #34
0
        /// <summary>
        /// Creates device resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }
            catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
Exemple #35
0
        private Device CreateDxgiDevice()
        {
            var featureLevels = new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
                SharpDX.Direct3D.FeatureLevel.Level_10_1,
                SharpDX.Direct3D.FeatureLevel.Level_10_0,
                SharpDX.Direct3D.FeatureLevel.Level_9_3,
                SharpDX.Direct3D.FeatureLevel.Level_9_2,
                SharpDX.Direct3D.FeatureLevel.Level_9_1,
            };

            using (var d3dDevice = new SharpDX.Direct3D11.Device(
                       SharpDX.Direct3D.DriverType.Hardware,
                       SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport |
                       SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport,
                       featureLevels))
            {
                return(d3dDevice.QueryInterface <SharpDX.DXGI.Device>());
            }
        }
Exemple #36
0
        public static IDirect3DDevice CreateDevice(bool useWARP)
        {
            var d3dDevice = new SharpDX.Direct3D11.Device(
                useWARP ? SharpDX.Direct3D.DriverType.Software : SharpDX.Direct3D.DriverType.Hardware,
                SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);
            IDirect3DDevice device = null;

            // Acquire the DXGI interface for the Direct3D device.
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device3>())
            {
                // Wrap the native device using a WinRT interop object.
                uint hr = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out IntPtr pUnknown);

                if (hr == 0)
                {
                    device = Marshal.GetObjectForIUnknown(pUnknown) as IDirect3DDevice;
                    Marshal.Release(pUnknown);
                }
            }

            return(device);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsDevice" /> class using the default GraphicsAdapter
        /// and the Level10 <see cref="GraphicsProfile" />.
        /// </summary>
        /// <param name="device">The device.</param>
        private GraphicsDevice(GraphicsDevice device)
        {
            RootDevice = device;
            Adapter = device.Adapter;
            creationFlags = device.creationFlags;
            Features = device.Features;
            sharedDataPerDevice = device.sharedDataPerDevice;
            InputLayoutManager = device.InputLayoutManager;
            nativeDevice = device.NativeDevice;
            nativeDeviceContext = new SharpDX.Direct3D11.DeviceContext(NativeDevice).DisposeBy(this);
            nativeDeviceProfiler = SharpDX.ComObject.QueryInterfaceOrNull<SharpDX.Direct3D11.UserDefinedAnnotation>(nativeDeviceContext.NativePointer);
            isDeferred = true;
            IsDebugMode = device.IsDebugMode;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(device, nativeDeviceContext, "DeferredContext");
            }
            NeedWorkAroundForUpdateSubResource = !Features.HasDriverCommandLists;

            primitiveQuad = new PrimitiveQuad(this).DisposeBy(this);

            InitializeStages();
        }
        private void ReleaseDevice()
        {
            // Display D3D11 ref counting info
            NativeDevice.ImmediateContext.ClearState();
            NativeDevice.ImmediateContext.Flush();

            if (IsDebugMode)
            {
                var deviceDebug = new SharpDX.Direct3D11.DeviceDebug(NativeDevice);
                deviceDebug.ReportLiveDeviceObjects(SharpDX.Direct3D11.ReportingLevel.Detail);
                deviceDebug.Dispose();
            }

            nativeDevice.Dispose();
            nativeDevice = null;
        }
 public AppendPositionBufferTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.TranslateInertia | ManipulationModes.Scale;

            tileBackground.ImageSource = "Assets/bgline.JPG";

            onePointWait.Visibility = Visibility.Collapsed;
            twoPointWait.Visibility = Visibility.Collapsed;

            double val = -Math.PI / 2;
            foreach (UIElement child in colorSelect.Children)
            {
                child.SetValue(Canvas.LeftProperty, Math.Cos(val) * 70);
                child.SetValue(Canvas.TopProperty, Math.Sin(val) * 70);
                val += Math.PI / 5;
            }

            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
            d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel);

            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            using (var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags))
                d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();

            d3dContext = d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();

            using (dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
                d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);

            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            DisplayProperties.LogicalDpiChanged += LogicalDpiChanged;
        }
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

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

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

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

                // duplicate output stuff

                dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                string error = "Directx 11 initializer error.\n" + dxe.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                string error = "Directx 11 initializer error.\n" + ex.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        void CreateRenderingResources (SharpDX.Direct3D11.Device device3d, SharpDX.Direct2D1.Factory2 d2dFactory)
        {
            device = device3d;
            Factory2D = d2dFactory;

            dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>();

            d2dDevice = new SharpDX.Direct2D1.Device1(Factory2D, dxgiDevice);

            d2dResourceCreationDeviceContext = new SharpDX.Direct2D1.DeviceContext1(d2dDevice, DeviceContextOptions.None);

        }
 public BodyIndexPointCloudBufferTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            SharpDX.Direct3D.FeatureLevel[] levels = graphicsProfiles.ToFeatureLevel();
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Create Device D3D11 with feature Level based on profile
            nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, levels);
            nativeDeviceContext = nativeDevice.ImmediateContext;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }

            InitializeStages();

            // Create the input layout manager
            if (InputLayoutManager == null)
                InputLayoutManager = new InputLayoutManager(this).DisposeBy(this);
        }
 public DynamicBodyIndexTextureTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
        private void ReleaseDevice()
        {
            // Display D3D11 ref counting info
            NativeDevice.ImmediateContext.ClearState();
            NativeDevice.ImmediateContext.Flush();

            if (IsDebugMode)
            {
                var debugDevice = NativeDevice.QueryInterfaceOrNull<SharpDX.Direct3D11.DeviceDebug>();
                if (debugDevice != null)
                {
                    debugDevice.ReportLiveDeviceObjects(SharpDX.Direct3D11.ReportingLevel.Detail);
                    debugDevice.Dispose();
                }
            }

            nativeDevice.Dispose();
            nativeDevice = null;
        }
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Default fallback
            if (graphicsProfiles.Length == 0)
                graphicsProfiles = new[] { GraphicsProfile.Level_11_0, GraphicsProfile.Level_10_1, GraphicsProfile.Level_10_0, GraphicsProfile.Level_9_3, GraphicsProfile.Level_9_2, GraphicsProfile.Level_9_1 };

            // Create Device D3D11 with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // D3D12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();

                    // INTEL workaround: it seems Intel driver doesn't support properly feature level 9.x. Fallback to 10.
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (level < SharpDX.Direct3D.FeatureLevel.Level_10_0)
                            level = SharpDX.Direct3D.FeatureLevel.Level_10_0;
                    }

                    nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, level);

                    // INTEL workaround: force ShaderProfile to be 10+ as well
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (graphicsProfile < GraphicsProfile.Level_10_0 && (!ShaderProfile.HasValue || ShaderProfile.Value < GraphicsProfile.Level_10_0))
                            ShaderProfile = GraphicsProfile.Level_10_0;
                    }

                    RequestedProfile = graphicsProfile;
                    break;
                }
                catch (Exception)
                {
                    if (index == graphicsProfiles.Length - 1)
                        throw;
                }
            }

            nativeDeviceContext = nativeDevice.ImmediateContext;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }
        }
 public DynamicColorToDepthTextureTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
 public BodyJointOrientationBufferTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
        private void LoadPipeline(RenderForm form)
        {
            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            viewport.Width = width;
            viewport.Height = height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right = width;
            scissorRect.Bottom = height;

            #if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
            #endif
            device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0);
            using (var factory = new Factory4())
            {

                // Describe and create the command queue.
                CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);

                // Describe and create the swap chain.
                SwapChainDescription swapChainDesc = new SwapChainDescription()
                {
                    BufferCount = FrameCount,
                    ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    Usage = Usage.RenderTargetOutput,
                    SwapEffect = SwapEffect.FlipDiscard,
                    OutputHandle = form.Handle,
                    //Flags = SwapChainFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed = true
                };

                SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc);
                swapChain = tempSwapChain.QueryInterface<SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags = DescriptorHeapFlags.None,
                Type = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            //Init Direct3D11 device from Direct3D12 device
            device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            deviceContext11 = device11.ImmediateContext;
            device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>();
            var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded);

            // Create frame resources.
            CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer<Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                //init Direct2D surfaces
                SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };

                device11on12.CreateWrappedResource(
                    renderTargets[n], format,
                    (int)ResourceStates.Present,
                    (int)ResourceStates.RenderTarget,
                    typeof(SharpDX.Direct3D11.Resource).GUID,
                    out wrappedBackBuffers[n]);

                //Init direct2D surface
                var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>();
                direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
                d2dSurface.Dispose();
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            d2dFactory.Dispose();

            //Init font
            var directWriteFactory = new SharpDX.DirectWrite.Factory();
            textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
            textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White);
            directWriteFactory.Dispose();
        }
Exemple #51
0
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            SafeDispose(ref d3dDevice);
            SafeDispose(ref d3dContext);
            SafeDispose(ref d2dDevice);
            SafeDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
            #endif
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
 public MultiKinectCameraTextureTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
 public DynamicLongInfraredTextureTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
Exemple #54
0
 static Device1 CreateDevice()
 {
     #if NETFX_CORE
     using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
     {
         return device.QueryInterface<Device1>();
     }
     #else
     return new Device1(DriverType.Hardware, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);
     #endif
 }
 public DynamicColorRGBATextureProcessorTests()
 {
     device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Reference);
 }
Exemple #56
0
 public ScreenCapture(SharpDX.Direct3D11.Device device)
 {
     this.device = device;
     this.Reset();
 }
 public PrimitiveModel(Device device, Model baseModel) {
     this.BaseModel = baseModel;
     this.Meshes = BaseModel.Meshes.Select(m => new PrimitiveMesh(device, m)).ToArray();
 }
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            } catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
        void CreateDevice()
        {
            // d3d11
            var flags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            // error on Windows10(Geforce435M)
            //flags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
            #endif

            using (var device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware
                , flags
                , SharpDX.Direct3D.FeatureLevel.Level_10_0
                ))
            {
                D3DDevice = device.QueryInterfaceOrNull<SharpDX.Direct3D11.Device1>();
            }

            // DXGIDevice
            DXGIDevice = D3DDevice.QueryInterface<SharpDX.DXGI.Device2>();
            DXGIDevice.MaximumFrameLatency = 1;
        }