Example #1
0
        public KinectD3DImage()
        {
            if (App.Current.MainWindow != null)
            {
                IntPtr window        = new WindowInteropHelper(App.Current.MainWindow).Handle;
                var    presentparams = new SharpDX.Direct3D9.PresentParameters
                {
                    Windowed             = true,
                    SwapEffect           = SharpDX.Direct3D9.SwapEffect.Discard,
                    DeviceWindowHandle   = window,
                    PresentationInterval = PresentInterval.Immediate,
                };

                const CreateFlags deviceFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve;

                this.direct3d       = new Direct3DEx();
                this.imagingFactory = new ImagingFactory();
                this.device         = Capture.Direct3D11Helper.CreateDevice();
                this.d3dDevice      = Capture.Direct3D11Helper.CreateSharpDXDevice(this.device);
                this.d9device       = new DeviceEx(this.direct3d, 0, DeviceType.Hardware, IntPtr.Zero, deviceFlags, presentparams);
                this.IsFrontBufferAvailableChanged += this.GraphicItemD3DImageIsFrontBufferAvailableChanged;
                this.renderEvent = new ManualResetEventSlim(false);
                var renderThread = new Thread(this.RenderThread);
                renderThread.Start();
            }
        }
Example #2
0
 public Graphics(RenderForm form, int width, int height)
 {
     reset = () => form.Invoke(new Action(() =>
     {
         device.Reset(presentParameters);
         fontRenderer.Flush();
         textureRenderer.Flush();
         resized = false;
     }));
     form.UserResized += (sender, args) => Resize(form.ClientSize.Width, form.ClientSize.Height);
     presentParameters = new PresentParameters
     {
         Windowed = true,
         SwapEffect = SwapEffect.Discard,
         BackBufferFormat = Format.A8R8G8B8,
         BackBufferCount = 1,
         BackBufferWidth = width,
         BackBufferHeight = height,
         PresentationInterval = PresentInterval.One,
         MultiSampleType = MultisampleType.None,
         MultiSampleQuality = 0,
         PresentFlags = PresentFlags.LockableBackBuffer
     };
     direct3D = new Direct3DEx();
     device = new DeviceEx(direct3D, 0, DeviceType.Hardware, form.Handle, CREATE_FLAGS, presentParameters);
     fontRenderer = new FontRenderer(device);
     textureRenderer = new TextureRenderer(device);
     renderLocker.Reset();
 }
Example #3
0
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect       = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

                var format = SharpDX.Direct3D9.Format.A8R8G8B8;
                SharpDX.Direct3D9.PresentParameters present_params = new SharpDX.Direct3D9.PresentParameters();
                present_params.Windowed         = true;
                present_params.BackBufferFormat = format;
                present_params.SwapEffect       = SharpDX.Direct3D9.SwapEffect.Discard;
                present_params.BackBufferWidth  = WIDTH;
                present_params.BackBufferHeight = HEIGHT;
                dx9Device = new SharpDX.Direct3D9.Device(new SharpDX.Direct3D9.Direct3D(),
                                                         0,
                                                         SharpDX.Direct3D9.DeviceType.Hardware,
                                                         IntPtr.Zero,
                                                         SharpDX.Direct3D9.CreateFlags.HardwareVertexProcessing,
                                                         present_params);

                dx9Device.SetRenderState(RenderState.CullMode, Cull.None);
                dx9Device.SetRenderState(RenderState.Lighting, false);
                dx9Device.SetRenderState(RenderState.AntialiasedLineEnable, false);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                LdpLog.Error("SharpDX InitializeDX9\n" + dxe.Message);
            }
            catch (Exception ex)
            {
                LdpLog.Error("InitializeDX9\n" + ex.Message);
            }
        }
Example #4
0
        private void Form1_Load(object sender, EventArgs e)
        {
            direct3dInterface = new Direct3D();

            PresentParameters[] paramters = new PresentParameters[1];

            paramters[0].Windowed = true;
            paramters[0].SwapEffect = SwapEffect.Discard;
            paramters[0].DeviceWindowHandle = this.Handle;

            direct3dDevice = new Device(direct3dInterface, 0, DeviceType.Hardware, this.Handle, CreateFlags.SoftwareVertexProcessing, paramters);

            if (direct3dDevice == null)
            {
                MessageBox.Show("Error: Can not initialize Direct3D Device", Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Vertex[] vertices = new Vertex[]
            {
                new Vertex(0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f),
                new Vertex(0.5f, -.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f),
                new Vertex(-.5f, -.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f),
            };

            int bufferSize = 3 * Marshal.SizeOf<CustomVertex>();
            vertexBuffer = new VertexBuffer(direct3dDevice, bufferSize, Usage.None, vertexFormat, Pool.Managed);

            tmrUpdate.Start();
        }
Example #5
0
        static void Main(string[] args)
        {
            RenderForm form = new RenderForm("Underground - POO version");
            form.Size = new Size(1280, 700);

            Direct3D direct3D = new Direct3D();
            PresentParameters parameters = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            Device device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, parameters);
            ResManager.Initialize(ref device, ref form);
            IngameClass ingame = new IngameClass(ref device, ref form);

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

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                ingame.Draw(ref device, ref form, ref clock);

                device.EndScene();
                device.Present();
            });

            ResManager.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="D3D9"/> class.
        /// </summary>
        public D3D9()
        {
            // Create Direct3DEx device on Windows Vista/7/8 with a display configured to use 
            // the Windows Display Driver Model (WDDM). Use Direct3D on any other platform.
            _direct3D = new Direct3DEx();

            PresentParameters presentparams = new PresentParameters
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard,
                PresentationInterval = PresentInterval.Default,

                // The device back buffer is not used.
                BackBufferFormat = Format.Unknown,
                BackBufferWidth = 1,
                BackBufferHeight = 1,

                // Use dummy window handle.
                DeviceWindowHandle = GetDesktopWindow()
            };


            _device = new DeviceEx(_direct3D, 0, DeviceType.Hardware, IntPtr.Zero,
                                   CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                                   presentparams);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceContext9"/> class.
        /// </summary>
        /// <param name="handle">The window handle to associate with the device.</param>
        /// <param name="settings">The settings used to configure the device.</param>
        internal DeviceContext9(IntPtr handle, DeviceSettings9 settings)
        {
            if (handle == IntPtr.Zero)
                throw new ArgumentException("Value must be a valid window handle.", "handle");
            if (settings == null)
                throw new ArgumentNullException("settings");

            this.settings = settings;

            PresentParameters = new PresentParameters
            {
                BackBufferFormat = Format.X8R8G8B8,
                BackBufferCount = 1,
                BackBufferWidth = settings.Width,
                BackBufferHeight = settings.Height,
                MultiSampleType = MultisampleType.None,
                SwapEffect = SwapEffect.Discard,
                EnableAutoDepthStencil = true,
                AutoDepthStencilFormat = Format.D16,
                PresentFlags = PresentFlags.DiscardDepthStencil,
                PresentationInterval = PresentInterval.Default,
                Windowed = true,
                DeviceWindowHandle = handle
            };
            direct3D = new Direct3D();
            Device = new Device(direct3D, settings.AdapterOrdinal, DeviceType.Hardware, handle, settings.CreationFlags, PresentParameters);
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D9"/> class.
        /// </summary>
        /// <param name="dxgiAdapter">The target adapter.</param>
        /// <param name="isSoftwareAdapter">Are we in software mode?</param>
        /// <param name="debugEnabled">Is debug mode enabled?</param>
        internal DeviceHandlerD3D9(DXGI.Adapter1 dxgiAdapter, bool isSoftwareAdapter, bool debugEnabled)
        {
            // Update member variables
            m_dxgiAdapter = dxgiAdapter;

            try
            {
                // Just needed when on true hardware
                if (!isSoftwareAdapter)
                {
                    //Prepare device creation
                    D3D9.CreateFlags createFlags =
                        D3D9.CreateFlags.HardwareVertexProcessing |
                        D3D9.CreateFlags.PureDevice |
                        D3D9.CreateFlags.FpuPreserve |
                        D3D9.CreateFlags.Multithreaded;
                    D3D9.PresentParameters presentparams = new D3D9.PresentParameters();
                    presentparams.Windowed             = true;
                    presentparams.SwapEffect           = D3D9.SwapEffect.Discard;
                    presentparams.DeviceWindowHandle   = GetDesktopWindow();
                    presentparams.PresentationInterval = D3D9.PresentInterval.Default;
                    presentparams.BackBufferCount      = 1;

                    //Create the device finally
                    m_direct3DEx = new D3D9.Direct3DEx();

                    // Try to find the Direct3D9 adapter that maches given DXGI adapter
                    m_adapterIndex = -1;
                    for (int loop = 0; loop < m_direct3DEx.AdapterCount; loop++)
                    {
                        var d3d9AdapterInfo = m_direct3DEx.GetAdapterIdentifier(loop);
                        if (d3d9AdapterInfo.DeviceId == m_dxgiAdapter.Description1.DeviceId)
                        {
                            m_adapterIndex = loop;
                            break;
                        }
                    }

                    // Direct3D 9 is only relevant on the primary device
                    if (m_adapterIndex < 0)
                    {
                        return;
                    }

                    // Try to create the device
                    m_deviceEx = new D3D9.DeviceEx(m_direct3DEx, m_adapterIndex, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags, presentparams);
                }
                else
                {
                    //Not supported in software mode
                }
            }
            catch (Exception)
            {
                // No direct3d 9 interface support
                GraphicsHelper.SafeDispose(ref m_direct3DEx);
                GraphicsHelper.SafeDispose(ref m_deviceEx);
            }
        }
        public Device CreateDevice(int adapter, DeviceType deviceType, IntPtr hFocusWindow, CreateFlags behaviorFlags,  PresentParameters presentParams)
        {
            IntPtr devicePtr = IntPtr.Zero;
            int res = Interop.Calli(comPointer, adapter, (int)deviceType, hFocusWindow, (int)behaviorFlags, (IntPtr)(void*)&presentParams,
                                       (IntPtr)(void*)&devicePtr,(*(IntPtr**)comPointer)[16]);

            if( res < 0 ) { throw new SharpDXException( res ); }
            return new Device( devicePtr );
        }
Example #10
0
 internal GraphicsDevice(GraphicSystem graphicSystem)
 {
     _direct3D = new Direct3D();
     _graphicsSystem = graphicSystem;
     _presentParameters = new PresentParameters();
     _presentParameters.InitDefaults();
     _presentParameters.BackBufferWidth = graphicSystem.DefaultScreenWidth;
     _presentParameters.BackBufferHeight = graphicSystem.DefaultScreenHeight;
 }
 public TextureConverter Create() {
    var presentParameters = new PresentParameters {
       BackBufferCount = 2, // 1
       SwapEffect = SwapEffect.Discard,
       Windowed = true,
    };
    var direct3d = new Direct3D();
    var panel = new Panel();
    var device = new Device(direct3d, 0, DeviceType.Hardware, panel.Handle, CreateFlags.SoftwareVertexProcessing, presentParameters);
    return new TextureConverter(direct3d, panel, device);
 }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Получение параметров представления Direct3D9
            /// </summary>
            /// <returns>Параметры представления Direct3D9</returns>
            //---------------------------------------------------------------------------------------------------------
            public static Direct3D9.PresentParameters GetPresentParameters()
            {
                var present_params = new Direct3D9.PresentParameters();

                present_params.Windowed             = true;
                present_params.SwapEffect           = Direct3D9.SwapEffect.Discard;
                present_params.DeviceWindowHandle   = XNative.GetDesktopWindow();
                present_params.PresentationInterval = Direct3D9.PresentInterval.Default;

                return(present_params);
            }
Example #13
0
        private static D3D9.PresentParameters GetPresentParameters()
        {
            var presentParams = new D3D9.PresentParameters();

            presentParams.Windowed             = true;
            presentParams.SwapEffect           = D3D9.SwapEffect.Discard;
            presentParams.DeviceWindowHandle   = NativeMethods.GetDesktopWindow();
            presentParams.PresentationInterval = D3D9.PresentInterval.Default;

            return(presentParams);
        }
Example #14
0
        /// <summary>
        /// Capture a region of the screen using Direct3D
        /// </summary>
        /// <param name="handle">The handle of a window</param>
        /// <param name="region">The region to capture (in screen coordinates)</param>
        /// <returns>A bitmap containing the captured region, this should be disposed of appropriately when finished with it</returns>
        public static Bitmap CaptureRegionDirect3D(IntPtr handle, Rectangle region)
        {
            var hWnd = handle;
            Bitmap bitmap = null;
 
            // We are only supporting the primary display adapter for Direct3D mode
            
            var adapterInfo = _direct3D9.Adapters[0];
            Device device;
 
            #region Get Direct3D Device
            // Retrieve the existing Direct3D device if we already created one for the given handle
            if (_direct3DDeviceCache.ContainsKey(hWnd))
            {
                device = _direct3DDeviceCache[hWnd];
            }
            // We need to create a new device
            else
            {
                // Setup the device creation parameters
                var parameters = new PresentParameters();
                /*
                parameters.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;
                var clientRect = NativeMethods.GetAbsoluteClientRect(hWnd);
                parameters.BackBufferHeight = clientRect.Height;
                parameters.BackBufferWidth = clientRect.Width;
                parameters.MultiSampleType = MultisampleType.None;
                parameters.SwapEffect = SwapEffect.Discard;
                parameters.DeviceWindowHandle = hWnd;
                parameters.PresentationInterval = PresentInterval.Default;
                parameters.FullScreenRefreshRateInHz = 0;
                */
                // Create the Direct3D device
                device = new Device(_direct3D9, adapterInfo.Adapter, DeviceType.Hardware, hWnd, CreateFlags.SoftwareVertexProcessing, parameters);
                _direct3DDeviceCache.Add(hWnd, device);
            }
            #endregion
 
            // Capture the screen and copy the region into a Bitmap
            using (var surface = Surface.CreateOffscreenPlain(device, adapterInfo.CurrentDisplayMode.Width, adapterInfo.CurrentDisplayMode.Height, Format.A8R8G8B8, Pool.SystemMemory))
            {
                device.GetFrontBufferData(0, surface);
 
                // Update: thanks digitalutopia1 for pointing out that SlimDX have fixed a bug
                // where they previously expected a RECT type structure for their Rectangle
                bitmap = new Bitmap(Surface.ToStream(surface, ImageFileFormat.Bmp, new SharpDX.Rectangle(region.Left, region.Top, region.Width, region.Height)));
            }
            return bitmap;
        }
Example #15
0
        public DX9ScreenCapture()
        {
            Width = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
            Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight;

            PresentParameters presentParams = new PresentParameters(Width, Height)
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard
            };

            _device = new Device(new Direct3D(), 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.SoftwareVertexProcessing, presentParams);
            _surface = Surface.CreateOffscreenPlain(_device, Width, Height, Format.A8R8G8B8, Pool.Scratch);
            _buffer = new byte[Width * Height * 4];
        }
        private void StartD3D()
        {
            if (DX10ImageSource.ActiveClients != 0)
                return;

            D3DContext = new Direct3DEx();

            PresentParameters presentparams = new PresentParameters();
            presentparams.Windowed = true;
            presentparams.SwapEffect = SwapEffect.Discard;
            presentparams.DeviceWindowHandle = GetDesktopWindow();
            presentparams.PresentationInterval = PresentInterval.Default;

            DX10ImageSource.D3DDevice = new DeviceEx(D3DContext,
                0,
                DeviceType.Hardware, IntPtr.Zero,
                CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams);
        }
        public GraphicsDeviceService()
        {
            PresentParameters pp = new PresentParameters
            {
                SwapEffect = SwapEffect.Discard,
                DeviceWindowHandle = IntPtr.Zero,// windows[0].WindowHandle,
                Windowed = true,
                BackBufferWidth = 1,
                BackBufferHeight = 1,
                BackBufferFormat = Format.Unknown
            };

            Device = new DeviceEx(
                    new Direct3DEx(),
                    0, DeviceType.Hardware,
                    IntPtr.Zero, //windows[0].WindowHandle,
                    CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                    pp);
        }
        void EnsureDirectX()
        {
            if (s_d3DDevice != null)
            {
                return;
            }
            s_d3DContext = new Direct3DEx();

            SharpDX.Direct3D9.PresentParameters presentparams = new SharpDX.Direct3D9.PresentParameters
            {
                Windowed             = true,
                SwapEffect           = SharpDX.Direct3D9.SwapEffect.Discard,
                DeviceWindowHandle   = GetDesktopWindow(),
                PresentationInterval = PresentInterval.Default
            };
            s_dxDevice = s_dxDevice ?? AvaloniaLocator.Current.GetService <SharpDX.DXGI.Device>()
                         .QueryInterface <SharpDX.Direct3D11.Device>();
            s_d3DDevice = new DeviceEx(s_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams);
        }
Example #19
0
        D3D.PresentParameters[] createPresentParams(bool windowed, System.Windows.Forms.Control owner)
        {
            D3D.PresentParameters[] presentParams = new D3D.PresentParameters[1];

            //No Z (Depth) buffer or Stencil buffer
            presentParams[0].EnableAutoDepthStencil = false;

            //multiple backbuffers for a flipchain
            presentParams[0].BackBufferCount = 3;

            //Set our Window as the Device Window
            presentParams[0].DeviceWindowHandle = owner.Handle;

            //wait for VSync
            presentParams[0].PresentationInterval = D3D.PresentInterval.Immediate;

            //flip frames on vsync
            presentParams[0].SwapEffect = D3D.SwapEffect.Discard;

            //Set Windowed vs. Full-screen
            presentParams[0].Windowed = windowed;

            //We only need to set the Width/Height in full-screen mode
            if (!windowed)
            {
                presentParams[0].BackBufferHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
                presentParams[0].BackBufferWidth  = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;

                D3D.Format format = D3D.Format.X8R8G8B8;

                //Choose a compatible 16-bit mode.
                presentParams[0].BackBufferFormat = format;
            }
            else
            {
                presentParams[0].BackBufferHeight = 0;
                presentParams[0].BackBufferWidth  = 0;
                presentParams[0].BackBufferFormat = D3D.Format.Unknown;
            }

            return(presentParams);
        }
		public static void StartD3D(Window parentWindow)
		{
            _activeClients++;

			if (_activeClients > 1)
				return;

			_d3DContext = new Direct3DEx();

			var presentParameters = new PresentParameters
			{
				Windowed = true,
				SwapEffect = SwapEffect.Discard,
				DeviceWindowHandle = new WindowInteropHelper(parentWindow).Handle,
				PresentationInterval = PresentInterval.Default
			};

			_d3DDevice = new DeviceEx(_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, 
				CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
				presentParameters);
		}
Example #21
0
        public DeviceProvider()
        {
            Direct3D direct3D = new Direct3D();

            _form = new RenderForm("OpenUO - A truely open Ultima Online client");

            _presentParameters = new PresentParameters();
            _presentParameters.BackBufferFormat = Format.X8R8G8B8;
            _presentParameters.BackBufferCount = 1;
            _presentParameters.BackBufferWidth = _form.ClientSize.Width;
            _presentParameters.BackBufferHeight = _form.ClientSize.Height;
            _presentParameters.MultiSampleType = MultisampleType.None;
            _presentParameters.SwapEffect = SwapEffect.Discard;
            _presentParameters.EnableAutoDepthStencil = true;
            _presentParameters.AutoDepthStencilFormat = Format.D24S8;
            _presentParameters.PresentFlags = PresentFlags.DiscardDepthStencil;
            _presentParameters.PresentationInterval = PresentInterval.Immediate;
            _presentParameters.Windowed = true;
            _presentParameters.DeviceWindowHandle = _form.Handle;

            _device = new Device(direct3D, 0, DeviceType.Hardware, _form.Handle, CreateFlags.HardwareVertexProcessing, _presentParameters);
        }
Example #22
0
        public GraphicsItemD3DImage()
        {
            if (App.Current.MainWindow != null)
            {
                IntPtr window        = new WindowInteropHelper(App.Current.MainWindow).Handle;
                var    presentparams = new SharpDX.Direct3D9.PresentParameters
                {
                    Windowed             = true,
                    SwapEffect           = SharpDX.Direct3D9.SwapEffect.Discard,
                    DeviceWindowHandle   = window,
                    PresentationInterval = PresentInterval.Immediate,
                };

                const CreateFlags deviceFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve;

                this.direct3d  = new Direct3DEx();
                this.device    = Direct3D11Helper.CreateDevice();
                this.d3dDevice = Direct3D11Helper.CreateSharpDXDevice(this.device);
                this.d9device  = new DeviceEx(this.direct3d, 0, DeviceType.Hardware, IntPtr.Zero, deviceFlags, presentparams);
                this.IsFrontBufferAvailableChanged += this.GraphicItemD3DImageIsFrontBufferAvailableChanged;
            }
        }
Example #23
0
        /// <summary>
        /// Creates a new instance of <see cref="SharpDXElement"/> class.
        /// Initializes the D3D9 runtime.
        /// </summary>
        public SharpDXElement()
        {
            image = new D3DImage();

            var presentparams = new PresentParameters
                {
                    Windowed = true,
                    SwapEffect = SwapEffect.Discard,
                    DeviceWindowHandle = GetDesktopWindow(),
                    PresentationInterval = PresentInterval.Default
                };

            direct3D = new Direct3DEx();

            device9 = new DeviceEx(direct3D,
                                   0,
                                   DeviceType.Hardware,
                                   IntPtr.Zero,
                                   CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                                   presentparams);

            Unloaded += HandleUnloaded;
        }
Example #24
0
    /// <summary>
    /// Creates the DirectX device.
    /// </summary>
    public DeviceEx CreateDevice(D3DConfiguration configuration)
    {
      GraphicsAdapterInfo adapterInfo = configuration.AdapterInfo;
      GraphicsDeviceInfo deviceInfo = configuration.DeviceInfo;

      // Set up the presentation parameters
      _presentParams = BuildPresentParamsFromSettings(_currentGraphicsConfiguration = configuration);

      if ((deviceInfo.Caps.PrimitiveMiscCaps & PrimitiveMiscCaps.NullReference) != 0)
        // Warn user about null ref device that can't render anything
        HandleException(new NullReferenceDeviceException(), ApplicationMessage.None);

      CreateFlags createFlags;
      if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.PureHardware))
        createFlags = CreateFlags.HardwareVertexProcessing; // | CreateFlags.PureDevice;
      else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Hardware))
        createFlags = CreateFlags.HardwareVertexProcessing;
      else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Mixed))
        createFlags = CreateFlags.MixedVertexProcessing;
      else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Software))
        createFlags = CreateFlags.SoftwareVertexProcessing;
      else
        throw new ApplicationException();

      ServiceRegistration.Get<ILogger>().Info("DirectX: Using adapter: {0} {1} {2}",
          configuration.AdapterInfo.AdapterOrdinal,
          MPDirect3D.Direct3D.Adapters[configuration.AdapterInfo.AdapterOrdinal].Details.Description,
          configuration.DeviceInfo.DevType);

      // Create the device
      DeviceEx result = new DeviceEx(MPDirect3D.Direct3D,
          configuration.AdapterInfo.AdapterOrdinal,
          configuration.DeviceInfo.DevType,
          _renderTarget.Handle,
          createFlags | CreateFlags.Multithreaded | CreateFlags.EnablePresentStatistics,
          _presentParams);

      // When moving from fullscreen to windowed mode, it is important to
      // adjust the window size after recreating the device rather than
      // beforehand to ensure that you get the window size you want.  For
      // example, when switching from 640x480 fullscreen to windowed with
      // a 1000x600 window on a 1024x768 desktop, it is impossible to set
      // the window size to 1000x600 until after the display mode has
      // changed to 1024x768, because windows cannot be larger than the
      // desktop.

      StringBuilder sb = new StringBuilder();

      // Store device description
      if (deviceInfo.DevType == DeviceType.Reference)
        sb.Append("REF");
      else if (deviceInfo.DevType == DeviceType.Hardware)
        sb.Append("HAL");
      else if (deviceInfo.DevType == DeviceType.Software)
        sb.Append("SW");

      if (deviceInfo.DevType == DeviceType.Hardware)
      {
        sb.Append(": ");
        sb.Append(adapterInfo.AdapterDetails.Description);
      }

      ServiceRegistration.Get<ILogger>().Info("DirectX: {0}", sb.ToString());
      return result;
    }
Example #25
0
 /// <summary>
 /// Creates a device to represent the display adapter.
 /// </summary>
 /// <param name="direct3D">an instance of <see cref="SharpDX.Direct3D9.Direct3D"/></param>
 /// <param name="adapter">Ordinal number that denotes the display adapter. {{D3DADAPTER_DEFAULT}} is always the primary display adapter.</param>
 /// <param name="deviceType">Member of the <see cref="SharpDX.Direct3D9.DeviceType"/> enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.</param>
 /// <param name="controlHandle">The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks.        For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.</param>
 /// <param name="createFlags">Combination of one or more options that control device creation. For more information, see {{D3DCREATE}}.</param>
 /// <param name="presentParameters">Pointer to a <see cref="SharpDX.Direct3D9.PresentParameters"/> structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies {{D3DCREATE_ADAPTERGROUP_DEVICE}}, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created. For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:   User-specified nonzero ForcedRefreshRate registry key, if supported by the device. Application-specified nonzero refresh rate value in the presentation parameter. Refresh rate of the latest desktop mode, if supported by the device. 75 hertz if supported by the device. 60 hertz if supported by the device. Device default.  An unsupported refresh rate will default to the closest supported refresh rate below it.  For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz. pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:  If BackBufferCount, BackBufferWidth, and BackBufferHeight  are 0 before the method is called, they will be changed when the method returns. If BackBufferFormat equals <see cref="SharpDX.Direct3D9.Format.Unknown"/> before the method is called, it will be changed when the method returns.</param>
 /// <param name="fullScreenDisplayMode">The full screen display mode.</param>
 /// <remarks>
 /// This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in <see cref="SharpDX.Direct3D9.PresentParameters"/>). When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in <see cref="SharpDX.Direct3D9.PresentParameters"/>). The purpose of each window is:  The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application. The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during {{Present}}.  This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE.  Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window. Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method. Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.) The methods {{Reset}}, <see cref="SharpDX.ComObject"/>, and {{TestCooperativeLevel}} must be called from the same thread that used this method to create a device. D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling CreateDevice, {{Reset}}, and {{CreateAdditionalSwapChain}}. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. If you attempt to create a device on a 0x0 sized window, CreateDevice will fail.
 /// </remarks>
 /// <unmanaged>HRESULT CreateDevice([None] UINT Adapter,[None] D3DDEVTYPE DeviceType,[None] HWND hFocusWindow,[None] int BehaviorFlags,[None] D3DPRESENT_PARAMETERS* pPresentationParameters,[None] IDirect3DDevice9** ppReturnedDeviceInterface)</unmanaged>
 public DeviceEx(Direct3DEx direct3D, int adapter, DeviceType deviceType, IntPtr controlHandle, CreateFlags createFlags, PresentParameters presentParameters, DisplayModeEx fullScreenDisplayMode)
     : base(IntPtr.Zero)
 {
     direct3D.CreateDeviceEx(adapter, deviceType, controlHandle, (int)createFlags, new[] { presentParameters }, fullScreenDisplayMode == null ? null : new[] { fullScreenDisplayMode }, this);
 }
Example #26
0
 /// <summary>
 /// Creates a device to represent the display adapter.
 /// </summary>
 /// <param name="direct3D">an instance of <see cref="SharpDX.Direct3D9.Direct3D"/></param>
 /// <param name="adapter">Ordinal number that denotes the display adapter. {{D3DADAPTER_DEFAULT}} is always the primary display adapter.</param>
 /// <param name="deviceType">Member of the <see cref="SharpDX.Direct3D9.DeviceType"/> enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.</param>
 /// <param name="controlHandle">The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks.        For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.</param>
 /// <param name="createFlags">Combination of one or more options that control device creation. For more information, see {{D3DCREATE}}.</param>
 /// <param name="presentParameters">Pointer to a <see cref="SharpDX.Direct3D9.PresentParameters"/> structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies {{D3DCREATE_ADAPTERGROUP_DEVICE}}, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created. For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:   User-specified nonzero ForcedRefreshRate registry key, if supported by the device. Application-specified nonzero refresh rate value in the presentation parameter. Refresh rate of the latest desktop mode, if supported by the device. 75 hertz if supported by the device. 60 hertz if supported by the device. Device default.  An unsupported refresh rate will default to the closest supported refresh rate below it.  For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz. pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:  If BackBufferCount, BackBufferWidth, and BackBufferHeight  are 0 before the method is called, they will be changed when the method returns. If BackBufferFormat equals <see cref="SharpDX.Direct3D9.Format.Unknown"/> before the method is called, it will be changed when the method returns.</param>
 /// <remarks>
 /// This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in <see cref="SharpDX.Direct3D9.PresentParameters"/>). When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in <see cref="SharpDX.Direct3D9.PresentParameters"/>). The purpose of each window is:  The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application. The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during {{Present}}.  This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE.  Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window. Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method. Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.) The methods {{Reset}}, <see cref="SharpDX.ComObject"/>, and {{TestCooperativeLevel}} must be called from the same thread that used this method to create a device. D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling CreateDevice, {{Reset}}, and {{CreateAdditionalSwapChain}}. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. If you attempt to create a device on a 0x0 sized window, CreateDevice will fail.
 /// </remarks>
 /// <unmanaged>HRESULT CreateDevice([None] UINT Adapter,[None] D3DDEVTYPE DeviceType,[None] HWND hFocusWindow,[None] int BehaviorFlags,[None] D3DPRESENT_PARAMETERS* pPresentationParameters,[None] IDirect3DDevice9** ppReturnedDeviceInterface)</unmanaged>
 public DeviceEx(Direct3DEx direct3D, int adapter, DeviceType deviceType, IntPtr controlHandle, CreateFlags createFlags, PresentParameters presentParameters)
     : base(IntPtr.Zero)
 {
     direct3D.CreateDeviceEx(adapter, deviceType, controlHandle, (int)createFlags, new[] { presentParameters }, null, this);
 }
Example #27
0
        public Device CreateDevice(int adapter, DeviceType deviceType, IntPtr hFocusWindow, CreateFlags behaviorFlags, PresentParameters presentParams)
        {
            IntPtr devicePtr = IntPtr.Zero;
            int    res       = Interop.Calli(comPointer, adapter, (int)deviceType, hFocusWindow, (int)behaviorFlags, (IntPtr)(void *)&presentParams,
                                             (IntPtr)(void *)&devicePtr, (*(IntPtr **)comPointer)[16]);

            if (res < 0)
            {
                throw new SharpDXException(res);
            }
            return(new Device(devicePtr));
        }
Example #28
0
 public void Reset( PresentParameters presentParams )
 {
     int res = Interop.Calli(comPointer, (IntPtr)(void*)&presentParams,(*(IntPtr**)comPointer)[16]);
     if( res < 0 ) { throw new SharpDXException( res ); }
 }
Example #29
0
        /// <summary>
        /// Creates a new instance of <see cref="SharpDXElement"/> class.
        /// Initializes the D3D9 runtime.
        /// </summary>
        public SharpDXElement()
        {
            image = new D3DImage();

            var presentparams = new PresentParameters
                {
                    Windowed = true,
                    SwapEffect = SwapEffect.Discard,
                    DeviceWindowHandle = GetDesktopWindow(),
                    PresentationInterval = PresentInterval.Default
                };

            direct3D = new Direct3DEx();

            device9 = new DeviceEx(direct3D,
                                   0,
                                   DeviceType.Hardware,
                                   IntPtr.Zero,
                                   CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                                   presentparams);

            resizeDelayTimer = new DispatcherTimer(DispatcherPriority.Normal);
            resizeDelayTimer.Interval = SendResizeDelay;
            resizeDelayTimer.Tick += HandleResizeDelayTimerTick;

            SizeChanged += HandleSizeChanged;
            Unloaded += HandleUnloaded;
        }
Example #30
0
        void CreateDevice()
        {
            SharpDX.Direct3D.FeatureLevel[] levels = new SharpDX.Direct3D.FeatureLevel[] {
                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
            };
            foreach (var level in levels)
            {
                try
                {
                    this.device = new D3D11.Device(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, level);
                    break;
                }
                catch
                {
                    continue;
                }
            }
            if (this.device == null)
            {
                throw new PlatformNotSupportedException("DirectX10デバイスの作成に失敗しました");
            }

            var dxgiDevice = this.device.QueryInterface <DXGI.Device>();

            this.device2d = new D2D.Device1(this._factory.D2DFactory, dxgiDevice);
            dxgiDevice.Dispose();

            this.render = new D2D.DeviceContext1(this.device2d, D2D.DeviceContextOptions.None);

            IntPtr DesktopWnd = NativeMethods.GetDesktopWindow();

            D3D9.Direct3DEx d3dex = new D3D9.Direct3DEx();

            D3D9.PresentParameters param = new D3D9.PresentParameters();
            param.Windowed             = true;
            param.SwapEffect           = D3D9.SwapEffect.Discard;
            param.DeviceWindowHandle   = DesktopWnd;
            param.PresentationInterval = D3D9.PresentInterval.Default;

            try
            {
                this.device9 = new D3D9.DeviceEx(
                    d3dex,
                    0,
                    D3D9.DeviceType.Hardware,
                    DesktopWnd,
                    D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.Multithreaded | D3D9.CreateFlags.FpuPreserve,
                    param);
            }
            catch
            {
                try
                {
                    this.device9 = new D3D9.DeviceEx(
                        d3dex,
                        0,
                        D3D9.DeviceType.Hardware,
                        DesktopWnd,
                        D3D9.CreateFlags.SoftwareVertexProcessing | D3D9.CreateFlags.Multithreaded | D3D9.CreateFlags.FpuPreserve,
                        param);
                }
                catch
                {
                    throw new PlatformNotSupportedException("DirectX9デバイスの作成に失敗しました");
                }
            }
            finally
            {
                d3dex.Dispose();
            }
        }
Example #31
0
        public void BuildPresentParameters(ref D3D9.PresentParameters presentParams)
        {
            // Set up the presentation parameters
            var pD3D    = D3D9RenderSystem.Direct3D9;
            var devType = D3D9.DeviceType.Hardware;

            if (this._device != null)
            {
                devType = this._device.DeviceType;
            }

#warning Do we need to zero anything here or does everything get inited?
            //ZeroMemory( presentParams, sizeof(D3DPRESENT_PARAMETERS) );

            presentParams.Windowed   = !isFullScreen;
            presentParams.SwapEffect = D3D9.SwapEffect.Discard;
            // triple buffer if VSync is on
            presentParams.BackBufferCount           = this._vSync ? 2 : 1;
            presentParams.EnableAutoDepthStencil    = isDepthBuffered;
            presentParams.DeviceWindowHandle        = this._windowHandle.Handle;
            presentParams.BackBufferWidth           = width;
            presentParams.BackBufferHeight          = height;
            presentParams.FullScreenRefreshRateInHz = isFullScreen ? this._displayFrequency : 0;

            if (presentParams.BackBufferWidth == 0)
            {
                presentParams.BackBufferWidth = 1;
            }

            if (presentParams.BackBufferHeight == 0)
            {
                presentParams.BackBufferHeight = 1;
            }

            if (this._vSync)
            {
                // D3D9 only seems to support 2-4 presentation intervals in fullscreen
                if (isFullScreen)
                {
                    switch (this._vSyncInterval)
                    {
                    case 1:
                    default:
                        presentParams.PresentationInterval = D3D9.PresentInterval.One;
                        break;

                    case 2:
                        presentParams.PresentationInterval = D3D9.PresentInterval.Two;
                        break;

                    case 3:
                        presentParams.PresentationInterval = D3D9.PresentInterval.Three;
                        break;

                    case 4:
                        presentParams.PresentationInterval = D3D9.PresentInterval.Four;
                        break;
                    }
                    ;
                    // check that the interval was supported, revert to 1 to be safe otherwise
                    var caps = pD3D.GetDeviceCaps(this._device.AdapterNumber, devType);
                    if ((caps.PresentationIntervals & presentParams.PresentationInterval) == 0)
                    {
                        presentParams.PresentationInterval = D3D9.PresentInterval.One;
                    }
                }
                else
                {
                    presentParams.PresentationInterval = D3D9.PresentInterval.One;
                }
            }
            else
            {
                // NB not using vsync in windowed mode in D3D9 can cause jerking at low
                // frame rates no matter what buffering modes are used (odd - perhaps a
                // timer issue in D3D9 since GL doesn't suffer from this)
                // low is < 200fps in this context
                if (!isFullScreen)
                {
                    LogManager.Instance.Write("D3D9 : WARNING - " +
                                              "disabling VSync in windowed mode can cause timing issues at lower " +
                                              "frame rates, turn VSync on if you observe this problem.");
                }
                presentParams.PresentationInterval = D3D9.PresentInterval.Immediate;
            }

            presentParams.BackBufferFormat = D3D9.Format.R5G6B5;
            if (colorDepth > 16)
            {
                presentParams.BackBufferFormat = D3D9.Format.X8R8G8B8;
            }

            if (colorDepth > 16)
            {
                // Try to create a 32-bit depth, 8-bit stencil

                if (
                    !pD3D.CheckDeviceFormat(this._device.AdapterNumber, devType, presentParams.BackBufferFormat,
                                            D3D9.Usage.DepthStencil,
                                            D3D9.ResourceType.Surface, D3D9.Format.D24S8))
                {
                    // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer
                    if (
                        !pD3D.CheckDeviceFormat(this._device.AdapterNumber, devType, presentParams.BackBufferFormat,
                                                D3D9.Usage.DepthStencil,
                                                D3D9.ResourceType.Surface, D3D9.Format.D32))
                    {
                        // Jeez, what a naff card. Fall back on 16-bit depth buffering
                        presentParams.AutoDepthStencilFormat = D3D9.Format.D16;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = D3D9.Format.D32;
                    }
                }
                else
                {
                    // Woohoo!
                    if (pD3D.CheckDepthStencilMatch(this._device.AdapterNumber, devType, presentParams.BackBufferFormat,
                                                    presentParams.BackBufferFormat, D3D9.Format.D24S8))
                    {
                        presentParams.AutoDepthStencilFormat = D3D9.Format.D24S8;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = D3D9.Format.D24X8;
                    }
                }
            }
            else
            {
                // 16-bit depth, software stencil
                presentParams.AutoDepthStencilFormat = D3D9.Format.D16;
            }


            var rsys = (D3D9RenderSystem)Root.Instance.RenderSystem;

            rsys.DetermineFSAASettings(this._device.D3DDevice, fsaa, fsaaHint, presentParams.BackBufferFormat, isFullScreen,
                                       out this._fsaaType, out this._fsaaQuality);

            presentParams.MultiSampleType    = this._fsaaType;
            presentParams.MultiSampleQuality = (this._fsaaQuality == 0) ? 0 : this._fsaaQuality;

            // Check sRGB
            if (hwGamma)
            {
                /* hmm, this never succeeds even when device does support??
                 * if(FAILED(pD3D->CheckDeviceFormat(mDriver->getAdapterNumber(),
                 *      devType, presentParams->BackBufferFormat, D3DUSAGE_QUERY_SRGBWRITE,
                 *      D3DRTYPE_SURFACE, presentParams->BackBufferFormat )))
                 * {
                 *      // disable - not supported
                 *      mHwGamma = false;
                 * }
                 */
            }
        }
Example #32
0
 public static int Reset(IntPtr ptr, PresentParameters presentParams)
 {
     return(Interop.Calli(ptr, (IntPtr)(void *)&presentParams, (*(IntPtr **)ptr)[16]));
 }
Example #33
0
        public void Sin()
        {
            for (int i = 0; i < NumChanel; i++)
            {
                vectormas[i] = new Vector2[NumVect];
            }

            form = new RenderForm("DirectX Rendered Window");
            //form.AllowUserResizing = false;
            form.UserResized += new EventHandler<EventArgs>(onResize);
            PresentParameters presentParams = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, presentParams);

            //Line[] linemas = new Line[NumChanel];
            for (int i = 0; i < NumChanel; i++)
            {
                linemas[i] = new Line(device);
                linemas[i].Width = 1;
            }

            /*Line line = new Line(device);
            line.Width = 1;
            Line line2 = new Line(device);
            line2.Width = 3;*/

            //ColorBGRA[] colormas = new ColorBGRA[NumChanel];
            Random randColor = new Random();

            for (int i = 0; i < NumChanel; i++)
            {
                colormas[i].B = (byte)randColor.Next(0, 255);
                colormas[i].G = (byte)randColor.Next(0, 255);
                colormas[i].R = (byte)randColor.Next(0, 255);
                colormas[i].A = 255;
            }

            var timer = new System.Timers.Timer(1);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(onTick);
            timer.Enabled = true;

            /*double x = 0;
            for (int i = 0; i < NumVect; i++)
            {
                x+=0.1;
                double y = 100*Math.Sin(x * Math.PI / 15.0)+300;
                vector[i] = new Vector2((float)x,(float)y);
            }*/

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                //device.SoftwareVertexProcessing = true;
                device.BeginScene();

                //line.Antialias = true;
                //line2.Antialias = true;
                //line.GLLines = true;
                //line2.GLLines = true;
                //line.PatternScale = (float)5;
                //line.Pattern = 0xFFFFFF;

                //line.Draw(vector, color);
                //line2.Draw(vector2, color2);

                for (int i = 0; i < NumChanel; i++)
                {
                    linemas[i].Draw(vectormas[i], colormas[i]);
                    linemas[i].Antialias = true;
                }

                device.EndScene();
                device.Present();
            });
        }
Example #34
0
        /// <summary>
        ///     Reset the _renderTarget so that we are sure it will have the correct presentation parameters (required to support
        ///     working across changes to windowed/fullscreen or resolution changes)
        /// </summary>
        /// <param name="devicePtr"></param>
        /// <param name="presentParameters"></param>
        /// <returns></returns>
        private int ResetHook(IntPtr devicePtr, ref PresentParameters presentParameters)
        {
            Cleanup();

            return Direct3DDevice_ResetHook.Original(devicePtr, ref presentParameters);
        }
Example #35
0
        private static void CreateDeviceWithFallback(Format backbufferFmt, Format depthFmt)
        {
            var p = Parameters;

            p.BackBufferFormat = backbufferFmt;
            p.AutoDepthStencilFormat = depthFmt;

            p.BackBufferHeight = 800;
            p.BackBufferWidth = 600;
            p.FullScreenRefreshRateInHz = 0;
            p.Windowed = true;
            m_parameters = p;

            CreateDevice(m_windowHandle, m_settings);
        }
Example #36
0
        public static void ApplySettings(MyRenderDeviceSettings settings)
        {
            bool canReset = m_settings.AdapterOrdinal == settings.AdapterOrdinal;
            m_settings = settings;
            m_parameters = CreatePresentParameters(m_settings, m_windowHandle);
            SupportsHDR = GetAdaptersList()[m_settings.AdapterOrdinal].HDRSupported;

            if (canReset)
            {
                if (!Reset())
                    Recreate();
            }
            else
            {
                Recreate();
            }
        }
Example #37
0
 /// <summary>
 /// Build presentation parameters from the current settings.
 /// </summary>
 public void BuildPresentParamsFromSettings()
 {
   _presentParams = BuildPresentParamsFromSettings(_currentGraphicsConfiguration);
 }
Example #38
0
        /// <summary>Initialises Direct3D.</summary>
        /// <param name="windowed">Whether to display in a window.</param>
        /// <param name="vsync">Whether to use vsync.</param>
        private void InitialiseDirect3D(bool windowed, bool vsync)
        {
            _presentParameters = new PresentParameters(ClientSize.Width, ClientSize.Height);
            _presentParameters.Windowed = windowed;

            if(vsync)
                _presentParameters.PresentationInterval = PresentInterval.One;
            else
                _presentParameters.PresentationInterval = PresentInterval.Immediate;

            _direct3D = new Direct3D();
            _disposableResources.Add(_direct3D);

            _device = new Device(_direct3D, 0, DeviceType.Hardware, Handle, CreateFlags.HardwareVertexProcessing, _presentParameters);
            _disposableResources.Add(_device);

            for(int i = 0; i < _dx9Resources.Count; i++)
                _dx9Resources[i].DeviceCreated(_device);

            for(int i = 0; i < _dx9Resources.Count; i++)
                _dx9Resources[i].DeviceReset(_device);
        }
Example #39
0
    /// <summary>
    /// Build presentation parameters from the given settings.
    /// </summary>
    /// <param name="configuration">Graphics configuration to use.</param>
    public PresentParameters BuildPresentParamsFromSettings(D3DConfiguration configuration)
    {
      int backBufferWidth;
      int backBufferHeight;
      if (configuration.DeviceCombo.IsWindowed)
      {
        backBufferWidth = _renderTarget.ClientRectangle.Width;
        backBufferHeight = _renderTarget.ClientRectangle.Height;
      }
      else
      {
        backBufferWidth = configuration.DisplayMode.Width;
        backBufferHeight = configuration.DisplayMode.Height;
      }

      ServiceRegistration.Get<ILogger>().Debug("BuildPresentParamsFromSettings: Windowed = {0},  {1} x {2}",
          configuration.DeviceCombo.IsWindowed, backBufferWidth, backBufferHeight);

      PresentParameters result = new PresentParameters();

      AppSettings settings = ServiceRegistration.Get<ISettingsManager>().Load<AppSettings>();

      DeviceCombo dc = configuration.DeviceCombo;
      MultisampleType mst = settings.MultisampleType;
      mst = dc.MultisampleTypes.ContainsKey(mst) ? mst : MultisampleType.None;
      result.MultiSampleType = mst;
      result.MultiSampleQuality = 0;
      result.EnableAutoDepthStencil = false;
      result.AutoDepthStencilFormat = dc.DepthStencilFormats.FirstOrDefault(dsf =>
          !dc.DepthStencilMultiSampleConflicts.Contains(new DepthStencilMultiSampleConflict {DepthStencilFormat = dsf, MultisampleType = mst}));
      // Note that PresentFlags.Video makes NVidia graphics drivers switch off multisampling antialiasing
      result.PresentFlags = PresentFlags.None;
      // Attention: assigning the Form's handle to DeviceWindowHandle resets its Location!
      Point location = _renderTarget.Location;
      result.DeviceWindowHandle = _renderTarget.Handle;
      _renderTarget.Location = location;
      result.Windowed = configuration.DeviceCombo.IsWindowed;
      result.BackBufferFormat = configuration.DeviceCombo.BackBufferFormat;
#if PROFILE_PERFORMANCE
      result.BackBufferCount = 20; // Such high backbuffer count is only useful for benchmarking so that rendering is not limited by backbuffer count
      result.PresentationInterval = PresentInterval.One;
#else
      result.BackBufferCount = 4; // 2 to 4 are recommended for FlipEx swap mode
      result.PresentationInterval = PresentInterval.One;
#endif
      result.FullScreenRefreshRateInHz = result.Windowed ? 0 : configuration.DisplayMode.RefreshRate;
      
      // From http://msdn.microsoft.com/en-us/library/windows/desktop/bb173422%28v=vs.85%29.aspx :
      // To use multisampling, the SwapEffect member of D3DPRESENT_PARAMETER must be set to D3DSWAPEFFECT_DISCARD.
      // SwapEffect must be set to SwapEffect.FlipEx to support the Present property to be Present.ForceImmediate
      // (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb174343%28v=vs.85%29.aspx )
      result.SwapEffect = mst == MultisampleType.None ? SwapEffect.FlipEx : SwapEffect.Discard;

      result.BackBufferWidth = backBufferWidth;
      result.BackBufferHeight = backBufferHeight;

      return result;
    }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SwapChain"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="presentParameters">The present parameters.</param>
 /// <unmanaged>HRESULT IDirect3DDevice9::CreateAdditionalSwapChain([In] D3DPRESENT_PARAMETERS* pPresentationParameters,[In] IDirect3DSwapChain9** pSwapChain)</unmanaged>
 public SwapChain(Device device, PresentParameters presentParameters)
 {
     device.CreateAdditionalSwapChain(ref presentParameters, this);
 }
 public int Reset(PresentParameters presentParams)
 {
     return(Interop.Calli(comPointer, (IntPtr)(void *)&presentParams, (*(IntPtr **)comPointer)[16]));
 }
Example #42
0
        //Переделать
        private void onResize(Object source, EventArgs e)
        {
            PresentParameters presentParams = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, presentParams);

            for (int i = 0; i < NumChanel; i++)
            {
                linemas[i] = new Line(device);
                linemas[i].Width = 1;
            }
        }
Example #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SwapChain"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="presentParameters">The present parameters.</param>
 /// <unmanaged>HRESULT IDirect3DDevice9::CreateAdditionalSwapChain([In] D3DPRESENT_PARAMETERS* pPresentationParameters,[In] IDirect3DSwapChain9** pSwapChain)</unmanaged>
 public SwapChain(Device device, PresentParameters presentParameters)
 {
     device.CreateAdditionalSwapChain(ref presentParameters, this);
 }
Example #44
0
        private static void TryCreateDeviceInternal(IntPtr windowHandle, DeviceType deviceType, MyRenderDeviceSettings settingsToTry, out Device device, out PresentParameters parameters)
        {
            device = null;
            parameters = CreatePresentParameters(settingsToTry, windowHandle);
            while (device == null)
            {
                try
                {
                    // These calls are here to ensure that none of these calls throw exceptions (even if their results are not used).
                    m_d3d.Dispose();
                    m_d3d = new Direct3D();

                    var d3dCaps = m_d3d.GetDeviceCaps(settingsToTry.AdapterOrdinal, DeviceType.Hardware);

                    device = new Device(m_d3d, settingsToTry.AdapterOrdinal, deviceType, Parameters.DeviceWindowHandle,
                        CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                        Parameters);
                    device.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(0, 0, 0, 1), 1.0f, 0);

                    var caps = Device.Capabilities;
                }
                catch (SharpDX.SharpDXException e)
                {
                    if (e.ResultCode == ResultCode.NotAvailable ||
                        (e.ResultCode == ResultCode.InvalidCall && GetForegroundWindow() != Parameters.DeviceWindowHandle))
                    {
                        // User has probably Alt+Tabbed or locked his computer before the game has started.
                        // To counter this, we try creating device again a bit later.
                        Thread.Sleep(2000);
                        MyLog.Default.WriteLine("Device creation failed with " + e.Message);
                    }
                    else
                    {
                        // Either settings or graphics card are not supported.
                        MyLog.Default.WriteLine(e);
                        throw;
                    }
                }

                try
                {
                    MyLog.Default.WriteLine("Loading adapters");
                    m_adaptersList = GetAdaptersList(m_d3d);
                    MyLog.Default.WriteLine("Found adapters");
                    foreach (var adapter in m_adaptersList)
                    {
                        adapter.LogInfo(MyLog.Default.WriteLine);
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                    throw;
                }
            }
        }
Example #45
0
        /// <summary>
        /// Reset the _renderTarget so that we are sure it will have the correct presentation parameters (required to support working across changes to windowed/fullscreen or resolution changes)
        /// </summary>
        /// <param name="devicePtr"></param>
        /// <param name="presentParameters"></param>
        /// <returns></returns>
        int ResetHook(IntPtr devicePtr, ref PresentParameters presentParameters)
        {
            // Ensure certain overlay resources have performed necessary pre-reset tasks
            if (_overlayEngine != null)
                _overlayEngine.BeforeDeviceReset();

            Cleanup();

            return Direct3DDevice_ResetHook.Original(devicePtr, ref presentParameters);
        }
Example #46
0
        private static PresentParameters CreatePresentParameters(MyRenderDeviceSettings settings, IntPtr windowHandle)
        {
            PresentParameters p = new PresentParameters();
            p.InitDefaults();

            switch (settings.WindowMode)
            {
                case MyWindowModeEnum.Fullscreen:
                    p.FullScreenRefreshRateInHz = settings.RefreshRate;
                    p.BackBufferHeight = settings.BackBufferHeight;
                    p.BackBufferWidth = settings.BackBufferWidth;
                    p.Windowed = false;
                    break;

                case MyWindowModeEnum.FullscreenWindow:
                    {
                        WinApi.DEVMODE mode = new WinApi.DEVMODE();
                        WinApi.EnumDisplaySettings(null, WinApi.ENUM_REGISTRY_SETTINGS, ref mode);
                        p.FullScreenRefreshRateInHz = 0;
                        p.BackBufferHeight = mode.dmPelsHeight;
                        p.BackBufferWidth = mode.dmPelsWidth;
                        p.Windowed = true;
                    }
                    break;

                case MyWindowModeEnum.Window:
                    p.FullScreenRefreshRateInHz = 0;
                    p.BackBufferHeight = settings.BackBufferHeight;
                    p.BackBufferWidth = settings.BackBufferWidth;
                    p.Windowed = true;
                    break;
            }
            p.DeviceWindowHandle = windowHandle;

            p.AutoDepthStencilFormat = Format.D24S8;
            p.EnableAutoDepthStencil = true;
            p.BackBufferFormat = Format.X8R8G8B8;
            p.MultiSampleQuality = 0;
            p.PresentationInterval = settings.VSync ? PresentInterval.One : PresentInterval.Immediate;
            p.SwapEffect = SwapEffect.Discard;

            // PresentFlags.Video may cause crash when driver settings has overridden multisampling
            // We don't need it, it's just hint for driver
            p.PresentFlags = PresentFlags.DiscardDepthStencil;

            return p;
        }