Ejemplo n.º 1
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();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes all adapters with the specified factory.
        /// </summary>
        /// <param name="factory1">The factory1.</param>
        internal static void Initialize()
        {
            if (staticCollector != null)
            {
                staticCollector.Dispose();
            }
            else
            {
                staticCollector = new DisposeCollector();
            }

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

            D3D = new Direct3D9.Direct3D();

            var adapters = new List <GraphicsAdapter>();

            for (int i = 0; i < D3D.AdapterCount; i++)
            {
                var adapter = new GraphicsAdapter(i);
                staticCollector.Collect(adapter);
                adapters.Add(adapter);
            }

            Default  = adapters[0];
            Adapters = adapters.ToArray();
        }
Ejemplo n.º 3
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();
        }
Ejemplo n.º 4
0
        /// <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);
        }
Ejemplo n.º 5
0
        public WinformsDevice(WinformsEye eye, Direct3D direct3D, CAdapter adapter, 
            ControlWindow primaryWindow, SwapChainDescription implicitSwapChainDesc, 
            DeviceInitializationFlags flags, IFileSystem fileSystem)
        {
            this.eye = eye;
            this.adapter = adapter;
            this.primaryWindow = primaryWindow;
            this.implicitSwapChainDesc = implicitSwapChainDesc;
            this.flags = flags;

            caps = adapter.Info.GetCaps(DeviceType.Hardware);
            devicePresentParams = new PresentParameters();

            FillDevicePresentParams();
            d3dDevice = new Device(direct3D, adapter.Index, DeviceType.Hardware, primaryWindow.Handle, CreateFlags.FpuPreserve | CreateFlags.HardwareVertexProcessing, devicePresentParams);

            CreateBackBufferAndDepthStencil();

            additionalSwapChains = new List<CAdditionalSwapChain>();
            creator = new CDeviceChildCreator(this);
            immediateContext = new CDeviceContext(this);

            lastSwapChainSize = new IntSize(primaryWindow.SwapChainWidth, primaryWindow.SwapChainHeight);
            fullscreenState = FullscreenState.Windowed;
            fullscreenDisplayMode = adapter.GetSupportedDisplayModes().First();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes all adapters with the specified factory.
        /// </summary>
        /// <param name="factory1">The factory1.</param>
        internal static void Initialize()
        {
            if (staticCollector != null)
            {
                staticCollector.Dispose();
            }
            else
                staticCollector = new DisposeCollector();

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

            D3D = new Direct3D9.Direct3D();

            var adapters = new List<GraphicsAdapter>();
            for (int i = 0; i < D3D.AdapterCount; i++)
            {
                var adapter = new GraphicsAdapter(i);
                staticCollector.Collect(adapter);
                adapters.Add(adapter);
            }

            Default = adapters[0];
            Adapters = adapters.ToArray();
        }
Ejemplo n.º 7
0
        private static MyDisplayMode[] GetSupportedDisplayModes(Direct3D d3d, int adapterOrdinal)
        {
            var modeAvailable = new List<MyDisplayMode>();
            var modeMap = new Dictionary<string, MyDisplayMode>();

            SharpDX.Direct3D9.Format format = m_backbufferFormat;

            int modeCount = format == Format.Unknown ? 0 : d3d.GetAdapterModeCount(adapterOrdinal, format);
            for (int modeIndex = 0; modeIndex < modeCount; modeIndex++)
            {
                var mode = d3d.EnumAdapterModes(adapterOrdinal, (SharpDX.Direct3D9.Format)format, modeIndex);

                string key = format + ";" + mode.Width + ";" + mode.Height + ";" + mode.RefreshRate;

                MyDisplayMode oldMode;
                if (!modeMap.TryGetValue(key, out oldMode))
                {
                    var displayMode = new MyDisplayMode()
                    {
                        Width = mode.Width,
                        Height = mode.Height,
                        RefreshRate = mode.RefreshRate,
                        AspectRatio = mode.AspectRatio
                    };

                    modeMap.Add(key, displayMode);
                    modeAvailable.Add(displayMode);
                }
            }

            modeAvailable.Sort(m_refreshRatePriorityComparer);
            return modeAvailable.ToArray();
        }
Ejemplo n.º 8
0
 internal GraphicsDevice(GraphicSystem graphicSystem)
 {
     _direct3D = new Direct3D();
     _graphicsSystem = graphicSystem;
     _presentParameters = new PresentParameters();
     _presentParameters.InitDefaults();
     _presentParameters.BackBufferWidth = graphicSystem.DefaultScreenWidth;
     _presentParameters.BackBufferHeight = graphicSystem.DefaultScreenHeight;
 }
Ejemplo n.º 9
0
        public override unsafe void CreateHooks()
        {
            _d3DDeviceFunctions = new List <IntPtr>();

            using (var direct3D = new SharpDX.Direct3D9.Direct3D())
            {
                using (var device = new Device(direct3D, 0, DeviceType.NullReference, IntPtr.Zero,
                                               CreateFlags.HardwareVertexProcessing,
                                               new PresentParameters {
                    BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = IntPtr.Zero
                }))
                {
                    _d3DDeviceFunctions.AddRange(ReadVTableAddresses(device.NativePointer, D3DDevice9FunctionCount));
                }
            }

            // Create the hooks for our target Direct3D Device functions.
            _d3DEndSceneHook = HookFactory.CreateHook <IDirect3DDevice9_EndSceneDelegate>(
                _d3DDeviceFunctions[(int)FunctionOrdinals.EndScene],
                Detour_EndScene,
                this);

            _d3DPresentHook = HookFactory.CreateHook <IDirect3DDevice9_PresentDelegate>(
                _d3DDeviceFunctions[(int)FunctionOrdinals.Present],
                Detour_Present,
                this);

            _d3DResetHook = HookFactory.CreateHook <IDirect3DDevice9_ResetDelegate>(
                _d3DDeviceFunctions[(int)FunctionOrdinals.Reset],
                Detour_Reset,
                this);

            // Add the Frames Per Second overlay.
            Overlays = new List <IOverlay>
            {
                new Direct3D.Core.Drawing.Overlay
                {
                    Elements =
                    {
                        new FramesPerSecondOverlay(new System.Drawing.Font("Arial",  16, FontStyle.Bold))
                        {
                            Location    = new System.Drawing.Point(25,              25),
                            Color       = Color.Red,
                            AntiAliased = true,
                            Text        = "{0:N0} FPS"
                        }
                    },
                    Hidden = false
                }
            };

            // Enable the hooks for all threads except the current thread.
            _d3DEndSceneHook.ThreadACL.SetExclusiveACL(new int[1]);
            _d3DPresentHook.ThreadACL.SetExclusiveACL(new int[1]);
            _d3DResetHook.ThreadACL.SetExclusiveACL(new int[1]);
        }
Ejemplo n.º 10
0
        public void initialize(int videoWidth, int videoHeight)
        {
            try
            {
                this.videoHeight = videoHeight;
                this.videoWidth  = videoWidth;

                if (direct3D == null)
                {
                    SharpDX.Result resultCode;

                    direct3D = new D3D.Direct3D();

                    if (direct3D.CheckDeviceFormatConversion(
                            0,
                            D3D.DeviceType.Hardware,
                            makeFourCC('Y', 'V', '1', '2'),
                            D3D.Format.X8R8G8B8,
                            out resultCode) == false)
                    {
                        throw new SharpDX.SharpDXException("Video Hardware does not support YV12 format conversion");
                    }

                    D3D.PresentParameters[] presentParams = createPresentParams(windowed, owner);

                    device = new D3D.Device(direct3D,
                                            0,
                                            D3D.DeviceType.Hardware,
                                            owner.Handle,
                                            D3D.CreateFlags.SoftwareVertexProcessing,
                                            presentParams);

                    releaseResources();
                    aquireResources();
                }
                else
                {
                    releaseResources();

                    D3D.PresentParameters[] presentParams = createPresentParams(windowed, owner);

                    device.Reset(presentParams);

                    aquireResources();
                }

                int sizeBytes = videoWidth * (videoHeight + videoHeight / 2);
                offscreenBuffer = new Byte[sizeBytes];

                //log.Info("Direct3D Initialized");
            }
            catch (SharpDX.SharpDXException e)
            {
                throw new VideoPlayerException("Direct3D Initialization error: " + e.Message, e);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Disposes of all objects
        /// </summary>
        internal static void DisposeStatic()
        {
            ((IDisposable)staticCollector).Dispose();

            if (D3D != null)
            {
                D3D.Dispose();
                D3D = null;
            }
        }
        private static MyAdapterInfo[] GetAdaptersList(Direct3D d3d)
        {
            MyAdapterInfo[] result = new MyAdapterInfo[d3d.AdapterCount];
            for (var i = 0; i < result.Length; i++)
            {
                result[i] = new MyAdapterInfo();
                var details = d3d.GetAdapterIdentifier(i);

                var currentDisplayMode = d3d.GetAdapterDisplayMode(i);
                result[i].CurrentDisplayMode = new MyDisplayMode { Height = currentDisplayMode.Height, Width = currentDisplayMode.Width, RefreshRate = currentDisplayMode.RefreshRate, AspectRatio = currentDisplayMode.AspectRatio };
                result[i].DeviceName = details.DeviceName;
                result[i].VendorId = details.VendorId;
                result[i].DeviceId = details.DeviceId;
                result[i].Description = details.Description;
                result[i].Name = details.Description + " (" + details.DeviceName.Replace("\\", "").Replace(".", "") + ")";
                result[i].SupportedDisplayModes = new MyDisplayMode[0];

                bool retry = false;
                try
                {
                    result[i].SupportedDisplayModes = GetSupportedDisplayModes(d3d, i);
                }
                catch (SharpDXException dxgiException)
                {
                    if (dxgiException.ResultCode != ResultCode.NotAvailable)
                    {
                        throw;
                    }

                    m_backbufferFormat = Format.A8B8G8R8;
                    retry = true;
                }

                if (retry)
                {
                    try
                    {
                        result[i].SupportedDisplayModes = GetSupportedDisplayModes(d3d, i);
                    }
                    catch (SharpDXException dxgiException)
                    {
                        if (dxgiException.ResultCode != ResultCode.NotAvailable)
                        {
                            throw;
                        }
                    }
                }
            }

            MyGraphicTest test = new MyGraphicTest();
            test.TestDX(d3d, ref result);

            return result;
        }
 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);
 }
Ejemplo n.º 14
0
 public static MyAdapterInfo[] GetAdaptersList()
 {
     // if null return unchecked list from d3d
     if (m_adaptersList == null)
     {
         using (var tmpD3d = new Direct3D())
         {
             return GetAdaptersList(tmpD3d);
         }
     }
     // else return list filled from correct device (not created during devicelost state when adapters params are incorrect)
     return m_adaptersList;
 }
Ejemplo n.º 15
0
        public DX(D3D9.Direct3D direct3D, D3D9.Device device)
        {
            Direct3D   = direct3D;
            Device     = device;
            GlobalLock = new object();

            if (Device.Capabilities.PixelShaderVersion < new Version(2, 0) ||
                Device.Capabilities.VertexShaderVersion < new Version(2, 0))
            {
                MessageBox.Show("This computer doesn't support Vertex and Pixel Shader version 2. Get with the times.");
                Application.Exit();
            }
        }
Ejemplo n.º 16
0
        public void Initialize()
        {
            Direct3D = new Direct3D();
            Device = new Device(Direct3D, 0, DeviceType.Hardware, dxViewport.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(dxViewport.Width, dxViewport.Height));
            Device.SetTransform(TransformState.Projection, Matrix.OrthoLH(dxViewport.Width, dxViewport.Height, -1, 1));
            Device.SetRenderState(RenderState.AlphaBlendEnable, true);
            Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
            Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);

            Content = new ContentManager(Device);
            spriteBatch = new SpriteBatch(Device, Content);

            Initialized = true;
        }
Ejemplo n.º 17
0
        public ScreenCaptor9(IHostStatistics statistics, IDevice device)
        {
            this.statistics = statistics;
            var resultFormatId = device.Adapter.GetSupportedFormats(FormatSupport.Texture2D).First(x => x.ExplicitFormat == ExplicitFormat.B8G8R8A8_UNORM).ID;
            texturePool = new TexturePool(device, resultFormatId, Usage.Dynamic, BindFlags.ShaderResource, MiscFlags.None);

            direct3D = new Direct3D();
            form = new Form();
            d3dDevice = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.SoftwareVertexProcessing, new PresentParameters
            {
                SwapEffect = SwapEffect.Discard,
                Windowed = true
            });

            d3dSurface1 = Surface.CreateOffscreenPlain(d3dDevice, 4096, 1440, Format.A8R8G8B8, Pool.Scratch);

            stopwatch = new Stopwatch();
        }
Ejemplo n.º 18
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (direct3dInterface != null)
     {
         direct3dInterface.Dispose();
         direct3dInterface = null;
     }
     if (direct3dDevice != null)
     {
         direct3dDevice.Dispose();
         direct3dDevice = null;
     }
     if (vertexBuffer != null)
     {
         vertexBuffer.Dispose();
         vertexBuffer = null;
     }
 }
Ejemplo n.º 19
0
        public FormViewer3D()
            : base("TRRM - 3D Viewer")
        {
            Icon              = TRRM.Properties.Resources.trrm;
            ClientSize        = new System.Drawing.Size(1280, 720);//( 800, 600 );
            AllowUserResizing = false;

            D3D9.Direct3D direct3D = new D3D9.Direct3D();
            DX = new DX(
                direct3D,
                new D3D9.Device(direct3D, 0, D3D9.DeviceType.Hardware, Handle,
                                D3D9.CreateFlags.HardwareVertexProcessing, new D3D9.PresentParameters(ClientSize.Width, ClientSize.Height))
                );

            meshes = new List <Data.Mesh>();

            sprite      = new D3D9.Sprite(DX.Device);
            basicEffect = D3D9.Effect.FromString(DX.Device, Data.Shader.Basic, D3D9.ShaderFlags.None);
            lightEffect = D3D9.Effect.FromString(DX.Device, Data.Shader.TexturePhong, D3D9.ShaderFlags.None);
        }
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a dictionary of Direct3D 9 function names to their in-memory function addresses.
        /// </summary>
        public static Dictionary<Direct3D9DeviceFunctions, IntPtr> GetDirect3D9VirtualTableAddresses()
        {
            var functionAddressDictionary = new Dictionary<Direct3D9DeviceFunctions, IntPtr>();

            using (var direct3D = new Direct3D())
            {
                using (
                    var device = new Device(direct3D, 0, DeviceType.NullReference, IntPtr.Zero, SharpDX.Direct3D9.CreateFlags.HardwareVertexProcessing,
                        new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    var virtualTablePointer = Marshal.ReadIntPtr(device.NativePointer);
                    var numFunctions = Enum.GetNames(typeof(Direct3D9DeviceFunctions)).Length;

                    for (int index = 0; index < numFunctions; index++)
                    {
                        functionAddressDictionary.Add((Direct3D9DeviceFunctions)index,
                                                      Marshal.ReadIntPtr(virtualTablePointer, index * IntPtr.Size));
                    }
                }
            }

            return functionAddressDictionary;
        }
Ejemplo n.º 22
0
        // Object created for specific window
        public VMR9Capture(IntPtr hWnd)
        {
            _windowHandle = hWnd;

            _d3d = new Direct3DEx();
        }
Ejemplo n.º 23
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample");

            // Creates the Device
            var direct3D = new Direct3D();
            var device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            // Creates the VertexBuffer
            var vertices = new VertexBuffer(device, Utilities.SizeOf<Vector4>() * 2 * 36, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            vertices.Lock(0, 0, LockFlags.None).WriteRange(new[]
                                  {
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
                                      new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                            });
            vertices.Unlock();

            // Compiles the effect
            var effect = Effect.FromFile(device, "MiniCube.fx", ShaderFlags.None);

            // Allocate Vertex Elements
            var vertexElems = new[] {
        		new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
        		new VertexElement(0, 16, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
				VertexElement.VertexDeclarationEnd
        	};

            // Creates and sets the Vertex Declaration
            var vertexDecl = new VertexDeclaration(device, vertexElems);
            device.SetStreamSource(0, vertices, 0, Utilities.SizeOf<Vector4>() * 2);
            device.VertexDeclaration = vertexDecl;

            // Get the technique
            var technique = effect.GetTechnique(0);
            var pass = effect.GetPass(technique, 0);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            RenderLoop.Run(form, () =>
            {
                var time = clock.ElapsedMilliseconds / 1000.0f;

                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                effect.Technique = technique;
                effect.Begin();
                effect.BeginPass(0);

                var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                effect.SetValue("worldViewProj", worldViewProj);

                device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);

                effect.EndPass();
                effect.End();

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

            effect.Dispose();
            vertices.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Ejemplo n.º 24
0
 public void InitDX()
 {
     Direct3D = new Direct3D();
     Device = new Device(Direct3D, 0, DeviceType.Hardware, Window.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(Window.ClientSize.Width, Window.ClientSize.Height)
     {
         MultiSampleType = MultisampleType.EightSamples
     });
     Window.Location = new System.Drawing.Point(Screen.PrimaryScreen.Bounds.Width / 2 - Window.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2 - Window.Height / 2);
     ConfigDX();
 }
Ejemplo n.º 25
0
 internal AdapterInformation(Direct3D direct3D, int adapter)
 {
     d3d     = direct3D;
     Adapter = adapter;
     Details = direct3D.GetAdapterIdentifier(adapter);
 }
Ejemplo n.º 26
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");
            // First we need to determine the function address for IDirect3DDevice9
            Device device;
            id3dDeviceFunctionAddresses = new List<IntPtr>();
            //id3dDeviceExFunctionAddresses = new List<IntPtr>();
            this.DebugMessage("Hook: Before device creation");
            using (Direct3D d3d = new Direct3D())
            {
                using (var renderForm = new System.Windows.Forms.Form())
                {
                    using (device = new Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle }))
                    {
                        this.DebugMessage("Hook: Device created");
                        id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D9_DEVICE_METHOD_COUNT));
                    }
                }
            }

            try
            {
                using (Direct3DEx d3dEx = new Direct3DEx())
                {
                    this.DebugMessage("Hook: Direct3DEx...");
                    using (var renderForm = new System.Windows.Forms.Form())
                    {
                        using (var deviceEx = new DeviceEx(d3dEx, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle }, new DisplayModeEx() { Width = 800, Height = 600 }))
                        {
                            this.DebugMessage("Hook: DeviceEx created - PresentEx supported");
                            id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(deviceEx.NativePointer, D3D9_DEVICE_METHOD_COUNT, D3D9Ex_DEVICE_METHOD_COUNT));
                            _supportsDirect3D9Ex = true;
                        }
                    }
                }
            }
            catch (Exception)
            {
                _supportsDirect3D9Ex = false;
            }

            // We want to hook each method of the IDirect3DDevice9 interface that we are interested in

            // 42 - EndScene (we will retrieve the back buffer here)
            Direct3DDevice_EndSceneHook = new Hook<Direct3D9Device_EndSceneDelegate>(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                // (IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x1ce09),
                // A 64-bit app would use 0xff18
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_EndSceneDelegate(EndSceneHook),
                this);

            unsafe
            {
                // If Direct3D9Ex is available - hook the PresentEx
                if (_supportsDirect3D9Ex)
                {
                    Direct3DDeviceEx_PresentExHook = new Hook<Direct3D9DeviceEx_PresentExDelegate>(
                        id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.PresentEx],
                        new Direct3D9DeviceEx_PresentExDelegate(PresentExHook),
                        this);
                }

                // Always hook Present also (device will only call Present or PresentEx not both)
                Direct3DDevice_PresentHook = new Hook<Direct3D9Device_PresentDelegate>(
                    id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Present],
                    new Direct3D9Device_PresentDelegate(PresentHook),
                    this);
            }

            // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well)
            Direct3DDevice_ResetHook = new Hook<Direct3D9Device_ResetDelegate>(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                //(IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x58dda),
                // A 64-bit app would use 0x3b3a0
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_ResetDelegate(ResetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            
            Direct3DDevice_EndSceneHook.Activate();
            Hooks.Add(Direct3DDevice_EndSceneHook);

            Direct3DDevice_PresentHook.Activate();
            Hooks.Add(Direct3DDevice_PresentHook);

            if (_supportsDirect3D9Ex)
            {
                Direct3DDeviceEx_PresentExHook.Activate();
                Hooks.Add(Direct3DDeviceEx_PresentExHook);
            }

            Direct3DDevice_ResetHook.Activate();
            Hooks.Add(Direct3DDevice_ResetHook);

            this.DebugMessage("Hook: End");
        }
Ejemplo n.º 27
0
 public void InitDX()
 {
     Direct3D = new Direct3D();
     Device = new Device(Direct3D, 0, DeviceType.Hardware, Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(ClientSize.Width, ClientSize.Height)
     {
         MultiSampleType = MultisampleType.EightSamples
     });
     ConfigDX();
 }
Ejemplo n.º 28
0
 internal AdapterInformation(Direct3D direct3D, int adapter)
 {
     this.direct3d = direct3D;
     Adapter = adapter;
     Details = direct3D.GetAdapterIdentifier(adapter, 0);
 }
Ejemplo n.º 29
0
 private static void EnablePerfHUD(Direct3D d3d, ref int adapterOrdinal, ref DeviceType deviceType)
 {
     var perfHudAdapter = d3d.Adapters.FirstOrDefault(s => s.Details.DeviceName.Contains("PerfHUD"));
     if (perfHudAdapter != null)
     {
         adapterOrdinal = perfHudAdapter.Adapter;
         deviceType = DeviceType.Reference;
     }
 }
Ejemplo n.º 30
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;
                }
            }
        }
        /// <summary>
        /// Initializes the Direct3D objects and sets the Available flag
        /// </summary>
        private void InitializeDirect3D()
        {
            DirectXStatus = DirectXStatus.Unavailable_Unknown;

            ReleaseDevice();
            ReleaseDirect3D();

            // assume that we can't run at all under terminal services
            //if (GetSystemMetrics(SM_REMOTESESSION) != 0)
            //{
            //    DirectXStatus = DirectXStatus.Unavailable_RemoteSession;
            //    return;
            //}

            //int renderingTier = (RenderCapability.Tier >> 16);
            //if (renderingTier < 2)
            //{
                //DirectXStatus = DirectXStatus.Unavailable_LowTier;
                //return;
            //}

#if USE_XP_MODE
         _direct3D = new Direct3D();
         UseDeviceEx = false;
#else
            try
            {
                direct3DEx = new Direct3DEx();
                UseDeviceEx = true;
            }
            catch
            {
                try
                {
                    direct3D = new Direct3D();
                    UseDeviceEx = false;
                }
                catch (Direct3DX9NotFoundException) 
                {
                    DirectXStatus = DirectXStatus.Unavailable_MissingDirectX;
                    return;
                }
                catch
                {
                    DirectXStatus = DirectXStatus.Unavailable_Unknown;
                    return;
                }
            }
#endif

            bool ok;
            Result result;

            ok = Direct3D.CheckDeviceType(0, DeviceType.Hardware, adapterFormat, backbufferFormat, true, out result);
            if (!ok)
            {
                //const int D3DERR_NOTAVAILABLE = -2005530518;
                //if (result.Code == D3DERR_NOTAVAILABLE)
                //{
                //   ReleaseDirect3D();
                //   Available = Status.Unavailable_NotReady;
                //   return;
                //}
                ReleaseDirect3D();
                return;
            }

            ok = Direct3D.CheckDepthStencilMatch(0, DeviceType.Hardware, adapterFormat, backbufferFormat, depthStencilFormat, out result);
            if (!ok)
            {
                ReleaseDirect3D();
                return;
            }

            Capabilities deviceCaps = Direct3D.GetDeviceCaps(0, DeviceType.Hardware);
            if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
                createFlags |= CreateFlags.HardwareVertexProcessing;
            else
                createFlags |= CreateFlags.SoftwareVertexProcessing;

            DirectXStatus = DirectXStatus.Available;

            return;
        }
        static void Main()
        {
            var worldSize = new Size2(1024, 768);
            var renderSize = new Size2(1920, 1080);
            const bool windowed = true;

            const int numParticles = 1000000;
            const int numEmitters = 5;
            const int budget = numParticles / numEmitters;

            var form = new RenderForm("Mercury Particle Engine - SharpDX.Direct3D9 Sample")
            {
                Size = new System.Drawing.Size(renderSize.Width, renderSize.Height)
            };

            var direct3d = new Direct3D();
            var device = new Device(direct3d, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(renderSize.Width, renderSize.Height) { PresentationInterval = PresentInterval.Immediate, Windowed = windowed });

            var view = new Matrix(
                1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, -1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, -1.0f, 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f);
            var proj = Matrix.OrthoOffCenterLH(worldSize.Width * -0.5f, worldSize.Width * 0.5f, worldSize.Height * 0.5f, worldSize.Height * -0.5f, 0f, 1f);
            var wvp = Matrix.Identity * view * proj;

            var emitters = new Emitter[numEmitters];

            for (int i = 0; i < numEmitters; i++)
            {
                emitters[i] = new Emitter(budget, TimeSpan.FromSeconds(600), Profile.BoxFill(worldSize.Width, worldSize.Height))
                {
                    Parameters = new ReleaseParameters
                    {
                        Colour = new Colour(220f, 0.7f, 0.1f),
                        Opacity = 1f,
                        Quantity = budget,
                        Speed = 0f,
                        Scale = 1f,
                        Rotation = 0f,
                        Mass = new RangeF(8f, 12f)
                    },
                    BlendMode = BlendMode.Add,
                    ReclaimInterval = 600f
                };

                emitters[i].Modifiers.Add(new DragModifier
                {
                    DragCoefficient = .47f,
                    Density         = .15f
                }, 15f);
                emitters[i].Modifiers.Add(new VortexModifier
                {
                    Position = Coordinate.Origin,
                    Mass = 200f,
                    MaxSpeed = 1000f
                }, 30f);
                emitters[i].Modifiers.Add(new VelocityHueModifier
                {
                    StationaryHue = 220f,
                    VelocityHue = 300f,
                    VelocityThreshold = 800f
                }, 15f);
                emitters[i].Modifiers.Add(new ContainerModifier
                        {
                            RestitutionCoefficient = 0.75f,
                            Position = Coordinate.Origin,
                            Width    = worldSize.Width,
                            Height   = worldSize.Height
                        }, 30f);
                emitters[i].Modifiers.Add(new MoveModifier(), 60f);
            };

            var renderer = new PointSpriteRenderer(device, budget)
            {
            //                EnableFastFade = true
            };

            var texture = Texture.FromFile(device, "Pixel.dds");

            var fontDescription = new FontDescription
            {
                Height         = 16,
                FaceName       = "Consolas",
                PitchAndFamily = FontPitchAndFamily.Mono,
                Quality        = FontQuality.Draft
            };

            var font = new Font(device, fontDescription);

            var totalTimer = Stopwatch.StartNew();
            var updateTimer = new Stopwatch();
            var renderTimer = new Stopwatch();

            var totalTime = 0f;

            foreach (var emitter in emitters)
            {
                emitter.Trigger(Coordinate.Origin);
            }

            float updateTime = 0f;

            RenderLoop.Run(form, () =>
                {
                    // ReSharper disable AccessToDisposedClosure
                    var frameTime = ((float)totalTimer.Elapsed.TotalSeconds) - totalTime;
                    totalTime = (float)totalTimer.Elapsed.TotalSeconds;

                    var mousePosition = form.PointToClient(RenderForm.MousePosition);

                    Task.WaitAll(
                        Task.Factory.StartNew(() =>
                        {
                            var mouseVector = new Vector3(mousePosition.X, mousePosition.Y, 0f);
                            var unprojected = Vector3.Unproject(mouseVector, 0, 0, renderSize.Width, renderSize.Height, 0f, 1f, wvp);

                            Parallel.ForEach(emitters, emitter => ((VortexModifier)emitter.Modifiers.ElementAt(1)).Position = new Coordinate(unprojected.X, unprojected.Y));

                            updateTimer.Restart();
                            Parallel.ForEach(emitters, emitter => emitter.Update(frameTime));
                            updateTimer.Stop();
                            updateTime = (float)updateTimer.Elapsed.TotalSeconds;
                            _updateTimes.Add(updateTime);
                        }),
                        Task.Factory.StartNew(() =>
                        {
                            device.Clear(ClearFlags.Target, Color.Black, 1f, 0);
                            device.BeginScene();

                            renderTimer.Restart();
                            for (int i = 0; i < numEmitters; i++)
                            {
                                renderer.Render(emitters[i], wvp, texture);
                            }
                            renderTimer.Stop();
                            var renderTime = (float)renderTimer.Elapsed.TotalSeconds;

                            var totalUpdateTime = 0f;
            //	                        foreach (var time in _updateTimes)
            //	                        {
            //		                        totalUpdateTime += time;
            //	                        }
            //	                        totalUpdateTime /= _updateTimes.Count;
            //
            //							if(_updateTimes.Count > 100)
            //								_updateTimes.RemoveAt(0);

                            font.DrawText(null, String.Format("Time:        {0}", totalTimer.Elapsed), 0, 0, Color.White);
                            font.DrawText(null, String.Format("Particles:   {0:n0}", emitters[0].ActiveParticles * numEmitters), 0, 16, Color.White);
                            font.DrawText(null, String.Format("Update:      {0:n4} ({1,8:P2})", updateTime, updateTime / 0.01666666f), 0, 32, Color.White);
                            font.DrawText(null, String.Format("Render:      {0:n4} ({1,8:P2})", renderTime, renderTime / 0.01666666f), 0, 48, Color.White);

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

                    if (Keyboard.IsKeyDown(Key.Escape))
                        Environment.Exit(0);
            // ReSharper restore AccessToDisposedClosure
                });

            form.Dispose();
            font.Dispose();
            device.Dispose();
            direct3d.Dispose();
        }
Ejemplo n.º 33
0
        /// <summary>Occurs when the form is disposing.</summary>
        /// <param name="disposing">Whether Dispose was invoked by managed code.</param>
        private void FormDisposing(bool disposing)
        {
            for(int i = 0; i < _dx9Resources.Count; i++)
            {
                try { _dx9Resources[i].Dispose(); }
                catch { }
            }
            _dx9Resources.Clear();

            for(int i = 0; i < _disposableResources.Count; i++)
            {
                try { _disposableResources[i].Dispose(); }
                catch { }
            }
            _disposableResources.Clear();

            _input = null;
            _direct3D = null;
            _device = null;
        }
Ejemplo n.º 34
0
 public WinformsEye()
 {
     direct3D = new Direct3D();
     adapters = direct3D.Adapters.Select(a => new CAdapter(direct3D, a)).ToArray();
     windows = new List<ControlWindow>();
 }
Ejemplo n.º 35
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);
        }
Ejemplo n.º 36
0
        public override unsafe void Hook()
        {
            this.DebugMessage("Hook: Begin");

            this.DebugMessage("Hook: Before device creation");
            using (var d3d = new Direct3D())
            {
                this.DebugMessage("Hook: Direct3D created");
                using (
                    var device = new Device(
                        d3d,
                        0,
                        DeviceType.NullReference,
                        IntPtr.Zero,
                        CreateFlags.HardwareVertexProcessing,
                        new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    this.id3dDeviceFunctionAddresses.AddRange(this.GetVTblAddresses(device.NativePointer, D3D9_DEVICE_METHOD_COUNT));
                }
            }

            try
            {
                using (var d3dEx = new Direct3DEx())
                {
                    this.DebugMessage("Hook: Try Direct3DEx...");
                    using (
                        var deviceEx = new DeviceEx(
                            d3dEx,
                            0,
                            DeviceType.NullReference,
                            IntPtr.Zero,
                            CreateFlags.HardwareVertexProcessing,
                            new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 },
                            new DisplayModeEx() { Width = 800, Height = 600 }))
                    {
                        this.id3dDeviceFunctionAddresses.AddRange(
                            this.GetVTblAddresses(deviceEx.NativePointer, D3D9_DEVICE_METHOD_COUNT, D3D9Ex_DEVICE_METHOD_COUNT));
                        this.supportsDirect3DEx = true;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            this.DebugMessage("Setting up Direct3D hooks...");
            this.Direct3DDevice_EndSceneHook =
                new HookData<Direct3D9Device_EndSceneDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                    new Direct3D9Device_EndSceneDelegate(this.EndSceneHook),
                    this);

            this.Direct3DDevice_EndSceneHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_EndSceneHook.Hook);

            this.Direct3DDevice_PresentHook =
                new HookData<Direct3D9Device_PresentDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Present],
                    new Direct3D9Device_PresentDelegate(this.PresentHook),
                    this);

            this.Direct3DDevice_ResetHook =
                new HookData<Direct3D9Device_ResetDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                    new Direct3D9Device_ResetDelegate(this.ResetHook),
                    this);

            if (this.supportsDirect3DEx)
            {
                this.DebugMessage("Setting up Direct3DEx hooks...");
                this.Direct3DDeviceEx_PresentExHook =
                    new HookData<Direct3D9DeviceEx_PresentExDelegate>(
                        this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.PresentEx],
                        new Direct3D9DeviceEx_PresentExDelegate(this.PresentExHook),
                        this);

                this.Direct3DDeviceEx_ResetExHook =
                    new HookData<Direct3D9DeviceEx_ResetExDelegate>(
                        this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.ResetEx],
                        new Direct3D9DeviceEx_ResetExDelegate(this.ResetExHook),
                        this);
            }

            this.Direct3DDevice_ResetHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_ResetHook.Hook);

            this.Direct3DDevice_PresentHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_PresentHook.Hook);

            if (this.supportsDirect3DEx)
            {
                this.Direct3DDeviceEx_PresentExHook.ReHook();
                this.Hooks.Add(this.Direct3DDeviceEx_PresentExHook.Hook);

                this.Direct3DDeviceEx_ResetExHook.ReHook();
                this.Hooks.Add(this.Direct3DDeviceEx_ResetExHook.Hook);
            }

            this.DebugMessage("Hook: End");
        }
        private void ReleaseDirect3D()
        {
            if (direct3D != null)
            {
                if (!direct3D.IsDisposed)
                {
                    direct3D.Dispose();
                    direct3D = null;
                }
            }

            if (direct3DEx != null)
            {
                if (!direct3DEx.IsDisposed)
                {
                    direct3DEx.Dispose();
                    direct3DEx = null;
                }
            }
        }