コード例 #1
0
        public override void ShowDialog(object sender, EventArgs e)
        {
            if (d3d == null)
            {
                d3d = new Direct3D();
                var pm = new SlimDX.Direct3D9.PresentParameters();
                pm.Windowed = true;
                device = new Device(d3d, 0, DeviceType.Reference, IntPtr.Zero, CreateFlags.FpuPreserve, pm);
            }

            string[] files;
            string path;
            if (ConvDlg.Show(Name, GetOpenFilter(), out files, out path) == DialogResult.OK)
            {
                ProgressDlg pd = new ProgressDlg(DevStringTable.Instance["GUI:Converting"]);

                pd.MinVal = 0;
                pd.Value = 0;
                pd.MaxVal = files.Length;

                pd.Show();
                for (int i = 0; i < files.Length; i++)
                {
                    string dest = Path.Combine(path, Path.GetFileNameWithoutExtension(files[i]) + ".x");

                    Convert(new DevFileLocation(files[i]), new DevFileLocation(dest));
                    pd.Value = i;
                }
                pd.Close();
                pd.Dispose();
            }
        }
コード例 #2
0
		private void Initialize3D()
		{
			HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "D3", IntPtr.Zero);

			pp.SwapEffect = SwapEffect.Discard;
			pp.DeviceWindowHandle = hwnd.Handle;
			pp.Windowed = true;
			pp.BackBufferWidth = (int)ActualWidth;
			pp.BackBufferHeight = (int)ActualHeight;
			pp.BackBufferFormat = Format.X8R8G8B8;

			try
			{
				var direct3DEx = new Direct3DEx();
				direct3D = direct3DEx;
				device = new DeviceEx(direct3DEx, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp);
			}
			catch
			{
				direct3D = new Direct3D();
				device = new Device(direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp);
			}

			System.Windows.Media.CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
		}
コード例 #3
0
ファイル: DX9Renderer.cs プロジェクト: nickmass/Emu-o-Tron
 public void Create()
 {
     d3d = new Direct3D();
     pps.Windowed = true;
     pps.PresentationInterval = PresentInterval.Immediate;
     Reset();
 }
コード例 #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();
            PresentParameters.BackBufferFormat = Format.X8R8G8B8;
            PresentParameters.BackBufferCount = 1;
            PresentParameters.BackBufferWidth = settings.Width;
            PresentParameters.BackBufferHeight = settings.Height;
            PresentParameters.Multisample = MultisampleType.None;
            PresentParameters.SwapEffect = SwapEffect.Discard;
            PresentParameters.EnableAutoDepthStencil = true;
            PresentParameters.AutoDepthStencilFormat = Format.D24X8;
            PresentParameters.PresentFlags = PresentFlags.DiscardDepthStencil;
            PresentParameters.PresentationInterval = PresentInterval.Default;
            PresentParameters.Windowed = true;
            PresentParameters.DeviceWindowHandle = handle;

            direct3D = new Direct3D();
            int msaaQuality = 0;
            if (direct3D.CheckDeviceMultisampleType(settings.AdapterOrdinal, DeviceType.Hardware, Format.A8R8G8B8, true, MultisampleType.FourSamples, out msaaQuality))
            {
                this.MultisampleType = SlimDX.Direct3D9.MultisampleType.FourSamples;
                this.MultisampleQuality = msaaQuality - 1;
                PresentParameters.Multisample = MultisampleType.FourSamples;
                PresentParameters.MultisampleQuality = msaaQuality - 1;
            }

            Device = new Device(direct3D, settings.AdapterOrdinal, DeviceType.Hardware, handle, settings.CreationFlags, PresentParameters);
        }
コード例 #5
0
ファイル: DXControl.cs プロジェクト: ousttrue/csmeshio
        public DXControl()
        {
            // start timer
            _sw.Start();

            // initialize d3d device
            _direct3d = new Direct3D();
            _presentParam = new PresentParameters()
            {
                BackBufferWidth = ClientSize.Width,
                BackBufferHeight = ClientSize.Height,
                Windowed = true,
                BackBufferFormat = Format.X8R8G8B8,
                BackBufferCount = 1,
                SwapEffect = SwapEffect.Discard,
                EnableAutoDepthStencil = true,
                AutoDepthStencilFormat = Format.D24S8,
            };
            _device = new Device(_direct3d, 0,
                    DeviceType.Hardware, Handle,
                    CreateFlags.HardwareVertexProcessing, _presentParam);

            // event handlers
            Resize += OnResize;
        }
コード例 #6
0
        internal DeviceContext9(Form form, DeviceSettings9 settings)
        {
            if (form.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();
            PresentParameters.BackBufferFormat = Format.X8R8G8B8;
            PresentParameters.BackBufferCount = 1;
            PresentParameters.BackBufferWidth = form.ClientSize.Width;
            PresentParameters.BackBufferHeight = form.ClientSize.Height;
            PresentParameters.Multisample = settings.MultisampleType;
            PresentParameters.SwapEffect = SwapEffect.Discard;
            PresentParameters.EnableAutoDepthStencil = true;
            PresentParameters.AutoDepthStencilFormat = Format.D24S8;
            PresentParameters.PresentFlags = PresentFlags.DiscardDepthStencil;
            PresentParameters.PresentationInterval = PresentInterval.Immediate;
            PresentParameters.Windowed = settings.Windowed;
            PresentParameters.DeviceWindowHandle = form.Handle;

            direct3D = new Direct3D();
            Device = new Device(direct3D, settings.AdapterOrdinal, DeviceType.Hardware, form.Handle, settings.CreationFlags, PresentParameters);
        }
コード例 #7
0
ファイル: FormVideoSettings.cs プロジェクト: ywjno/mynes-code
        private void LoadSettings()
        {
            //res
            Direct3D d3d = new Direct3D();
            comboBox_fullscreenRes.Items.Clear();
            for (int i = 0; i < d3d.Adapters[0].GetDisplayModes(SlimDX.Direct3D9.Format.X8R8G8B8).Count; i++)
            {
                comboBox_fullscreenRes.Items.Add(d3d.Adapters[0].GetDisplayModes(SlimDX.Direct3D9.Format.X8R8G8B8)[i].Width + " x " +
                    d3d.Adapters[0].GetDisplayModes(SlimDX.Direct3D9.Format.X8R8G8B8)[i].Height + " " +
                    d3d.Adapters[0].GetDisplayModes(SlimDX.Direct3D9.Format.X8R8G8B8)[i].RefreshRate + " Hz");
            }

            checkBox1.Checked = Program.Settings.Video_StretchToMulti;
            comboBox_windowedModeSize.SelectedIndex = Program.Settings.Video_StretchMulti - 1;
            checkBox_fullscreen.Checked = Program.Settings.Video_StartFullscreen;
            comboBox_fullscreenRes.SelectedIndex = Program.Settings.Video_FullscreenRes;
            checkBox_showNot.Checked = Program.Settings.Video_ShowNotifications;
            checkBox_showFPS.Checked = Program.Settings.Video_ShowFPS;
            checkBox_cutLines.Checked = Program.Settings.Video_CutLines;
            checkBox_hardware_vertex_processing.Checked = Program.Settings.Video_HardwareVertexProcessing;
            checkBox_keep_aspect_ratio.Checked = Program.Settings.Video_KeepAspectRatio;
            switch (Program.Settings.Video_Filter)
            {
                case TextureFilter.None: comboBox_filter.SelectedIndex = 0; break;
                case TextureFilter.Point: comboBox_filter.SelectedIndex = 1; break;
                case TextureFilter.Linear: comboBox_filter.SelectedIndex = 2; break;
            }
        }
コード例 #8
0
        public HumanCastleForm()
        {
            ClientSize = new Size(800,600);
            Text = "Human Castle";

            D3D = new Direct3D();
            SetupDevice();
        }
コード例 #9
0
        public static void Init(System.Windows.Forms.Form mainWindow)
        {
            Configuration.AddResultWatch(SlimDX.Direct3D9.ResultCode.DeviceLost, ResultWatchFlags.AlwaysIgnore);
            D3D = new Direct3D();

            System.Windows.Forms.Application.Idle += new EventHandler(Application_Idle);
            System.Windows.Forms.Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            Application.MainWindow = mainWindow;
        }
コード例 #10
0
        static DxScreenCapture()
        {
            var d3d = new Direct3D();
            var adapterInfo = d3d.Adapters.DefaultAdapter;
            PresentParameters parameters = new PresentParameters();
            parameters.Windowed = true;
            parameters.SwapEffect = SwapEffect.Discard;

            d = new Device(d3d, adapterInfo.Adapter, DeviceType.Hardware, IntPtr.Zero, CreateFlags.SoftwareVertexProcessing, parameters);
        }
コード例 #11
0
ファイル: IGL_SlimDX9.cs プロジェクト: cas1993per/bizhawk
        public IGL_SlimDX9()
        {
            if (d3d == null)
            {
                d3d = new Direct3D();
            }

            //make an 'offscreen context' so we can at least do things without having to create a window
            OffscreenNativeWindow = new OpenTK.NativeWindow();
            OffscreenNativeWindow.ClientSize = new sd.Size(8, 8);

            CreateDevice();
        }
コード例 #12
0
        static DxScreenCapture()
        {
            var d3d = new Direct3D();
            var adapterInfo = d3d.Adapters.DefaultAdapter;
            PresentParameters parameters = new PresentParameters();
            parameters.BackBufferCount = 1;
            parameters.BackBufferFormat = Format.A8R8G8B8;
            parameters.BackBufferWidth = Screen.PrimaryScreen.Bounds.Width;
            parameters.BackBufferHeight = Screen.PrimaryScreen.Bounds.Height;
            parameters.Windowed = true;
            parameters.SwapEffect = SwapEffect.Copy;

            d = new Device(d3d, adapterInfo.Adapter, DeviceType.Hardware, IntPtr.Zero, CreateFlags.SoftwareVertexProcessing, parameters);
        }
コード例 #13
0
ファイル: 3D.cs プロジェクト: Subv/Ejercicios
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            d3d = new Direct3D();
            var pp = new PresentParameters();
            pp.SwapEffect = SwapEffect.Discard;
            pp.DeviceWindowHandle = Handle;
            pp.Windowed = true;
            pp.BackBufferWidth = Width;
            pp.BackBufferHeight = Height;
            pp.BackBufferFormat = Format.A8R8G8B8;

            device = new Device(d3d, 0, DeviceType.Hardware, Handle, CreateFlags.HardwareVertexProcessing, pp);
        }
コード例 #14
0
ファイル: D3D9.cs プロジェクト: miceiken/D3DDetour
        public override void Initialize()
        {
            using (var d3d = new Direct3D())
            {
                using (var tmpDevice = new Device(d3d, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    EndScenePointer = Pulse.Magic.GetObjectVtableFunction(tmpDevice.ComPointer, VMT_ENDSCENE);
                    ResetPointer = Pulse.Magic.GetObjectVtableFunction(tmpDevice.ComPointer, VMT_RESET);
                }
            }

            _endSceneDelegate = Pulse.Magic.RegisterDelegate<Direct3D9EndScene>(EndScenePointer);
            _endSceneHook = Pulse.Magic.Detours.CreateAndApply(_endSceneDelegate, new Direct3D9EndScene(Callback), "D9EndScene");
        }
コード例 #15
0
ファイル: DXHookD3D9.cs プロジェクト: spazzarama/Afterglow
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");
            // First we need to determine the function address for IDirect3DDevice9
            Device device;
            List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>();
            this.DebugMessage("Hook: Before device creation");
            using (Direct3D d3d = new Direct3D())
            {
                this.DebugMessage("Hook: Device created");
                using (device = new Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.ComPointer, D3D9_DEVICE_METHOD_COUNT));
                }
            }

            // 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 = LocalHook.Create(
                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);

            // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well)
            Direct3DDevice_ResetHook = LocalHook.Create(
                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.ThreadACL.SetExclusiveACL(new Int32[1]);

            Direct3DDevice_ResetHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            this.DebugMessage("Hook: End");
        }
コード例 #16
0
ファイル: DXMain.cs プロジェクト: mdmallardi/MGE-XE
 static DXMain() {
 	d3d = new Direct3D();
 	format = Format.A8R8G8B8;
 	
     devParams=new PresentParameters();
     devParams.BackBufferCount=1;
     devParams.BackBufferFormat=format;
     devParams.BackBufferWidth=960;
     devParams.BackBufferHeight=540;
     devParams.EnableAutoDepthStencil=false;
     devParams.Multisample=MultisampleType.None;
     devParams.SwapEffect=SwapEffect.Discard;
     devParams.Windowed=true;
     devParams.PresentationInterval=PresentInterval.One;
 }
コード例 #17
0
        static unsafe void Main(string[] args)
        {
            Direct3D direct3D = new Direct3D();
            /*PresentParameters presentP = new PresentParameters();
            presentP.Windowed = true;
            presentP.SwapEffect = SwapEffect.Discard;
            Form form = new Form();
            Device device2 = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.SoftwareVertexProcessing, presentP);*/

            Console.WriteLine("--------------------------");
            //Device device = SlimDX.Direct3D9.Device.FromPointer(intPtr2);

            testDebug();
            MessageBox.Show("D3D9Device ok");
        }
コード例 #18
0
ファイル: DeviceUtil.cs プロジェクト: rookboom/Flow
 /// <summary>
 /// 
 /// </summary>
 /// <param name="cFlags"></param>
 /// <param name="minLevel"></param>
 /// <returns></returns>
 public static SharpDX.Direct3D11.Device Create11(
     Direct3D11.DeviceCreationFlags cFlags = Direct3D11.DeviceCreationFlags.None,
     Direct3D.FeatureLevel minLevel = Direct3D.FeatureLevel.Level_9_1)
 {
     using (var dg = new DisposeGroup())
     {
         var ada = GetBestAdapter(dg);
         if (ada == null)
             return null;
         var level = Direct3D11.Device.GetSupportedFeatureLevel(ada);
         if (level < minLevel)
             return null;
         return new Direct3D11.Device(ada, cFlags, level);
     }
 }
コード例 #19
0
			public void SetUp()
			{
				_d3D = new Direct3D();
				_form = new Form();
				_deviceSettings =
					new DeviceSettings
						{
							PresentParameters = new PresentParameters
								{
									BackBufferWidth = 10,
									BackBufferHeight = 10,
									EnableAutoDepthStencil = false,
									DeviceWindowHandle = _form.Handle,
								}
						};
			}
コード例 #20
0
ファイル: TextureViewer.cs プロジェクト: anirnet/raf-manager
        void TextureViewer_Load(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            pp = new PresentParameters();
            pp.BackBufferCount = 2;
            pp.SwapEffect = SwapEffect.Discard;
            pp.Windowed = true;

            Direct3D d3d = new Direct3D();
            d3d_device = new Device(d3d, 0, DeviceType.Hardware, d3dPanel.Handle, CreateFlags.HardwareVertexProcessing, pp);
            texture = Texture.FromFile(d3d_device, texturePath);

            int texWidth = texture.GetLevelDescription(0).Width;
            int texHeight = texture.GetLevelDescription(0).Height;
            d3dPanel.Top = menuStrip1.Height;
            d3dPanel.Left = 0;
            d3dPanel.ClientSize = new Size(texWidth, texHeight);
            this.ClientSize = new System.Drawing.Size(
                d3dPanel.Width,
                d3dPanel.Height + menuStrip1.Height
            );
            pp.BackBufferWidth = texWidth;
            pp.BackBufferHeight = texHeight;

            d3d_device.Reset(pp);
            sprite = new Sprite(d3d_device);

            while (this.Visible)
            {
                d3d_device.Clear(ClearFlags.ZBuffer | ClearFlags.Target, new Color4(Color.Black), 1.0f, 0);
                d3d_device.BeginScene();
                sprite.Begin(SpriteFlags.AlphaBlend);
                Rectangle rect = new Rectangle()
                {
                    X = 0,
                    Y = 0,
                    Width = texture.GetLevelDescription(0).Width,
                    Height = texture.GetLevelDescription(0).Height
                };
                sprite.Draw(texture, rect, new Color4(Color.White));
                sprite.End();
                d3d_device.EndScene();
                d3d_device.Present();
                Application.DoEvents();
            }
        }
コード例 #21
0
ファイル: SimplestDemo.cs プロジェクト: raiker/BulletSharp
        void InitializeDevice()
        {
            PresentParameters pp = new PresentParameters()
            {
                BackBufferWidth = Form.ClientSize.Width,
                BackBufferHeight = Form.ClientSize.Height,
                DeviceWindowHandle = Form.Handle
            };

            direct3D = new Direct3D();
            try
            {
                Device = new Device(direct3D, 0, DeviceType.Hardware, Form.Handle, CreateFlags.HardwareVertexProcessing, pp);
            }
            catch
            {
                Device = new Device(direct3D, 0, DeviceType.Hardware, Form.Handle, CreateFlags.SoftwareVertexProcessing, pp);
            }
        }
コード例 #22
0
ファイル: DXMain.cs プロジェクト: europop/MGE-XE
        static DXMain()
        {
            d3d = new Direct3D();

            try {
                format = d3d.Adapters[adapter].CurrentDisplayMode.Format;
            } catch {
                format = Format.X8R8G8B8;
            }

            devParams=new PresentParameters();
            devParams.BackBufferCount=1;
            devParams.BackBufferFormat=format;
            devParams.BackBufferHeight=1024;
            devParams.BackBufferWidth=1024;
            devParams.EnableAutoDepthStencil=false;
            devParams.Multisample=MultisampleType.None;
            devParams.SwapEffect=SwapEffect.Discard;
            devParams.Windowed=true;
            devParams.PresentationInterval=PresentInterval.One;
        }
コード例 #23
0
        public DX9Hook(IReloadedHooks _hooks)
        {
            // Obtain the pointer to the IDirect3DDevice9 instance by creating our own blank windows form and creating a
            // IDirect3DDevice9 targeting that form. The returned device should be the same one as used by the program.
            using (var direct3D = new Direct3D())
                using (var renderForm = new Form())
                    using (var device = new Device(direct3D, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, GetParameters(direct3D, renderForm.Handle)))
                    {
                        Direct3D9VTable = _hooks.VirtualFunctionTableFromObject(direct3D.NativePointer, Enum.GetNames(typeof(IDirect3D9)).Length);
                        DeviceVTable    = _hooks.VirtualFunctionTableFromObject(device.NativePointer, Enum.GetNames(typeof(IDirect3DDevice9)).Length);

                        using var texture = new Texture(device, 128, 128, 0, Usage.None, Format.X8R8G8B8, Pool.Default);
                        Texture9VTable    = _hooks.VirtualFunctionTableFromObject(texture.NativePointer, Enum.GetNames(typeof(IDirect3DTexture9)).Length);
                    }

            using (var direct3D = new Direct3DEx())
                using (var renderForm = new Form())
                    using (var device = new DeviceEx(direct3D, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, GetParameters(direct3D, renderForm.Handle)))
                    {
                        DeviceExVTable    = _hooks.VirtualFunctionTableFromObject(direct3D.NativePointer, Enum.GetNames(typeof(IDirect3D9)).Length);
                        Direct3D9ExVTable = _hooks.VirtualFunctionTableFromObject(device.NativePointer, Enum.GetNames(typeof(IDirect3DDevice9)).Length);
                    }
        }
コード例 #24
0
        public Renderer(Control control)
        {
            this.control = control;

            direct = new Direct3D();
            device = new Device(direct, 0, DeviceType.Hardware, control.Handle,
                                CreateFlags.HardwareVertexProcessing /*| CreateFlags.Multithreaded*/,
                                new PresentParameters
            {
                AutoDepthStencilFormat = Format.D24S8,
                BackBufferCount        = 1,
                BackBufferFormat       = Format.A8R8G8B8,
                BackBufferHeight       = control.ClientSize.Height,
                BackBufferWidth        = control.ClientSize.Width,
                DeviceWindowHandle     = control.Handle,
                EnableAutoDepthStencil = true,
                SwapEffect             = SwapEffect.Discard,
                Windowed = true
            });

            //runned = true;
            //task = Task.Run(new Action(Rendering));
        }
コード例 #25
0
ファイル: MobPicker.cs プロジェクト: dethunter12/DevPack
        private void InitializeDevice()
        {
            //you mest do private void example() and with all the code from panel1 (working) and call the example() to start form for example..
            _Direct3D = new Direct3D();
            Direct3D direct3D = _Direct3D;
            int      adapter  = 0;
            int      num1     = 1;
            IntPtr   handle1  = Handle;
            int      num2     = 32;

            PresentParameters[] presentParametersArray = new PresentParameters[1];
            int index = 0;
            PresentParameters presentParameters = new PresentParameters();

            presentParameters.SwapEffect = SwapEffect.Discard;
            IntPtr handle2 = panel3DView.Handle;

            presentParameters.DeviceWindowHandle = handle2;
            int num3 = 1;

            presentParameters.Windowed = num3 != 0;
            int width = panel3DView.Width;

            presentParameters.BackBufferWidth = width;
            int height = panel3DView.Height;

            presentParameters.BackBufferHeight = height;
            int num4 = 21;

            presentParameters.BackBufferFormat = (SlimDX.Direct3D9.Format)num4;
            presentParametersArray[index]      = presentParameters;
            _Device = new Device(direct3D, adapter, (DeviceType)num1, handle1, (CreateFlags)num2, presentParametersArray);
            _Device.SetRenderState <Cull>(RenderState.CullMode, Cull.None);
            _Device.SetRenderState <FillMode>(RenderState.FillMode, FillMode.Solid);
            _Device.SetRenderState(RenderState.Lighting, false);
            CameraPositioning();
        }
コード例 #26
0
 public void Init()
 {
     this.form            = new Form();
     this.form.ClientSize = new Size(640, 480);
     this.pp = new PresentParameters()
     {
         BackBufferFormat       = SlimDX.Direct3D9.Format.X8R8G8B8,
         BackBufferCount        = 1,
         BackBufferWidth        = this.form.ClientSize.Width,
         BackBufferHeight       = this.form.ClientSize.Height,
         Multisample            = MultisampleType.None,
         SwapEffect             = SwapEffect.Discard,
         EnableAutoDepthStencil = true,
         AutoDepthStencilFormat = SlimDX.Direct3D9.Format.D16,
         PresentFlags           = PresentFlags.DiscardDepthStencil,
         PresentationInterval   = PresentInterval.Default,
         Windowed           = true,
         DeviceWindowHandle = this.form.Handle
     };
     this.direct3D = new Direct3D();
     try
     {
         this.device = new Device(this.direct3D, 0, DeviceType.Hardware, this.form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters[1]
         {
             this.pp
         });
     }
     catch (Direct3D9Exception ex)
     {
         int num = (int)MessageBox.Show(ex.Message, "DirectX Initialization failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         this.form.Close();
     }
     this.sprite  = new Sprite(this.device);
     this.texture = Texture.FromFile(this.device, "roboicon.png");
     this.sprite  = new Sprite(this.device);
     this.LoadResource();
 }
コード例 #27
0
        private void CreateDevice(IDXViewForm form)
        {
            Direct3D   direct3D = new Direct3D();
            DeviceType dType;

            CheckDeviceType(direct3D, out dType, out maxSample, out maxQuality);
            tmpSample  = maxSample;
            tmpQuality = maxQuality;
            PresentParameters pp = GetPresentParameters(form.ViewPort);

            direct3D = new Direct3D();
            try
            {
                Device     = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, pp);
                DriveState = "松";
            }
            catch (SlimDXException ex1)
            {
                try
                {
                    Device     = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.SoftwareVertexProcessing, pp);
                    DriveState = "竹\r\n" + ex1;
                }
                catch (SlimDXException ex2)
                {
                    try
                    {
                        Device     = new Device(direct3D, 0, DeviceType.Reference, form.Handle, CreateFlags.SoftwareVertexProcessing, pp);
                        DriveState = "梅\r\n" + ex2;
                    }
                    catch (SlimDXException ex3)
                    {
                        MessageBox.Show(ex3 + "\r\nデバイスの作成に失敗しました。", "DirectX Initialization failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
        }
コード例 #28
0
        public static byte[] GetDdsTextureFromImage(Bitmap bitmap, bool withHeader)
        {
            using (var d3d = new Direct3D()) {
                var pp = new PresentParameters(100, 100);

                pp.DeviceWindowHandle   = IntPtr.Zero;
                pp.Windowed             = true;
                pp.BackBufferCount      = 1;
                pp.BackBufferFormat     = Format.A8R8G8B8;
                pp.SwapEffect           = SwapEffect.Discard;
                pp.PresentationInterval = PresentInterval.Default;

                var hWnd = IntPtr.Zero;

                try {
                    hWnd = CreateWindowEx(0, "STATIC", "dummy", 0, 0, 0, 100, 100, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

                    pp.DeviceWindowHandle = hWnd;

                    var ppRef = new[] { pp };

                    using (var bmp = (Bitmap)bitmap.Clone()) {
                        bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);

                        using (var device = new Device(d3d, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.MixedVertexProcessing, ppRef)) {
                            return(GetDdsData(device, bmp, withHeader));
                        }
                    }
                } finally {
                    if (hWnd != IntPtr.Zero)
                    {
                        DestroyWindow(hWnd);
                    }
                }
            }
        }
コード例 #29
0
        public void Dispose(bool disposing)
        {
            this.window.Children.Remove((FrameworkElement)_layer);

            this._layer.Dispose();
            this._layer = null;

            this.thread.Do((Action)(() =>
            {
                this.renderframe?.Dispose();
                this.opentk?.Dispose();

                ready.Set();

                this.window.SizeChanged -= Ctl_SizeChanged;

                if (this.olddepth != null)
                {
                    this.device.DepthStencilSurface = this.olddepth;
                    this.olddepth?.Dispose();
                    this.olddepth = null;
                }
                this.frame?.Dispose();
                this.Xwt.FreeWindowInfo(this.widget);
                depthsurface?.Dispose(); depthsurface = null;
                depthtexture?.Dispose(); depthtexture = null;
                effect3?.Dispose(); effect3 = null;
                effect2?.Dispose(); effect2 = null;
                presenteffect?.Dispose(); presenteffect = null;
                vertices2?.Dispose(); vertices2 = null;
                indices?.Dispose(); indices = null;
                device?.Dispose(); device = null;
                direct3D?.Dispose(); direct3D = null;
            }));
            this.thread.Dispose();
        }
コード例 #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 ||
#if !XB1
                        (e.ResultCode == ResultCode.InvalidCall && GetForegroundWindow() != Parameters.DeviceWindowHandle))
#else
                        // TODO [vicent]
                        (e.ResultCode == ResultCode.InvalidCall))
#endif
                    {
                        // 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);
                    }
コード例 #31
0
 public void ResetDevice()
 {
     if (_parent != null && _device != null)
     {
         DisposeDeviceResources();
         _parent.DisposeTextures();
         try
         {
             _device.Reset(presentParams);
             isDeviceLost = false;
             InitDeviceResources();
         }
         catch
         {
             _device.Dispose();
             direct3d.Dispose();
             _device  = null;
             direct3d = null;
             Init(_parent);
             isDeviceLost = false;
             _parent.Reload();
         }
     }
 }
コード例 #32
0
        private bool InitializeD3D()
        {
            HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "null", IntPtr.Zero);

            // Create the D3D object.
            d3d = new Direct3D();


            PresentParameters pp = new PresentParameters();

            pp.BackBufferWidth        = 512;
            pp.BackBufferHeight       = 512;
            pp.BackBufferFormat       = Format.Unknown;
            pp.BackBufferCount        = 0;
            pp.Multisample            = MultisampleType.None;
            pp.MultisampleQuality     = 0;
            pp.SwapEffect             = SwapEffect.Discard;
            pp.DeviceWindowHandle     = (IntPtr)0;
            pp.Windowed               = true;
            pp.EnableAutoDepthStencil = false;
            pp.AutoDepthStencilFormat = Format.Unknown;
            pp.PresentationInterval   = PresentInterval.Default;

            bDeviceFound = false;
            CUdevice[] cudaDevices = null;
            for (g_iAdapter = 0; g_iAdapter < d3d.AdapterCount; g_iAdapter++)
            {
                device = new Device(d3d, d3d.Adapters[g_iAdapter].Adapter, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded, pp);
                try
                {
                    cudaDevices  = CudaContext.GetDirectXDevices(device.ComPointer, CUd3dXDeviceList.All, CudaContext.DirectXVersion.D3D9);
                    bDeviceFound = cudaDevices.Length > 0;
                    infoLog.AppendText("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter
                                       + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 and CUDA.\n");
                    break;
                }
                catch (CudaException)
                {
                    //No Cuda device found for this Direct3D9 device
                    infoLog.AppendText("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter
                                       + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 but not CUDA.\n");
                }
            }

            // we check to make sure we have found a cuda-compatible D3D device to work on
            if (!bDeviceFound)
            {
                infoLog.AppendText("No CUDA-compatible Direct3D9 device available");
                if (device != null)
                {
                    device.Dispose();
                }
                return(false);
            }

            ctx             = new CudaContext(cudaDevices[0], device.ComPointer, CUCtxFlags.BlockingSync, CudaContext.DirectXVersion.D3D9);
            deviceName.Text = "Device name: " + ctx.GetDeviceName();

            // Set projection matrix
            SlimDX.Matrix matProj = SlimDX.Matrix.OrthoOffCenterLH(0, 1, 1, 0, 0, 1);
            device.SetTransform(TransformState.Projection, matProj);

            // Turn off D3D lighting, since we are providing our own vertex colors
            device.SetRenderState(RenderState.Lighting, false);

            //Load kernels
            CUmodule module = ctx.LoadModulePTX("kernel.ptx");

            addForces_k       = new CudaKernel("addForces_k", module, ctx);
            advectVelocity_k  = new CudaKernel("advectVelocity_k", module, ctx);
            diffuseProject_k  = new CudaKernel("diffuseProject_k", module, ctx);
            updateVelocity_k  = new CudaKernel("updateVelocity_k", module, ctx);
            advectParticles_k = new CudaKernel("advectParticles_k", module, ctx);

            d3dimage.Lock();
            Surface surf = device.GetBackBuffer(0, 0);

            d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surf.ComPointer);
            d3dimage.Unlock();
            surf.Dispose();

            //Setup the "real" frame rate counter.
            //The cuda counter only measures cuda runtime, not the overhead to actually
            //show the result via DirectX and WPF.
            realLastTick = Environment.TickCount;
            return(true);
        }
コード例 #33
0
ファイル: VMR9Movie.cs プロジェクト: KHCmaster/PPD
 public VMR9Movie(PPDDevice device, Direct3D d3d, string filename) : base(device, filename)
 {
     this.d3d = d3d;
 }
コード例 #34
0
        /// <summary>
        /// Initializes the Device
        /// </summary>
        private void InitializeDevice(int width, int height)
        {
            if (DirectXStatus != DirectXStatus.Available)
            {
                return;
            }

            Debug.Assert(Direct3D != null);

            ReleaseDevice();

            IntPtr windowHandle = (new Form()).Handle;

            //HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, width, height, "SharpDXControl", IntPtr.Zero);

            presentParameters = new PresentParameters();
            if (UseDeviceEx)
            {
                presentParameters.SwapEffect = SwapEffect.Discard;
            }
            else
            {
                presentParameters.SwapEffect = SwapEffect.Copy;
            }

            presentParameters.DeviceWindowHandle     = windowHandle;
            presentParameters.Windowed               = true;
            presentParameters.BackBufferWidth        = Math.Max(width, 1);
            presentParameters.BackBufferHeight       = Math.Max(height, 1);
            presentParameters.BackBufferFormat       = backbufferFormat;
            presentParameters.AutoDepthStencilFormat = depthStencilFormat;
            presentParameters.EnableAutoDepthStencil = true;
            presentParameters.PresentationInterval   = PresentInterval.Immediate;
            presentParameters.MultiSampleType        = MultisampleType.None;
            IsAntialiased = false;
            int qualityLevels;

            if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.EightSamples, out qualityLevels))
            {
                presentParameters.MultiSampleType    = MultisampleType.EightSamples;
                presentParameters.MultiSampleQuality = qualityLevels - 1;
                IsAntialiased = true;
            }
            else if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.FourSamples, out qualityLevels))
            {
                presentParameters.MultiSampleType    = MultisampleType.FourSamples;
                presentParameters.MultiSampleQuality = qualityLevels - 1;
                IsAntialiased = false;
            }


            try
            {
                if (UseDeviceEx)
                {
                    deviceEx = new DeviceEx((Direct3DEx)Direct3D, 0,
                                            DeviceType.Hardware,
                                            windowHandle,
                                            createFlags,
                                            presentParameters);
                }
                else
                {
                    device = new Device(Direct3D, 0,
                                        DeviceType.Hardware,
                                        windowHandle,
                                        createFlags,
                                        presentParameters);
                }
            }
            catch (Exception) //Direct3D9Exception
            {
                DirectXStatus = DirectXStatus.Unavailable_Unknown;
                return;
            }
            return;
        }
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Direct3D obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
コード例 #36
0
        private void ReleaseDirect3D()
        {
            if (direct3D != null)
            {
                if (!direct3D.Disposed)
                {
                    direct3D.Dispose();
                    direct3D = null;
                }
            }

            if (direct3DEx != null)
            {
                if (!direct3DEx.Disposed)
                {
                    direct3DEx.Dispose();
                    direct3DEx = null;
                }
            }
        }
コード例 #37
0
        public void DisposeDeviceResources(int type = 0)
        {
            if (tx != null)
            {
                tx.Dispose();
                tx = null;
            }
            if (tcircle != null)
            {
                tcircle.Dispose();
                tcircle = null;
            }
            if (tecircle != null)
            {
                tecircle.Dispose();
                tecircle = null;
            }
            if (hvcursor != null)
            {
                hvcursor.Dispose();
                hvcursor = null;
            }
            if (vcursor != null)
            {
                vcursor.Dispose();
                vcursor = null;
            }
            if (hcursor != null)
            {
                hcursor.Dispose();
                hcursor = null;
            }

            if (font != null)
            {
                font.Dispose();
                font = null;
            }
            if (fontBold != null)
            {
                fontBold.Dispose();
                fontBold = null;
            }

            if (sprite != null || type == 1)
            {
                sprite.Dispose();
                sprite = null;
            }
            if (sprite2 != null || type == 1)
            {
                sprite2.Dispose();
                sprite2 = null;
            }

            if (_parent != null && type == 1)
            {
                _parent.DisposeTextures();
                _parent = null;
            }
            if (_device != null && type == 1)
            {
                _device.Dispose();
                _device = null;
            }
            if (direct3d != null && type == 1)
            {
                direct3d.Dispose();
                direct3d = null;
            }
        }
コード例 #38
0
ファイル: DxVideo.cs プロジェクト: MutoMagic/xstream
        private void Initialize(SDL_RendererFlags flags)
        {
            _info       = new RendererInfo();
            _info.Flags = SDL_RendererFlags.SDL_RENDERER_ACCELERATED;

            _d3d = new Direct3D();

            _pparams = new PresentParameters();
            _pparams.DeviceWindowHandle = _hwnd;
            _pparams.BackBufferWidth    = _window.ClientSize.Width;
            _pparams.BackBufferHeight   = _window.ClientSize.Height;
            if (Config.Fullscreen)
            {
            }
            else
            {
                _pparams.BackBufferFormat = Format.Unknown;
            }
            _pparams.BackBufferCount = 1;// 后备缓冲区的数量。通常设为“1”,即只有一个后备表面。

            /*
             * 指定系统如何将后台缓冲区的内容复制到前台缓冲区,从而在屏幕上显示。它的值有:
             * D3DSWAPEFFECT_DISCARD: 清除后台缓存的内容。
             * D3DSWAPEEFECT_FLIP: 保留后台缓存的内容,当缓存区>1时。
             * D3DSWAPEFFECT_COPY: 保留后台缓存的内容,缓冲区=1时。
             * 一般情况下使用D3DSWAPEFFECT_DISCARD
             */
            _pparams.SwapEffect = SwapEffect.Discard;

            if (Config.Fullscreen)
            {
                if (Config.Borderless)
                {
                    _pparams.Windowed = true;
                    _pparams.FullScreenRefreshRateInHz = 0;
                }
                else
                {
                    _pparams.Windowed = false;
                    _pparams.FullScreenRefreshRateInHz = 0;
                }
            }
            else
            {
                _pparams.Windowed = true;// 指定窗口模式。True = 窗口模式;False = 全屏模式

                /*
                 * 显示适配器刷新屏幕的速率。该值取决于应用程序运行的模式:
                 * 对于窗口模式,刷新率必须为0。
                 * 对于全屏模式,刷新率是EnumAdapterModes返回的刷新率之一。
                 */
                _pparams.FullScreenRefreshRateInHz = 0;
            }
            if ((flags & SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC) != 0)
            {
                /*
                 * 交换链的后缓冲区可以提供给前缓冲区的最大速率。可以用以下方式:
                 * D3DPRESENT_INTERVAL_DEFAULT: 这几乎等同于D3DPRESENT_INTERVAL_ONE。
                 * D3DPRESENT_INTERVAL_ONE: 垂直同步。当前的操作不会比刷新屏幕更频繁地受到影响。
                 * D3DPRESENT_INTERVAL_IMMEDIATE: 以实时的方式来显示渲染画面。
                 */
                _pparams.PresentationInterval = PresentInterval.One;
            }
            else
            {
                _pparams.PresentationInterval = PresentInterval.Immediate;
            }

            CreateFlags device_flags = CreateFlags.FpuPreserve;// 将Direct3D浮点计算的精度设置为调用线程使用的精度
            //device_flags |= CreateFlags.Multithreaded;// 瓶颈主要在IO上面,且SDL中尚未设置,此处预留以备不时之需
            Capabilities caps = _d3d.GetDeviceCaps(D3DADAPTER_DEFAULT, DeviceType.Hardware);

            if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                device_flags |= CreateFlags.HardwareVertexProcessing;
            }
            else
            {
                device_flags |= CreateFlags.SoftwareVertexProcessing;
            }

            /*
             * @param adapter       表示显示适配器的序号。D3DADAPTER_DEFAULT(0)始终是主要的显示适配器。
             * @param renderWindow  窗体或任何其他Control派生类的句柄。此参数指示要绑定到设备的表面。
             *                      指定的窗口必须是顶级窗口。不支持空值。
             * @param deviceType    定义设备类型。
             *                      D3DDEVTYPE_HAL 硬件栅格化。可以使用软件,硬件或混合的变换和照明进行着色。
             *                      详见:https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3ddevtype
             * @param behaviorFlags 控制设备创建行为的一个或多个标志的组合。
             *                      D3DCREATE_HARDWARE_VERTEXPROCESSING 指定硬件顶点处理。
             *                      D3DCREATE_SOFTWARE_VERTEXPROCESSING 指定软件顶点处理。
             *                      对于Windows 10版本1607及更高版本,不建议使用此设置。
             *                      使用D3DCREATE_HARDWARE_VERTEXPROCESSING。
             *                      [!Note] 除非没有可用的硬件顶点处理,
             *                      否则在Windows 10版本1607(及更高版本)中不建议使用软件顶点处理,
             *                      因为在提高实现安全性的同时,软件顶点处理的效率已大大降低。
             *                      详见:https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dcreate
             *
             * @see https://docs.microsoft.com/en-us/windows/win32/api/d3d9/nf-d3d9-idirect3d9-createdevice
             */
            _d3dDevice = new Device(_d3d
                                    , D3DADAPTER_DEFAULT
                                    , DeviceType.Hardware
                                    , _hwnd
                                    , device_flags
                                    , _pparams);
            _beginScene = true;
            _scaleMode  = (TextureFilter)D3DTEXF_FORCE_DWORD;

            // Get presentation parameters to fill info
            SwapChain chain = _d3dDevice.GetSwapChain(0);

            _pparams = chain.PresentParameters;
            chain.Dispose();// FIXME: IDirect3DSwapChain9::Release?
            if (_pparams.PresentationInterval == PresentInterval.One)
            {
                _info.Flags |= SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC;
            }

            caps = _d3dDevice.Capabilities;
            _info.MaxTextureWidth  = caps.MaxTextureWidth;
            _info.MaxTextureHeight = caps.MaxTextureHeight;
            if (caps.SimultaneousRTCount >= 2)
            {
                _info.Flags |= SDL_RendererFlags.SDL_RENDERER_TARGETTEXTURE;
            }

            // Set up parameters for rendering
            _d3dDevice.VertexShader = null;
            // IDirect3DDevice9::SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)
            _d3dDevice.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse | VertexFormat.Texture1;
            // IDirect3DDevice9::SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE)
            _d3dDevice.SetRenderState(RenderState.ZEnable, ZBufferType.DontUseZBuffer);
            _d3dDevice.SetRenderState(RenderState.CullMode, Cull.None);
            _d3dDevice.SetRenderState(RenderState.Lighting, false);
            // Enable color modulation by diffuse color
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.Modulate);
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Texture);
            _d3dDevice.SetTextureStageState(0, TextureStage.ColorArg2, TextureArgument.Diffuse);
            // Enable alpha modulation by diffuse alpha
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate);
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture);
            _d3dDevice.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse);
            // Disable second texture stage, since we're done
            _d3dDevice.SetTextureStageState(1, TextureStage.ColorOperation, TextureOperation.Disable);
            _d3dDevice.SetTextureStageState(1, TextureStage.AlphaOperation, TextureOperation.Disable);

            // Store the default render target
            _defaultRenderTarget = _d3dDevice.GetRenderTarget(0);
            _currentRenderTarget = null;

            // Set an identity world and view matrix
            RawMatrix matrix;

            matrix.M11 = 1.0f;
            matrix.M12 = 0.0f;
            matrix.M13 = 0.0f;
            matrix.M14 = 0.0f;
            matrix.M21 = 0.0f;
            matrix.M22 = 1.0f;
            matrix.M23 = 0.0f;
            matrix.M24 = 0.0f;
            matrix.M31 = 0.0f;
            matrix.M32 = 0.0f;
            matrix.M33 = 1.0f;
            matrix.M34 = 0.0f;
            matrix.M41 = 0.0f;
            matrix.M42 = 0.0f;
            matrix.M43 = 0.0f;
            matrix.M44 = 1.0f;
            _d3dDevice.SetTransform(TransformState.World, matrix);
            _d3dDevice.SetTransform(TransformState.View, matrix);

            _scale.x = 1.0f;
            _scale.y = 1.0f;

            if (!_window.Visible || _window.WindowState == FormWindowState.Minimized)
            {
                _hidden = true;
            }
            else
            {
                _hidden = false;
            }
        }
コード例 #39
0
        public override unsafe void Hook()
        {
            DebugMessage("Hook: Begin");

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

            try
            {
                using (var d3dEx = new Direct3DEx())
                {
                    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
                    }))
                    {
                        _id3DDeviceFunctionAddresses.AddRange(
                            GetVTblAddresses(deviceEx.NativePointer, D3D9_DEVICE_METHOD_COUNT, D3D9Ex_DEVICE_METHOD_COUNT));
                        _supportsDirect3DEx = true;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

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

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

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

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

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

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

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

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

            if (_supportsDirect3DEx)
            {
                Direct3DDeviceEx_PresentExHook.ReHook();
                Hooks.Add(Direct3DDeviceEx_PresentExHook.Hook);

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

            DebugMessage("Hook: End");
        }
コード例 #40
0
ファイル: MainDetector.cs プロジェクト: softworkz/SharpDX
 public MainDetector(ILogger logger)
 {
     this.logger = logger;
     this.d3d    = new Direct3D();
 }
コード例 #41
0
ファイル: Direct3D9Renderer.cs プロジェクト: shff/gk3tools
        public Direct3D9Renderer(RenderWindow parentWindow, IntPtr windowHandle, int width, int height, bool hosted)
        {
            _parentWindow = parentWindow;

            _pp = new PresentParameters();
            _pp.BackBufferWidth        = width;
            _pp.BackBufferHeight       = height;
            _pp.DeviceWindowHandle     = windowHandle;
            _pp.EnableAutoDepthStencil = true;
            _pp.AutoDepthStencilFormat = Format.D16;
            _pp.Windowed = true;
            if (hosted)
            {
                _pp.SwapEffect      = SwapEffect.Flip;
                _pp.BackBufferCount = 1;
            }
            else
            {
                _pp.SwapEffect      = SwapEffect.Discard;
                _pp.BackBufferCount = 2;
            }

            Direct3D d3d = new Direct3D();

            _device = new Device(d3d, 0, DeviceType.Hardware, windowHandle,
                                 CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.PureDevice, _pp);


            _device.VertexFormat = VertexFormat.None;

            _currentSamplerStates.SamplerChanged += new SamplerStateCollection.SamplerChangedHandler(samplerStateChanged);

            SamplerState.PointWrap = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = TextureFilter.Point, MaxAnisotropy = 4
            });
            SamplerState.PointClamp = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = TextureFilter.Point, MaxAnisotropy = 4
            });
            SamplerState.LinearWrap = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = TextureFilter.Linear, MaxAnisotropy = 4
            });
            SamplerState.LinearClamp = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = TextureFilter.Linear, MaxAnisotropy = 4
            });
            SamplerState.AnisotropicWrap = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = TextureFilter.Anisoptropic, MaxAnisotropy = 4
            });
            SamplerState.AnisotropicClamp = CreateSampler(new SamplerStateDesc()
            {
                AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = TextureFilter.Anisoptropic, MaxAnisotropy = 4
            });

            // set default render states
            _device.SetRenderState(RenderState.CullMode, Cull.None);
            SamplerStates[0] = SamplerState.LinearWrap;
            SamplerStates[1] = SamplerState.LinearClamp;
            BlendState       = BlendState.Opaque;

            // TODO: load this from the caps!
            _maxAnisotropy = 0;
        }
コード例 #42
0
        public override void Hook()
        {
            CurrentProcess = Process.GetProcessById(ProcessId);
            TraceListener listen = new DebugListener(Interface);

            Trace.Listeners.Add(listen);
            Services.Tracker.Configure(Services.CompassSettings).Apply();
            DebugMessage("Settings loaded");


            DebugMessage("Hook: Begin");

            // First we need to determine the function address for IDirect3DDevice9
            id3dDeviceFunctionAddresses = new List <IntPtr>();
            using (var d3d = new Direct3D())
            {
                using (var renderForm = new Form())
                {
                    Device device;
                    using (device = new Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing,
                                               new PresentParameters {
                        BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle
                    }))
                    {
                        id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D9_DEVICE_METHOD_COUNT));
                    }
                }
            }

            try
            {
                using (var d3dEx = new Direct3DEx())
                {
                    using (var renderForm = new 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
                        }))
                        {
                            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],
                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],
                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);

            DebugMessage("Hook: End");
        }
コード例 #43
0
 public Bitmap CaptureScreen(IntPtr hwnd)
 {
     Bitmap result = null;
     List<Bitmap> screens = new List<Bitmap>();
     try {
         using (Direct3D d3 = new Direct3D()) {
             foreach (AdapterInformation adapterInfo in d3.Adapters) {
                 PresentParameters parameters = new PresentParameters();
                 parameters.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;
                 parameters.BackBufferHeight = adapterInfo.CurrentDisplayMode.Height;
                 parameters.BackBufferWidth = adapterInfo.CurrentDisplayMode.Width;
                 parameters.Multisample = SlimDX.Direct3D9.MultisampleType.None;
                 parameters.SwapEffect = SlimDX.Direct3D9.SwapEffect.Discard;
                 parameters.DeviceWindowHandle = hwnd;
                 parameters.PresentationInterval = SlimDX.Direct3D9.PresentInterval.Default;
                 parameters.FullScreenRefreshRateInHertz = 0;
                 using (Device d = new Device(d3, adapterInfo.Adapter, DeviceType.Hardware, hwnd, CreateFlags.HardwareVertexProcessing, parameters)) {
                     using (SlimDX.Direct3D9.Surface surface = SlimDX.Direct3D9.Surface.CreateOffscreenPlain(d, adapterInfo.CurrentDisplayMode.Width, adapterInfo.CurrentDisplayMode.Height, SlimDX.Direct3D9.Format.A8R8G8B8, SlimDX.Direct3D9.Pool.SystemMemory)) {
                         d.GetFrontBufferData(0, surface);
                         screens.Add(new Bitmap(SlimDX.Direct3D9.Surface.ToStream(surface, SlimDX.Direct3D9.ImageFileFormat.Bmp)));
                     }
                 }
             }
         }
     }
     catch (Exception e) {
         result = null;
         this.Log(e.StackTrace + '\n' + e.Message);
     }
     int newWidth = 0;
     int newHeight = 0;
     float xDpi = 0;
     float yDpi = 0;
     foreach (Bitmap screen in screens) {
         newWidth += screen.Width;
         newHeight = newHeight > screen.Height ? newHeight : screen.Height;
         xDpi = screen.HorizontalResolution;
         yDpi = screen.VerticalResolution;
     }
     newHeight += 1;
     result = new Bitmap(newWidth, newHeight);
     result.SetResolution(xDpi, yDpi);
     using (Graphics g = Graphics.FromImage(result)) {
         int drawX = 0;
         foreach(Bitmap screen in screens) {
             g.DrawImage(screen, new Point(drawX, 0));
             drawX += screen.Width;
         }
     }
     foreach (Bitmap screen in screens) {
         screen.Dispose();
     }
     return result;
 }
コード例 #44
0
ファイル: VideoSlimDx.cs プロジェクト: afonsof/nes-hd
        private void InitializeDirect3D()
        {
            try
            {
                if (!_fullScreen)
                {
                    D3D            = new Direct3D();
                    _presentParams = new PresentParameters
                    {
                        BackBufferWidth      = _width,
                        BackBufferHeight     = _height,
                        Windowed             = true,
                        SwapEffect           = SwapEffect.Discard,
                        Multisample          = MultisampleType.None,
                        PresentationInterval = PresentInterval.Immediate
                    };
                    _displayDevice = new Device(D3D, 0, DeviceType.Hardware, _surface.Handle,
                                                CreateFlags.SoftwareVertexProcessing, new[] { _presentParams });
                    _displayRect = new Rectangle(0, 0, _width, _height);
                    _buffSize    = (_width * _height) * 4;
                    _displayData = new byte[_buffSize];
                    CreateDisplayObjects(_displayDevice);
                    _initialized = true;
                    _disposed    = false;
                    Debug.WriteLine(this, "SlimDX video mode (Windowed) Initialized ok.", DebugStatus.Cool);
                }
                else
                {
                    D3D            = new Direct3D();
                    _mode          = FindSupportedMode();
                    _presentParams = new PresentParameters
                    {
                        BackBufferFormat             = _mode.Format,
                        BackBufferCount              = 1,
                        BackBufferWidth              = _mode.Width,
                        BackBufferHeight             = _mode.Height,
                        Windowed                     = false,
                        FullScreenRefreshRateInHertz = _mode.RefreshRate,
                        SwapEffect                   = SwapEffect.Discard,
                        Multisample                  = MultisampleType.None,
                        PresentationInterval         = PresentInterval.Immediate
                    };
                    _displayDevice = new Device(D3D, 0, DeviceType.Hardware, _surface.Parent.Handle,
                                                CreateFlags.SoftwareVertexProcessing, new[] { _presentParams })
                    {
                        ShowCursor = false,
                    };
                    _displayDevice.SetRenderState(RenderState.PointScaleEnable, true);
                    _displayDevice.SetRenderState(RenderState.PointSpriteEnable, true);
                    _displayRect = new Rectangle(0, 0, _width, _height);
                    _position    = new Vector3((_mode.Width - _width) / 2, (_mode.Height - _height) / 2, 0);
                    _buffSize    = (_width * _height) * 4;
                    _displayData = new byte[_buffSize];
                    CreateDisplayObjects(_displayDevice);
                    _initialized = true;
                    _disposed    = false;

                    Debug.WriteLine(this, "SlimDX video mode (Fullscreen) Initialized ok.", DebugStatus.Cool);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(this, "Could not Initialize SlimDX mode because of : \n" + ex.Message, DebugStatus.Error);
                _initialized = false;
            }
        }
コード例 #45
0
        /// <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;
        }
コード例 #46
0
        private void InitializeD3D()
        {
            // Create the D3D object.
            d3d = new Direct3D();

            PresentParameters pp = new PresentParameters();

            pp.BackBufferWidth        = 512;
            pp.BackBufferHeight       = 512;
            pp.BackBufferFormat       = Format.Unknown;
            pp.BackBufferCount        = 0;
            pp.Multisample            = MultisampleType.None;
            pp.MultisampleQuality     = 0;
            pp.SwapEffect             = SwapEffect.Discard;
            pp.DeviceWindowHandle     = panel1.Handle;
            pp.Windowed               = true;
            pp.EnableAutoDepthStencil = false;
            pp.AutoDepthStencilFormat = Format.Unknown;
            pp.PresentationInterval   = PresentInterval.Default;


            bDeviceFound = false;
            CUdevice[] cudaDevices = null;
            for (g_iAdapter = 0; g_iAdapter < d3d.AdapterCount; g_iAdapter++)
            {
                device = new Device(d3d, d3d.Adapters[g_iAdapter].Adapter, DeviceType.Hardware, panel1.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded, pp);
                try
                {
                    cudaDevices  = CudaContext.GetDirectXDevices(device.ComPointer, CUd3dXDeviceList.All, CudaContext.DirectXVersion.D3D9);
                    bDeviceFound = cudaDevices.Length > 0;
                    Console.WriteLine("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter
                                      + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 and CUDA.");
                    break;
                }
                catch (CudaException)
                {
                    //No Cuda device found for this Direct3D9 device
                    Console.WriteLine("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter
                                      + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 but not CUDA.");
                }
            }

            // we check to make sure we have found a cuda-compatible D3D device to work on
            if (!bDeviceFound)
            {
                Console.WriteLine("No CUDA-compatible Direct3D9 device available");
                if (device != null)
                {
                    device.Dispose();
                }
                Close();
                return;
            }

            ctx = new CudaContext(cudaDevices[0], device.ComPointer, CUCtxFlags.BlockingSync, CudaContext.DirectXVersion.D3D9);

            // Set projection matrix
            SlimDX.Matrix matProj = SlimDX.Matrix.OrthoOffCenterLH(0, 1, 1, 0, 0, 1);
            device.SetTransform(TransformState.Projection, matProj);

            // Turn off D3D lighting, since we are providing our own vertex colors
            device.SetRenderState(RenderState.Lighting, false);

            //Load kernels
            CUmodule module = ctx.LoadModulePTX("kernel.ptx");

            addForces_k       = new CudaKernel("addForces_k", module, ctx);
            advectVelocity_k  = new CudaKernel("advectVelocity_k", module, ctx);
            diffuseProject_k  = new CudaKernel("diffuseProject_k", module, ctx);
            updateVelocity_k  = new CudaKernel("updateVelocity_k", module, ctx);
            advectParticles_k = new CudaKernel("advectParticles_k", module, ctx);
        }
コード例 #47
0
        public void ResolutionChanged()
        {
            Direct3D d3d = new Direct3D();
            PresentParameters present_params = new PresentParameters();
            present_params.Windowed = true;
            present_params.SwapEffect = SwapEffect.Discard;

            dxdevice_offsets = new Point[Screen.AllScreens.Length];
            dxdevice_sizes = new Size[Screen.AllScreens.Length];
            dxdevices = new Device[Screen.AllScreens.Length];

            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                dxdevices[i] = new Device(d3d, i, DeviceType.Hardware, IntPtr.Zero, CreateFlags.SoftwareVertexProcessing, present_params);
                dxdevice_offsets[i] = Screen.AllScreens[i].Bounds.Location;
                dxdevice_sizes[i] = Screen.AllScreens[i].Bounds.Size;
            }
        }
コード例 #48
0
ファイル: Visf.cs プロジェクト: weimingtom/OpenKH
        private void p1_Load(object sender, EventArgs e)
        {
            p3D = new Direct3D();
            alDeleter.Add(p3D);
            device = new Device(p3D, 0, DeviceType.Hardware, p1.Handle, CreateFlags.HardwareVertexProcessing, new[]
            {
                PP
            });
            alDeleter.Add(device);
            device.SetRenderState(RenderState.Lighting, false);
            device.SetRenderState(RenderState.ZEnable, true);
            device.SetRenderState(RenderState.AlphaTestEnable, true);
            device.SetRenderState(RenderState.AlphaRef, 2);
            device.SetRenderState(RenderState.AlphaFunc, Compare.GreaterEqual);
            device.SetRenderState(RenderState.AlphaBlendEnable, true);
            device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
            device.SetRenderState(RenderState.SourceBlendAlpha, Blend.SourceAlpha);
            device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
            device.SetRenderState(RenderState.DestinationBlendAlpha, Blend.InverseSourceAlpha);
            device.SetRenderState(RenderState.CullMode, Cull.Counterclockwise);
            device.SetRenderState(RenderState.FogColor, p1.BackColor.ToArgb());
            device.SetRenderState(RenderState.FogStart, 5f);
            device.SetRenderState(RenderState.FogEnd, 30000f);
            device.SetRenderState(RenderState.FogDensity, 0.0001f);
            device.SetRenderState(RenderState.FogVertexMode, FogMode.Exponential);
            p1.MouseWheel += p1_MouseWheel;
            var list = new List <CustomVertex.PositionColoredTextured>();

            foreach (DC current in aldc)
            {
                var toolStripButton = new ToolStripButton("Show " + current.name);
                toolStripButton.DisplayStyle    = ToolStripItemDisplayStyle.Text;
                toolStripButton.CheckOnClick    = true;
                toolStripButton.Tag             = current.dcId;
                toolStripButton.Checked         = true;
                toolStripButton.CheckedChanged += tsiIfRender_CheckedChanged;
                toolStrip1.Items.Insert(toolStrip1.Items.IndexOf(tsbShowColl), toolStripButton);
            }
            alci.Clear();
            altex.Clear();
            var array = new int[4];
            int num   = 0;

            foreach (DC current2 in aldc)
            {
                int      count = altex.Count;
                Bitmap[] pics  = current2.o7.pics;
                for (int i = 0; i < pics.Length; i++)
                {
                    Bitmap bitmap       = pics[i];
                    var    memoryStream = new MemoryStream();
                    bitmap.Save(memoryStream, ImageFormat.Png);
                    memoryStream.Position = 0L;
                    Texture item;
                    altex.Add(item = Texture.FromStream(device, memoryStream));
                    alDeleter.Add(item);
                }
                if (current2.o4Mdlx != null)
                {
                    using (
                        SortedDictionary <int, Parse4Mdlx.Model> .Enumerator enumerator3 =
                            current2.o4Mdlx.dictModel.GetEnumerator())
                    {
                        while (enumerator3.MoveNext())
                        {
                            KeyValuePair <int, Parse4Mdlx.Model> current3 = enumerator3.Current;
                            var cI                 = new CI();
                            int count2             = list.Count;
                            Parse4Mdlx.Model value = current3.Value;
                            list.AddRange(value.alv);
                            var list2 = new List <uint>();
                            for (int j = 0; j < value.alv.Count; j++)
                            {
                                list2.Add((uint)(count2 + j));
                            }
                            cI.ali  = list2.ToArray();
                            cI.texi = count + current3.Key;
                            cI.vifi = 0;
                            alci.Add(cI);
                        }
                        goto IL_75D;
                    }
                }
                goto IL_3C9;
IL_75D:
                alalci.Add(alci.ToArray());
                alci.Clear();
                continue;
IL_3C9:
                if (current2.o4Map != null)
                {
                    for (int k = 0; k < current2.o4Map.alvifpkt.Count; k++)
                    {
                        Vifpli vifpli   = current2.o4Map.alvifpkt[k];
                        byte[] vifpkt   = vifpli.vifpkt;
                        var    vu       = new VU1Mem();
                        var    parseVIF = new ParseVIF1(vu);
                        parseVIF.Parse(new MemoryStream(vifpkt, false), 0);
                        foreach (var current4 in parseVIF.almsmem)
                        {
                            var cI2           = new CI();
                            var memoryStream2 = new MemoryStream(current4, false);
                            var binaryReader  = new BinaryReader(memoryStream2);
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            int num2 = binaryReader.ReadInt32();
                            int num3 = binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            int num4 = binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            binaryReader.ReadInt32();
                            int num5   = binaryReader.ReadInt32();
                            var list3  = new List <uint>();
                            int count3 = list.Count;
                            for (int l = 0; l < num2; l++)
                            {
                                memoryStream2.Position = 16 * (num3 + l);
                                int num6 = binaryReader.ReadInt16();
                                binaryReader.ReadInt16();
                                int num7 = binaryReader.ReadInt16();
                                binaryReader.ReadInt16();
                                int num8 = binaryReader.ReadInt16();
                                binaryReader.ReadInt16();
                                int num9 = binaryReader.ReadInt16();
                                binaryReader.ReadInt16();
                                memoryStream2.Position = 16 * (num5 + num8);
                                Vector3 v;
                                v.X = -binaryReader.ReadSingle();
                                v.Y = binaryReader.ReadSingle();
                                v.Z = binaryReader.ReadSingle();
                                memoryStream2.Position = 16 * (num4 + l);
                                int num10 = (byte)binaryReader.ReadUInt32();
                                int num11 = (byte)binaryReader.ReadUInt32();
                                int num12 = (byte)binaryReader.ReadUInt32();
                                int num13 = (byte)binaryReader.ReadUInt32();
                                if (num4 == 0)
                                {
                                    num10 = 255;
                                    num11 = 255;
                                    num12 = 255;
                                    num13 = 255;
                                }
                                array[num & 3] = count3 + l;
                                num++;
                                if (num9 != 0 && num9 != 16)
                                {
                                    if (num9 == 32)
                                    {
                                        list3.Add(Convert.ToUInt32(array[num - 1 & 3]));
                                        list3.Add(Convert.ToUInt32(array[num - 2 & 3]));
                                        list3.Add(Convert.ToUInt32(array[num - 3 & 3]));
                                    }
                                    else
                                    {
                                        if (num9 == 48)
                                        {
                                            list3.Add(Convert.ToUInt32(array[num - 1 & 3]));
                                            list3.Add(Convert.ToUInt32(array[num - 3 & 3]));
                                            list3.Add(Convert.ToUInt32(array[num - 2 & 3]));
                                        }
                                    }
                                }
                                Color color = Color.FromArgb(lm.al[num13], lm.al[num10], lm.al[num11], lm.al[num12]);
                                var   item2 = new CustomVertex.PositionColoredTextured(v, color.ToArgb(), num6 / 16f / 256f,
                                                                                       num7 / 16f / 256f);
                                list.Add(item2);
                            }
                            cI2.ali  = list3.ToArray();
                            cI2.texi = count + vifpli.texi;
                            cI2.vifi = k;
                            alci.Add(cI2);
                        }
                    }
                }
                goto IL_75D;
            }
            if (alalci.Count != 0)
            {
                alci.Clear();
                alci.AddRange(alalci[0]);
            }
            if (list.Count == 0)
            {
                list.Add(default(CustomVertex.PositionColoredTextured));
            }
            vb = new VertexBuffer(device, (cntVerts = list.Count) * CustomVertex.PositionColoredTextured.Size,
                                  Usage.Points, CustomVertex.PositionColoredTextured.Format, Pool.Managed);
            alDeleter.Add(vb);
            DataStream dataStream = vb.Lock(0, 0, LockFlags.None);

            try
            {
                foreach (CustomVertex.PositionColoredTextured current5 in list)
                {
                    dataStream.Write(current5);
                }
            }
            finally
            {
                vb.Unlock();
            }
            lCntVert.Text = cntVerts.ToString("#,##0");
            int num14 = 0;

            alib.Clear();
            int num15 = 0;

            foreach (var current6 in alalci)
            {
                CI[] array2 = current6;
                for (int i = 0; i < array2.Length; i++)
                {
                    CI cI3 = array2[i];
                    if (cI3.ali.Length != 0)
                    {
                        var indexBuffer = new IndexBuffer(device, 4 * cI3.ali.Length, Usage.None, Pool.Managed, false);
                        num14 += cI3.ali.Length;
                        alDeleter.Add(indexBuffer);
                        DataStream dataStream2 = indexBuffer.Lock(0, 0, LockFlags.None);
                        try
                        {
                            uint[] ali = cI3.ali;
                            for (int m = 0; m < ali.Length; m++)
                            {
                                uint value2 = ali[m];
                                dataStream2.Write(value2);
                            }
                        }
                        finally
                        {
                            indexBuffer.Unlock();
                        }
                        var rIB = new RIB();
                        rIB.ib   = indexBuffer;
                        rIB.cnt  = cI3.ali.Length;
                        rIB.texi = cI3.texi;
                        rIB.vifi = cI3.vifi;
                        rIB.name = aldc[num15].name;
                        rIB.dcId = aldc[num15].dcId;
                        alib.Add(rIB);
                    }
                    else
                    {
                        var rIB2 = new RIB();
                        rIB2.ib   = null;
                        rIB2.cnt  = 0;
                        rIB2.texi = cI3.texi;
                        rIB2.vifi = cI3.vifi;
                        rIB2.name = aldc[num15].name;
                        rIB2.dcId = aldc[num15].dcId;
                        alib.Add(rIB2);
                    }
                }
                num15++;
            }
            lCntTris.Text = (num14 / 3).ToString("#,##0");
            foreach (Co2 current7 in coll.alCo2)
            {
                alpf.Add(putb.Add(current7));
            }
            if (putb.alv.Count != 0)
            {
                pvi = new Putvi(putb, device);
            }
            Console.Write("");
        }
コード例 #49
0
        /// <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;
        }
コード例 #50
0
        static public void Hook06000005(ref Direct3D d3d, ref Device device, ref PresentParameters param, Control control, bool windowed, Size size, int quality)
        {
            fullscreen |= !windowed;
            d3d         = new Direct3D();
            int          adapter     = d3d.Adapters.DefaultAdapter.Adapter;
            Capabilities deviceCaps  = d3d.GetDeviceCaps(adapter, DeviceType.Hardware);
            DeviceType   deviceType  = deviceCaps.DeviceType;
            CreateFlags  createFlags = (deviceCaps.VertexShaderVersion >= new Version(2, 0)) ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing;

            param            = new PresentParameters();
            param.SwapEffect = SwapEffect.Discard;
            DisplayMode currentDisplayMode = d3d.Adapters[adapter].CurrentDisplayMode;

            param.Windowed = (windowed || !d3d.CheckDeviceType(adapter, DeviceType.Hardware, currentDisplayMode.Format, currentDisplayMode.Format, false));
            if (param.Windowed)
            {
                param.DeviceWindowHandle = control.Handle;
                if (!fullscreen)
                {
                    param.BackBufferWidth  = 0;
                    param.BackBufferHeight = 0;
                }
                else
                {
                    param.BackBufferWidth  = size.Width;
                    param.BackBufferHeight = size.Height;
                    control.ClientSize     = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                    control.Location       = new Point(0, 0);
                }
            }
            else
            {
                param.BackBufferFormat = currentDisplayMode.Format;
                param.BackBufferCount  = 1;
                if (size.Width == 0 || size.Height == 0)
                {
                    size = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                }
                param.BackBufferWidth  = size.Width;
                param.BackBufferHeight = size.Height;
                param.PresentFlags     = PresentFlags.LockableBackBuffer;
                control.ClientSize     = new Size(currentDisplayMode.Width, currentDisplayMode.Height);
                control.Location       = new Point(0, 0);
            }
            if (d3d.CheckDeviceFormat(adapter, DeviceType.Hardware, currentDisplayMode.Format, Usage.DepthStencil, ResourceType.Surface, Format.D24S8))
            {
                param.EnableAutoDepthStencil = true;
                param.AutoDepthStencilFormat = Format.D24S8;
            }
            MultisampleType multisampleType = quality <= 1 ? MultisampleType.None : MultisampleType.NonMaskable;

            while (multisampleType > MultisampleType.None)
            {
                int val;
                int val2;
                if (d3d.CheckDeviceMultisampleType(adapter, deviceType, param.BackBufferFormat, param.Windowed, multisampleType, out val) && d3d.CheckDeviceMultisampleType(adapter, deviceType, Format.D24S8, param.Windowed, multisampleType, out val2))
                {
                    param.Multisample = multisampleType;
                    if (multisampleType == MultisampleType.NonMaskable)
                    {
                        param.MultisampleQuality = Math.Min(Math.Min(val, val2) - 1, (int)Math.Log(quality, 2) - 1);
                        break;
                    }
                    break;
                }
                else
                {
                    multisampleType--;
                }
            }
            param.PresentationInterval = PresentInterval.One;
            device = new Device(d3d, adapter, deviceType, control.Handle, createFlags, new PresentParameters[] { param });
        }
コード例 #51
0
ファイル: Program.cs プロジェクト: zyQmma/SharpDX-Samples
        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();
        }
コード例 #52
0
ファイル: Video.cs プロジェクト: hatori/GameBoy-Revolution
        public void reinit_directx()
        {
            if (critical_failure == false)
            {
                if (texture != null)
                {
                    texture.Dispose();
                    texture = null;
                }

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

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

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

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

                Load_Window_Size();

                if (!initialize_directx())
                {
                    MessageBox.Show("problem with directx initialization");
                    fatal_error = true;
                    return;
                }

                try
                {
                    texture = new Texture(device, 256, 256, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
                }
                catch (Direct3D9Exception e)
                {
                    MessageBox.Show("Gameboy Revolution failed to create rendering surface. \nPlease report this error. \n\nDirectX Error:\n" + e.ToString(), "Error!", MessageBoxButtons.OK);
                    fatal_error = true;
                    return;
                }

                setup_screen();
            }
        }
コード例 #53
0
ファイル: DebugForm.cs プロジェクト: Dfinitski/genesisradio
 private void buttonTS1_Click(object sender, EventArgs e)
 {
     try
     {
         Direct3D w = new Direct3D();
         Capabilities q = w.GetDeviceCaps(0, DeviceType.Hardware);
         rtbDebugMsg.AppendText("Vertex Shader ver: \n" + q.VertexShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Type: \n" + q.DeviceType.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps: \n" + q.DeviceCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Device Caps2: \n" + q.DeviceCaps2.ToString() + "\n");
         rtbDebugMsg.AppendText("Pixel Shader: \n" + q.PixelShaderVersion.ToString() + "\n");
         rtbDebugMsg.AppendText("Texture Caps: \n" + q.TextureCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("FVF Caps: \n" + q.FVFCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("Line Caps: \n" + q.LineCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("MaxVertexIndex Caps: \n" + q.MaxVertexIndex.ToString() + "\n");
         rtbDebugMsg.AppendText("PrimitiveMiscCaps: \n" + q.PrimitiveMiscCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("RatserCaps: \n" + q.RasterCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VertexProcessingCaps: \n" + q.VertexProcessingCaps.ToString() + "\n");
         rtbDebugMsg.AppendText("VS20Caps: \n" + q.VS20Caps.ToString() + "\n");
     }
     catch (Exception ex)
     {
         Debug.Write(ex.ToString());
     }
 }
コード例 #54
0
        public Engine(EngineSetup setup = null)
        {
            XmlConfigurator.Configure();

            _loaded = false;
            _setup  = new EngineSetup();
            if (setup != null)
            {
                _setup = setup;
            }
            _gEngine = this;

            var d3d         = new Direct3D();
            var enumeration = new DeviceEnumeration(d3d);

            if (enumeration.ShowDialog() != DialogResult.OK)
            {
                ReleaseCom(d3d);
                return;
            }


            Window = new FpsForm {
                Name            = "WindowClass",
                Text            = _setup.Name,
                FormBorderStyle = enumeration.Windowed ? FormBorderStyle.FixedSingle : FormBorderStyle.None,
                Size            = new Size(800, 600)
            };

            var pp = new PresentParameters {
                BackBufferWidth              = enumeration.SelectedDisplayMode.Width,
                BackBufferHeight             = enumeration.SelectedDisplayMode.Height,
                BackBufferFormat             = enumeration.SelectedDisplayMode.Format,
                BackBufferCount              = _setup.TotalBackBuffers,
                SwapEffect                   = SwapEffect.Discard,
                DeviceWindowHandle           = Window.Handle,
                Windowed                     = enumeration.Windowed,
                EnableAutoDepthStencil       = true,
                AutoDepthStencilFormat       = Format.D24S8,
                FullScreenRefreshRateInHertz = enumeration.SelectedDisplayMode.RefreshRate,
                PresentationInterval         = enumeration.VSync ? PresentInterval.Default :  PresentInterval.Immediate,
                Multisample                  = MultisampleType.None,
                MultisampleQuality           = 0,
                PresentFlags                 = PresentFlags.None
            };

            enumeration.Dispose();

            _device = new Device(d3d, 0, DeviceType.Hardware, Window.Handle, CreateFlags.MixedVertexProcessing, pp);

            ReleaseCom(d3d);

            _device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Anisotropic);
            _device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Anisotropic);
            _device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);

            var proj = Matrix.PerspectiveFovLH(
                (float)(Math.PI / 4),
                (float)pp.BackBufferWidth / pp.BackBufferHeight,
                0.1f / _setup.Scale, 1000.0f / _setup.Scale
                );

            _device.SetTransform(TransformState.Projection, proj);
            _displayMode = new SlimDX.Direct3D9.DisplayMode {
                Width       = pp.BackBufferWidth,
                Height      = pp.BackBufferHeight,
                RefreshRate = pp.FullScreenRefreshRateInHertz,
                Format      = pp.BackBufferFormat
            };
            _currentBackBuffer = 0;

            _sprite = new Sprite(_device);


            Window.Show();
            Window.Activate();
            _states      = new List <State>();
            CurrentState = null;

            ScriptManager = new ResourceManager <Script>();

            Input = new Input(Window);

            if (_setup.StateSetup != null)
            {
                _setup.StateSetup();
            }

            _loaded  = true;
            _running = true;
        }
コード例 #55
0
ファイル: Video.cs プロジェクト: hatori/GameBoy-Revolution
        private bool initialize_directx()
        {
            d3d = new Direct3D();
            if (pp == null)
            {
                pp = new PresentParameters();
                pp.SwapEffect = SwapEffect.Discard;
                pp.Windowed = true;
                pp.PresentFlags = PresentFlags.LockableBackBuffer;
                pp.PresentationInterval = PresentInterval.Immediate;
                pp.BackBufferCount = 1;
                pp.BackBufferHeight = height;
                pp.BackBufferWidth = width;
                pp.BackBufferFormat = Format.A8R8G8B8;
            }

            initialize_directx_window();

            if (screen.IsHandleCreated == true)
            {
                try
                {
                    device = new Device(d3d, 0, DeviceType.Hardware, screen.Handle, CreateFlags.HardwareVertexProcessing, pp);
                    return true;
                }
                catch
                {
                    try
                    {
                        device = new Device(d3d, 0, DeviceType.Hardware, screen.Handle, CreateFlags.SoftwareVertexProcessing, pp);
                    }
                    catch
                    {
                        try
                        {
                            device = new Device(d3d, 0, DeviceType.Reference, screen.Handle, CreateFlags.SoftwareVertexProcessing, pp);
                        }
                        catch (Direct3D9Exception e)
                        {
                            MessageBox.Show(e.ToString(), "Error!", MessageBoxButtons.OK);
                            critical_failure = true;
                            return false;
                        }
                        return true;
                    }
                    return true;
                }
            }
            else
            {
                MessageBox.Show("Directx window could not be drawn", "Error!", MessageBoxButtons.OK);
                return false;
            }
        }
コード例 #56
0
ファイル: StartUpDialog.cs プロジェクト: wirmachenbunt/tooll
        private void StartUpDialog_Load(object sender, EventArgs e)
        {
            var d3d = new Direct3D();

            if (d3d.Adapters.Count == 0)
            {
                return;
            }

            //update the display listview
            var   adapter = d3d.Adapters[0];
            int   currentDisplayModeIndex = 0, selectedDisplayModeIndex = -1;
            int   i   = 0;
            float dpi = this.CreateGraphics().DpiX;

            DisplayModesView.Columns[0].Width = DisplayModesView.Width - (int)(25.0f * (dpi / 96));
            Height += (int)(20 * dpi / 96.0);

            foreach (var dm in adapter.GetDisplayModes(Format.X8R8G8B8))
            {
                var item = new ListViewItem(String.Format("{0} x {1}   {2} Hz",
                                                          dm.Width.ToString().PadLeft(4, 'x').Replace("x", "  "),
                                                          dm.Height.ToString().PadLeft(4, 'x').Replace("x", "  "),
                                                          dm.RefreshRate.ToString().PadLeft(3, 'x').Replace("x", "  ")));
                DisplayModesView.Items.Add(item);
                _displayModesMap.Add(item.Index, dm);
                if (dm.ToString() == adapter.CurrentDisplayMode.ToString())
                {
                    currentDisplayModeIndex = i;
                }
                if (dm.Width == Settings.DisplayMode.Width &&
                    dm.Height == Settings.DisplayMode.Height &&
                    (selectedDisplayModeIndex < 1 ||
                     dm.RefreshRate == Settings.DisplayMode.RefreshRate))
                {
                    selectedDisplayModeIndex = i;
                }
                ++i;
            }
            if (selectedDisplayModeIndex < 0)
            {
                selectedDisplayModeIndex = currentDisplayModeIndex;
            }
            DisplayModesView.Items[selectedDisplayModeIndex].Selected = true;
            DisplayModesView.EnsureVisible(selectedDisplayModeIndex);
            Settings.DisplayMode = _displayModesMap[selectedDisplayModeIndex];

            //update aspect ratio listview
            var itm = new ListViewItem("Auto");

            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 0);
            itm = new ListViewItem("21:9");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 21.0 / 9.0);
            itm = new ListViewItem("16:9");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 16.0 / 9.0);
            itm = new ListViewItem("16:10");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 16.0 / 10.0);
            itm = new ListViewItem("3:2");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 3.0 / 2.0);
            itm = new ListViewItem("4:3");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 4.0 / 3.0);
            itm = new ListViewItem("5:4");
            AspectRatioView.Items.Add(itm);
            _aspectRatioMap.Add(itm.Index, 5.0 / 4.0);

            double minimalAspectDistance = 9999.0;
            int    minimalAspectIndex    = 0;

            i = 0;
            foreach (var el in _aspectRatioMap)
            {
                var currentAspectDistance = Math.Abs(el.Value - Settings.AspectRatio);
                if (currentAspectDistance < minimalAspectDistance)
                {
                    minimalAspectDistance = currentAspectDistance;
                    minimalAspectIndex    = i;
                }
                ++i;
            }
            AspectRatioView.Items[minimalAspectIndex].Selected = true;
            AspectRatioView.EnsureVisible(minimalAspectIndex);

            //update sampling listview
            itm = new ListViewItem("Disabled");
            SamplingView.Items.Add(itm);
            _samplingMap.Add(itm.Index, 0);
            itm = new ListViewItem("  2x");
            SamplingView.Items.Add(itm);
            _samplingMap.Add(itm.Index, 2);
            itm = new ListViewItem("  4x");
            SamplingView.Items.Add(itm);
            _samplingMap.Add(itm.Index, 4);
            itm = new ListViewItem("  8x");
            SamplingView.Items.Add(itm);
            _samplingMap.Add(itm.Index, 8);
            itm = new ListViewItem("16x");
            SamplingView.Items.Add(itm);
            _samplingMap.Add(itm.Index, 16);

            int minimalSamplingDistance = 9999;
            int minimalSamplingIndex    = 0;

            i = 0;
            foreach (var el in _samplingMap)
            {
                var currentSamplingDistance = Math.Abs(el.Value - Settings.Sampling);
                if (currentSamplingDistance < minimalSamplingDistance)
                {
                    minimalSamplingDistance = currentSamplingDistance;
                    minimalSamplingIndex    = i;
                }
                ++i;
            }
            SamplingView.Items[minimalSamplingIndex].Selected = true;
            SamplingView.EnsureVisible(minimalSamplingIndex);

            FullScreenCheckBox.Checked = Settings.FullScreen;
            LoopedCheckBox.Checked     = Settings.Looped;
            VSyncCheckBox.Checked      = Settings.VSyncEnabled;
            PreCacheCheckBox.Checked   = Settings.PreCacheEnabled;
        }
コード例 #57
0
ファイル: Video.cs プロジェクト: hatori/GameBoy-Revolution
        public void uninit_directx()
        {
            if (critical_failure == false)
            {
                if (texture != null)
                {
                    texture.Dispose();
                    texture = null;
                }

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

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

                if (device != null)
                {
                    device.Dispose();
                    device = null;
                }
            }
        }
コード例 #58
0
ファイル: Program.cs プロジェクト: MainMemory/SA2EmeraldCoast
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = @"C:\SONICADVENTUREDX\Projects\ECPort";

            List <BMPInfo> textures  = new List <BMPInfo>(TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH01.PVM"));
            LandTable      landTable = LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 1\LandTable.sa1lvl");

            texmap = new Dictionary <int, int>();
            BMPInfo[] newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH03.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }
            foreach (COL col in LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 3\LandTable.sa1lvl").COL)
            {
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                landTable.COL.Add(col);
            }
            texmap  = new Dictionary <int, int>();
            newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\BEACH02.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }
            foreach (COL col in LandTable.LoadFromFile(@"Levels\Emerald Coast\Act 2\LandTable.sa1lvl").COL)
            {
                col.Bounds.Center.Z  -= 2000;
                col.Model.Position.Z -= 2000;
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                landTable.COL.Add(col);
            }

            texmap  = new Dictionary <int, int>();
            newtexs = TextureArchive.GetTextures(@"C:\SONICADVENTUREDX\system\OBJ_BEACH.PVM");
            for (int i = 0; i < newtexs.Length; i++)
            {
                BMPInfo found = textures.FirstOrDefault(a => a.Name.Equals(newtexs[i].Name));
                if (found == null)
                {
                    texmap[i] = textures.Count;
                    textures.Add(newtexs[i]);
                }
                else
                {
                    texmap[i] = textures.IndexOf(found);
                }
            }

            PAKFile     pak       = new PAKFile();
            List <byte> inf       = new List <byte>();
            string      filenoext = "beach01";
            string      longdir   = "..\\..\\..\\sonic2\\resource\\gd_pc\\prs\\" + filenoext;

            using (System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel())
                using (Direct3D d3d = new Direct3D())
                    using (Device dev = new Device(d3d, 0, DeviceType.Hardware, panel.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(640, 480)))
                    {
                        for (int i = 0; i < textures.Count; i++)
                        {
                            using (Texture tex = textures[i].Image.ToTexture(dev))
                                using (DataStream str = Surface.ToStream(tex.GetSurfaceLevel(0), ImageFileFormat.Dds))
                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        str.CopyTo(ms);
                                        pak.Files.Add(new PAKFile.File(filenoext + '\\' + Path.ChangeExtension(textures[i].Name, ".dds"), longdir + '\\' + Path.ChangeExtension(textures[i].Name, ".dds"), ms.ToArray()));
                                    }
                            int infsz = inf.Count;
                            inf.AddRange(Encoding.ASCII.GetBytes(Path.ChangeExtension(textures[i].Name, null)));
                            inf.AddRange(new byte[0x1C - (inf.Count - infsz)]);
                            inf.AddRange(BitConverter.GetBytes(i + 200));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(textures[i].Image.Width));
                            inf.AddRange(BitConverter.GetBytes(textures[i].Image.Height));
                            inf.AddRange(BitConverter.GetBytes(0));
                            inf.AddRange(BitConverter.GetBytes(0x80000000));
                        }
                    }
            pak.Files.Insert(0, new PAKFile.File(filenoext + '\\' + filenoext + ".inf", longdir + '\\' + filenoext + ".inf", inf.ToArray()));
            pak.Save(@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\gd_PC\PRS\beach01.pak");

            List <COL> newcollist = new List <COL>();
            Dictionary <string, Attach> visitedAttaches = new Dictionary <string, Attach>();

            foreach (COL col in landTable.COL.Where((col) => col.Model != null && col.Model.Attach != null))
            {
                ConvertCOL(newcollist, visitedAttaches, col);
            }
            landTable.COL = newcollist;

            Console.WriteLine("Loading Object Definitions:");
            Console.WriteLine("Parsing...");

            LevelData.ObjDefs = new List <ObjectDefinition>();
            Dictionary <string, ObjectData> objdefini =
                IniSerializer.Deserialize <Dictionary <string, ObjectData> >("objdefs.ini");

            List <ObjectData> objectErrors = new List <ObjectData>();

            ObjectListEntry[] objlstini = ObjectList.Load(@"Levels\Emerald Coast\Object List.ini", false);
            Directory.CreateDirectory("dllcache").Attributes |= FileAttributes.Hidden;

            List <KeyValuePair <string, string> > compileErrors = new List <KeyValuePair <string, string> >();

            for (int ID = 0; ID < objlstini.Length; ID++)
            {
                string codeaddr = objlstini[ID].CodeString;

                if (!objdefini.ContainsKey(codeaddr))
                {
                    codeaddr = "0";
                }

                ObjectData       defgroup = objdefini[codeaddr];
                ObjectDefinition def;

                if (!string.IsNullOrEmpty(defgroup.CodeFile))
                {
                    Console.WriteLine("Compiling: " + defgroup.CodeFile);


                    def = CompileObjectDefinition(defgroup, out bool errorOccured, out string errorText);

                    if (errorOccured)
                    {
                        KeyValuePair <string, string> errorValue = new KeyValuePair <string, string>(
                            defgroup.CodeFile, errorText);

                        compileErrors.Add(errorValue);
                    }
                }
                else
                {
                    def = new DefaultObjectDefinition();
                }

                LevelData.ObjDefs.Add(def);

                // The only reason .Model is checked for null is for objects that don't yet have any
                // models defined for them. It would be annoying seeing that error all the time!
                if (string.IsNullOrEmpty(defgroup.CodeFile) && !string.IsNullOrEmpty(defgroup.Model))
                {
                    Console.WriteLine("Loading: " + defgroup.Model);
                    // Otherwise, if the model file doesn't exist and/or no texture file is defined,
                    // load the "default object" instead ("?").
                    if (!File.Exists(defgroup.Model))
                    {
                        ObjectData error = new ObjectData {
                            Name = defgroup.Name, Model = defgroup.Model, Texture = defgroup.Texture
                        };
                        objectErrors.Add(error);
                        defgroup.Model = null;
                    }
                }

                def.Init(defgroup, objlstini[ID].Name);
                def.SetInternalName(objlstini[ID].Name);
            }

            // Checks if there have been any errors added to the error list and does its thing
            // This thing is a mess. If anyone can think of a cleaner way to do this, be my guest.
            if (objectErrors.Count > 0)
            {
                int           count        = objectErrors.Count;
                List <string> errorStrings = new List <string> {
                    "The following objects failed to load:"
                };

                foreach (ObjectData o in objectErrors)
                {
                    bool texEmpty  = string.IsNullOrEmpty(o.Texture);
                    bool texExists = (!string.IsNullOrEmpty(o.Texture) && LevelData.Textures.ContainsKey(o.Texture));
                    errorStrings.Add("");
                    errorStrings.Add("Object:\t\t" + o.Name);
                    errorStrings.Add("\tModel:");
                    errorStrings.Add("\t\tName:\t" + o.Model);
                    errorStrings.Add("\t\tExists:\t" + File.Exists(o.Model));
                    errorStrings.Add("\tTexture:");
                    errorStrings.Add("\t\tName:\t" + ((texEmpty) ? "(N/A)" : o.Texture));
                    errorStrings.Add("\t\tExists:\t" + texExists);
                }

                // TODO: Proper logging. Who knows where this file may end up
                File.WriteAllLines("SADXLVL2.log", errorStrings.ToArray());
            }

            // Loading SET Layout
            Console.WriteLine("Loading SET items", "Initializing...");

            List <SETItem> setlist = new List <SETItem>();

            SonicRetro.SAModel.SAEditorCommon.UI.EditorItemSelection selection = new SonicRetro.SAModel.SAEditorCommon.UI.EditorItemSelection();
            if (LevelData.ObjDefs.Count > 0)
            {
                string setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0100S.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    setlist = SETItem.Load(setstr, selection);
                }
                setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0102B.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    setlist.AddRange(SETItem.Load(setstr, selection));
                }
                setstr = @"C:\SONICADVENTUREDX\Projects\ECPort\system\SET0101S.BIN";
                if (File.Exists(setstr))
                {
                    Console.WriteLine("SET: " + setstr.Replace(Environment.CurrentDirectory, ""));

                    List <SETItem> newlist = SETItem.Load(setstr, selection);
                    foreach (SETItem item in newlist)
                    {
                        item.Position.Z -= 2000;
                    }
                    setlist.AddRange(newlist);
                }
            }

            MatrixStack         transform = new MatrixStack();
            List <SETItem>      add       = new List <SETItem>();
            List <SETItem>      del       = new List <SETItem>();
            List <PalmtreeData> trees     = new List <PalmtreeData>();

            foreach (SETItem item in setlist)
            {
                switch (item.ID)
                {
                case 0xD:                         // item box
                    item.ID      = 0xA;
                    item.Scale.X = itemboxmap[(int)item.Scale.X];
                    break;

                case 0x15:                         // ring group to rings
                    for (int i = 0; i < Math.Min(item.Scale.X + 1, 8); i++)
                    {
                        if (item.Scale.Z == 1)                                 // circle
                        {
                            double  v4 = i * 360.0;
                            Vector3 v7 = new Vector3(
                                ObjectHelper.NJSin((int)(v4 / item.Scale.X * 65536.0 * 0.002777777777777778)) * item.Scale.Y,
                                0,
                                ObjectHelper.NJCos((int)(v4 / item.Scale.X * 65536.0 * 0.002777777777777778)) * item.Scale.Y);
                            transform.Push();
                            transform.NJTranslate(item.Position);
                            transform.NJRotateObject(item.Rotation);
                            Vector3 pos = Vector3.TransformCoordinate(v7, transform.Top);
                            transform.Pop();
                            add.Add(new SETItem(0, selection)
                            {
                                Position = pos.ToVertex()
                            });
                        }
                        else                                 // line
                        {
                            transform.Push();
                            transform.NJTranslate(item.Position);
                            transform.NJRotateObject(item.Rotation);
                            double v5;
                            if (i % 2 == 1)
                            {
                                v5 = i * item.Scale.Y * -0.5;
                            }
                            else
                            {
                                v5 = Math.Ceiling(i * 0.5) * item.Scale.Y;
                            }
                            Vector3 pos = Vector3.TransformCoordinate(new Vector3(0, 0, (float)v5), transform.Top);
                            transform.Pop();
                            add.Add(new SETItem(0, selection)
                            {
                                Position = pos.ToVertex()
                            });
                        }
                    }
                    del.Add(item);
                    break;

                case 0x1A:                         // tikal -> omochao
                    item.ID          = 0x19;
                    item.Position.Y += 3;
                    break;

                case 0x1D:                         // kiki
                    item.ID       = 0x5B;
                    item.Rotation = new Rotation();
                    item.Scale    = new Vertex();
                    break;

                case 0x1F:                         // sweep ->beetle
                    item.ID       = 0x38;
                    item.Rotation = new Rotation();
                    item.Scale    = new Vertex(1, 0, 0);
                    break;

                case 0x28:                         // launch ramp
                    item.ID       = 6;
                    item.Scale.X /= 2.75f;
                    item.Scale.Z  = 0.799999952316284f;
                    break;

                case 0x4F:                         // updraft
                    item.ID      = 0x35;
                    item.Scale.X = Math.Max(Math.Min(item.Scale.X, 200), 10) / 2;
                    item.Scale.Y = Math.Max(Math.Min(item.Scale.Y, 200), 10) / 2;
                    item.Scale.Z = Math.Max(Math.Min(item.Scale.Z, 200), 10) / 2;
                    break;

                case 0x52:                         // item box air
                    item.ID      = 0xB;
                    item.Scale.X = itemboxmap[(int)item.Scale.X];
                    break;

                // palm trees
                case 32:
                case 33:
                case 34:
                case 35:
                    trees.Add(new PalmtreeData((byte)(item.ID - 32), item.Position, item.Rotation));
                    del.Add(item);
                    break;

                // nonsolid objects
                case 47:
                case 48:
                case 49:
                case 50:
                case 51:
                case 52:
                case 59:
                case 62:
                case 63:
                case 64:
                case 70:
                    ConvertSETItem(newcollist, item, false, setlist.IndexOf(item));
                    del.Add(item);
                    break;

                // solid objects
                case 36:
                case 37:
                case 39:
                case 41:
                case 42:
                case 43:
                case 44:
                case 45:
                case 46:
                case 54:
                case 58:
                case 66:
                case 71:
                case 72:
                case 73:
                case 74:
                    ConvertSETItem(newcollist, item, true, setlist.IndexOf(item));
                    del.Add(item);
                    break;

                case 81:                         // goal
                    item.ID          = 0xE;
                    item.Position.Y += 30;
                    break;

                default:
                    if (idmap.ContainsKey(item.ID))
                    {
                        item.ID = idmap[item.ID];
                    }
                    else
                    {
                        del.Add(item);
                    }
                    break;
                }
            }
            setlist.AddRange(add);
            foreach (SETItem item in del)
            {
                setlist.Remove(item);
            }
            setlist.Add(new SETItem(0x55, selection)
            {
                Position = new Vertex(6158.6f, -88f, 2384.97f), Scale = new Vertex(3, 0, 0)
            });
            {
                COL col = new COL()
                {
                    Model = new ModelFile(@"E:\Bridge Model.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Visible
                };
                col.Model.Position = new Vertex(2803, -1, 365);
                foreach (NJS_MATERIAL mat in ((BasicAttach)col.Model.Attach).Material)
                {
                    mat.TextureID = texmap[mat.TextureID];
                }
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                ConvertCOL(newcollist, new Dictionary <string, Attach>(), col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\Bridge Model COL.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.Position = new Vertex(2803, -1, 365);
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment0.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment1.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment2.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
                col = new COL()
                {
                    Model = new ModelFile(@"E:\BridgeSegment3.sa1mdl").Model, SurfaceFlags = SurfaceFlags.Solid
                };
                col.Model.ProcessVertexData();
                col.CalculateBounds();
                newcollist.Add(col);
            }
            landTable.SaveToFile(@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\LandTable.sa2lvl", LandTableFormat.SA2);
            ByteConverter.BigEndian = true;
            SETItem.Save(setlist, @"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\gd_PC\set0013_s.bin");
            for (int i = 0; i < 4; i++)
            {
                ModelFile modelFile = new ModelFile($@"C:\SONICADVENTUREDX\Projects\Test\Objects\Levels\Emerald Coast\YASI{i}.sa1mdl");
                foreach (BasicAttach attach in modelFile.Model.GetObjects().Where(a => a.Attach != null).Select(a => a.Attach))
                {
                    foreach (NJS_MATERIAL mat in attach.Material)
                    {
                        mat.TextureID = texmap[mat.TextureID];
                    }
                }
                modelFile.SaveToFile($@"C:\Program Files (x86)\Steam\steamapps\common\Sonic Adventure 2\mods\Emerald Coast\YASI{i}.sa1mdl");
            }
            using (StreamWriter sw = File.CreateText(@"E:\Documents\Visual Studio 2017\Projects\LevelTest\LevelTest\pt.c"))
                sw.WriteLine(string.Join(",\r\n", trees));
        }
コード例 #59
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");
        }
コード例 #60
0
 // This starts up Direct3D
 public static void Startup()
 {
     d3d = new Direct3D();
 }