Beispiel #1
0
        /// <summary>
        /// Plugin entry point
        /// </summary>
        public override void Load()
        {
            drawArgs = ParentApplication.WorldWindow.DrawArgs;

            // Find the first space pilot or traveler device
            DeviceList dl = Microsoft.DirectX.DirectInput.Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

            dl.MoveNext();
            while (dl.Current != null)
            {
                if ((((DeviceInstance)dl.Current).ProductName != "SpacePilot") &&
                    (((DeviceInstance)dl.Current).ProductName != "SpaceTraveler USB"))
                {
                    dl.MoveNext();
                }
                else
                {
                    break;
                }
            }
            if (dl.Current == null)
            {
                throw new ApplicationException("No SpacePilot detected.  Please check your connections and verify your device appears in Control panel -> Game Controllers.");
            }
            DeviceInstance di = (DeviceInstance)dl.Current;

            spacePilot = new Microsoft.DirectX.DirectInput.Device(di.InstanceGuid);
            spacePilot.SetDataFormat(DeviceDataFormat.Joystick);
            spacePilot.SetCooperativeLevel(ParentApplication,
                                           CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);


            if (di.ProductName == "SpacePilot")
            {
                m_spacePilot = true;
            }

            foreach (DeviceObjectInstance d in spacePilot.Objects)
            {
                // For axes that are returned, set the DIPROP_RANGE property for the
                // enumerated axis in order to scale min/max values.
                if ((d.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                {
                    // Try to set the AXISRANGE for the axis but this seems ignored by space pilot
                    spacePilot.Properties.SetRange(ParameterHow.ById, d.ObjectId, new InputRange(-AXISRANGE, AXISRANGE));
                    spacePilot.Properties.SetDeadZone(ParameterHow.ById, d.ObjectId, 1000);                     // 10%

                    // change the axis mode to absolute to work more like how its expected
                    spacePilot.Properties.AxisModeAbsolute = false;
                }
            }

            spacePilot.Acquire();

            // Start a new thread to poll the SpacePilot
            // TODO: The Device supports events, use them
            joyThread = new Thread(new ThreadStart(SpacePilotLoop));
            joyThread.IsBackground = true;
            joyThread.Start();
        }
Beispiel #2
0
        private void InitInput()
        {
            //create keyboard device.
            keyboard = new Input.Device(Input.SystemGuid.Keyboard);
            if (keyboard == null)
            {
                MessageBox.Show("No keyboard found.");
            }
            keyboard.SetCooperativeLevel(
                this,
                Input.CooperativeLevelFlags.NonExclusive |
                Input.CooperativeLevelFlags.Background);
            keyboard.Acquire();

            //create mouse device.
            mouse = new Input.Device(Input.SystemGuid.Mouse);
            if (mouse == null)
            {
                MessageBox.Show("No mouse found.");
            }
            mouse.Properties.AxisModeAbsolute = false;
            mouse.SetCooperativeLevel(
                this,
                Input.CooperativeLevelFlags.NonExclusive |
                Input.CooperativeLevelFlags.Background);
            mouse.Acquire();
        }
Beispiel #3
0
        /// <summary>
        /// 指定されたジョイパッドを接続
        /// </summary>
        /// <param name="name"></param>
        internal static bool DI_Connect(System.Windows.Forms.Form self, string name)
        {
            // ジョイパッド一覧を取得
            Device     d       = null;
            DeviceList devList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

            foreach (DeviceInstance dev in devList)
            {
                d = new Microsoft.DirectX.DirectInput.Device(dev.InstanceGuid);
                if (d.DeviceInformation.ProductName == name)
                {
                    d.SetCooperativeLevel(self, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    break;
                }
            }

            if (d == null)
            {
                return(false);
            }

            // 占有権を取る
            d.SetDataFormat(DeviceDataFormat.Joystick);
            d.Acquire();
            DI_joypad = d;

            // デバイス情報を取得する
            DeviceName = d.DeviceInformation.ProductName;
            NumAxis    = d.Caps.NumberAxes;
            NumPovs    = d.Caps.NumberPointOfViews;
            NumBtns    = d.Caps.NumberButtons;

            return(true);
        }
Beispiel #4
0
        private void InitializeAsKeyboard(ScreenAccess ParentForm, InputDeviceAccess.TypeOfDevices NewTypeOfDevice)
        {
            try
            {
                this.device = new DirectInput.Device(DirectInput.SystemGuid.Keyboard);
                this.device.SetCooperativeLevel
                (
                    ParentForm,
                    DirectInput.CooperativeLevelFlags.Background |
                    DirectInput.CooperativeLevelFlags.NonExclusive
                );
                device.Acquire();

                this._TypeOfDevice = NewTypeOfDevice;

                //Determine how many users are suited for this device
                this._DeviceUserMax = 2;

                // Get space in the keytable for the number of device users
                this.KeyTable = new System.Collections.Hashtable[this._DeviceUserMax];

                //record guid as used
                InputDeviceAccess.AssignedGuids.Add(this.device.DeviceInformation.InstanceGuid);
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        //Initializes the input devices used in the game, namely the mouse and the keyboard.
        private void InitializeInputDevices()
        {
            foreach (Microsoft.DirectX.DirectInput.DeviceInstance device in Microsoft.DirectX.DirectInput.Manager.Devices)
            {
                if (device.InstanceName == "Mouse")
                {
                    this.mouse = new Microsoft.DirectX.DirectInput.Device(device.Instance);
                }
                else if (device.InstanceName == "Keyboard")
                {
                    this.keyboard = new Microsoft.DirectX.DirectInput.Device(device.Instance);
                }
            }

            //set the cooperative levels
            this.keyboard.SetCooperativeLevel(this.owner.Handle, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NoWindowsKey);
            this.mouse.SetCooperativeLevel(this.owner.Handle, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Foreground);
            this.keyboard.SetDataFormat(DeviceDataFormat.Keyboard);
            this.mouse.SetDataFormat(DeviceDataFormat.Mouse);

            //acquire the devices
            this.keyboard.Acquire();
            this.mouse.Acquire();

            //poll them to get the current states
            this.mouse.Poll();
            this.keyboard.Poll();
            //save the current states
            this.keyboardState      = this.keyboard.CurrentKeyboardState;
            this.previousMouseState = this.mouse.CurrentMouseState;
        }
 private void InitializeMouse()
 {
     mouse = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);
     mouse.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
     mouse.Properties.AxisModeAbsolute = false;
     mouse.Acquire();
 }
Beispiel #7
0
        public c_input(IntPtr hwnd,bool window)
        {
            keyboard = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);

            mouse = new Device(SystemGuid.Mouse);
            mouse.Properties.AxisModeAbsolute = false;
            if (window)
            {
                mouse.SetCooperativeLevel(hwnd, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
                keyboard.SetCooperativeLevel(hwnd, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            }
            else
            {
                mouse.SetCooperativeLevel(hwnd, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive);
                keyboard.SetCooperativeLevel(hwnd, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Foreground);

            }

            mouse.Acquire();
            keyboard.Acquire();

            this.X = 1024 / 2;
            this.Y = 768 / 2;
        }
        public void RestoreState(Form target)
        {
            keysDev.Dispose();
            mouseDev.Dispose();
            mouseDev = null;
            keysDev  = null;

            try
            {
                //create our mouse device
                mouseDev = new Device(SystemGuid.Mouse);
                mouseDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive);
                mouseDev.Acquire();

                //create our keyboard device
                keysDev = new Device(SystemGuid.Keyboard);
                keysDev.Properties.BufferSize = 0;
                keysDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.NoWindowsKey);
                keysDev.Acquire();
            }
            catch (Exception)
            {
                MessageBox.Show("DirectInput Faild to Start (userinterface.vb). Outerspace will exit");
                target.Dispose();
                Application.Exit();
            }

            Cursor.Hide();
            needrestore = false;
        }
Beispiel #9
0
        public TgcD3dInput(Control guiControl, Control panel3d)
        {
            this.guiControl = guiControl;
            this.panel3d = panel3d;

            //keyboard
            keyboardDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
            keyboardDevice.SetCooperativeLevel(guiControl, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
            keyboardDevice.Acquire();

            //mouse
            mouseDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);
            mouseDevice.SetCooperativeLevel(guiControl, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
            mouseDevice.Acquire();
            mouseIndex = 0;
            enableMouseFiltering = true;
            weightModifier = WEIGHT_MODIFIER;
            mouseX = 0;
            mouseY = 0;

            //Inicializar mouseMovement
            mouseMovement = new Vector2[2];
            for (int i = 0; i < mouseMovement.Length; i++)
            {
                mouseMovement[i] = new Vector2(0.0f, 0.0f);
            }

            //Inicializar historyBuffer
            historyBuffer = new Vector2[HISTORY_BUFFER_SIZE];
            for (int i = 0; i < historyBuffer.Length; i++)
            {
                historyBuffer[i] = new Vector2(0.0f, 0.0f);
            }

            //Inicializar ubicacion del cursor
            Point ceroToScreen = this.panel3d.PointToScreen(ceroPoint);
            Cursor.Position = new Point(ceroToScreen.X + panel3d.Width / 2, ceroToScreen.Y + panel3d.Height / 2);
            mouseInside = checkMouseInsidePanel3d();

            //Inicializar estados de teclas
            int[] keysArray = (int[])Enum.GetValues(typeof(Key));
            int maxKeyValue = keysArray[keysArray.Length - 1];
            previouskeyboardState = new bool[maxKeyValue];
            currentkeyboardState = new bool[maxKeyValue];
            for (int i = 0; i < maxKeyValue; i++)
            {
                previouskeyboardState[i] = false;
                currentkeyboardState[i] = false;
            }

            //Inicializar estados de botones del mouse
            previousMouseButtonsState = new bool[3];
            currentMouseButtonsState = new bool[previousMouseButtonsState.Length];
            for (int i = 0; i < previousMouseButtonsState.Length; i++)
            {
                previousMouseButtonsState[i] = false;
                currentMouseButtonsState[i] = false;
            }
        }
 // set up keyboard
 public void InitKeyboard()
 {
     keyboard = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
     keyboard.SetCooperativeLevel(
         this,
         CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
     keyboard.Acquire();
 }
Beispiel #11
0
 /// <summary>
 /// Disposes of the mouse device.
 /// </summary>
 public void Dispose()
 {
     if (_device != null)
     {
         _device.Dispose();
         _device = null;
     }
 }
Beispiel #12
0
 public D3DState()
 {
     Direct3D.Device    graphics  = null;
     DirectSound.Device sound     = null;
     DirectInput.Device keyboard  = null;
     DirectInput.Device mouse     = null;
     DirectInput.Device gameinput = null;
 }
Beispiel #13
0
        private void Initialize()
        {
            try {
                //Common DirectX setup calls...
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = SwapEffect.Discard;
                presentParams.BackBufferFormat       = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int         adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                device              = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                //Space Donuts setup
                donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile(TileSetFileName), 1024, 1024,
                                                      1, 0, Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked ((int)0xff000000)));

                donutTileSet   = new TileSet(donutTexture, 0, 0, 6, 5, 32, 32);
                pyramidTileSet = new TileSet(donutTexture, 0, 384, 4, 10, 16, 16);
                sphereTileSet  = new TileSet(donutTexture, 0, 512, 2, 20, 8, 8);
                cubeTileSet    = new TileSet(donutTexture, 0, 544, 2, 20, 8, 8);
                shipTileSet    = new TileSet(donutTexture, 0, 576, 4, 10, 16, 16);
                nixiesTileSet  = new TileSet(donutTexture, 0, 832, 1, 14, 8, 8);
                bulletTileSet  = new TileSet(donutTexture, 304, 832, 1, 1, 8, 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                                        DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                soundHandler = new SoundHandler(this);

                sm.OnCollisionDetected += new SpriteManager.HandleCollision(this.CollisionHandler);

                hrt.Start();
            }
            catch (DirectXException e) {
                Console.WriteLine("Exception is " + e.ErrorString);
                // Catch any errors and return a failure
            }
        }
Beispiel #14
0
 protected void FreeDirectInput()
 {
     if (p_DInputDevice != null)
     {
         p_DInputDevice.Unacquire();
         p_DInputDevice.Dispose();
         p_DInputDevice = null;
     }
 }
Beispiel #15
0
 static void FreeDirectInput()
 {
     if (null != mInputDevice)
     {
         mInputDevice.Unacquire();
         mInputDevice.Dispose();
         mInputDevice = null;
     }
 }
Beispiel #16
0
 public static void SetInputTo(Rendering.RenderForm form)
 {
     keyboard = new inp.Device(inp.SystemGuid.Keyboard);
     keyboard.SetCooperativeLevel(form, inp.CooperativeLevelFlags.NonExclusive | inp.CooperativeLevelFlags.Background);
     keyboard.Acquire();
     mouse = new inp.Device(inp.SystemGuid.Mouse);
     mouse.SetCooperativeLevel(form, inp.CooperativeLevelFlags.NonExclusive | inp.CooperativeLevelFlags.Background);
     mouse.Acquire();
 }
        private void InitializeGraphics()
        {
            try {
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed               = true;
                presentParams.SwapEffect             = SwapEffect.Discard;
                presentParams.BackBufferFormat       = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int         adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags          = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;
                }

                // Do we support a pure device?
                if (caps.DeviceCaps.SupportsPureDevice)
                {
                    flags |= CreateFlags.PureDevice;
                }

                device              = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                tileSheet = TextureLoader.FromFile(device, MediaUtilities.FindFile("donuts.bmp"), 1024, 1024,
                                                   1, 0, Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked ((int)0xff000000)));

                tileSet      = new TileSet(tileSheet, 0, 0, 6, 5, 32, 32);
                tilePosition = new Rectangle(tileSet.XOrigin, tileSet.YOrigin, tileSet.ExtentX * 2, tileSet.ExtentY * 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                                        DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                //Set up DirectSound device and buffers
                snd = new DS.Device();
                snd.SetCooperativeLevel(this, DS.CooperativeLevel.Normal);
                bounce = new DS.SecondaryBuffer(MediaUtilities.FindFile("bounce.wav"), snd);

                hrt.Start();
            }
            catch (DirectXException) {
                // Catch any errors and return a failure
            }
        }
Beispiel #18
0
        public void InitializeKeyboard()
        {
            keyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
            keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);


            mkeyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);
            mkeyb.SetCooperativeLevel(this, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);
        }
Beispiel #19
0
 public void InitDevices()
 {
     mouse = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);
     mouse.Properties.AxisModeAbsolute = true;
     //mouse.Properties.
     //mouse.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive);
     mouse.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
     mouse.Acquire();
 }
Beispiel #20
0
        //privateなメソッド=====================
        /// <summary>
        /// デバイスの初期化
        /// </summary>
        static void Initialize()
        {
            //keyMap = PS2KeyMap;

            // DirectInputデバイスのリストを取得
            DInput.DeviceList controllers =
                DInput.Manager.GetDevices(
                    DInput.DeviceClass.GameControl,
                    DInput.EnumDevicesFlags.AllDevices);

            //Joystickのデバイスを作る器
            DInput.Device d;

            //取得したデバイスのリストをforeachして1つづつjoysticksに登録
            foreach (DInput.DeviceInstance i in controllers)
            {
                //デバイスの生成
                d = new DInput.Device(i.InstanceGuid);

                //各種フラグの設定。Backgroundだと第一引数のFormはnullでいい
                d.SetCooperativeLevel(null,
                                      DInput.CooperativeLevelFlags.NonExclusive
                                      | DInput.CooperativeLevelFlags.NoWindowsKey
                                      | DInput.CooperativeLevelFlags.Background
                                      );

                //Joystickタイプのデータフォーマットを設定
                d.SetDataFormat(DInput.DeviceDataFormat.Joystick);

                //アナログスティックなどのAxis要素を持つDeviceObjectInstanceの出力レンジを設定
                foreach (DInput.DeviceObjectInstance oi in d.Objects)
                {
                    if ((oi.ObjectId & (int)DInput.DeviceObjectTypeFlags.Axis) != 0)
                    {
                        d.Properties.SetRange(
                            DInput.ParameterHow.ById,
                            oi.ObjectId,
                            new DInput.InputRange(-1000, 1000));
                    }
                }

                //Axisの絶対位置モードを設定
                d.Properties.AxisModeAbsolute = true;

                //とりあえずデバイスを動かす
                try { d.Acquire(); }
                catch (Microsoft.DirectX.DirectXException) { }

                //作ったJoystickのDeviceをJoystickリストに追加
                joysticks.Add(d);

                //Joystickの状態を保持させる為のjsstatesを用意、とりあえず現在と以前の状態で2つ用意してみる
                //Geek:一個でよくね……?
                jsStates.Add(new DInput.JoystickState());
            }
        }
Beispiel #21
0
        static public void InitKeyBoardCapture()
        {
            FreeDirectInput();
            CooperativeLevelFlags coopFlags;

            coopFlags    = CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive;
            mInputDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
            mInputDevice.SetCooperativeLevel(mWindow, coopFlags);
            mInputDevice.Acquire();
        }
Beispiel #22
0
        /// <summary>
        /// Creates a vanilla Turret that will be at the given location and 
        /// facing the given rotation. The turret is able to turn at the given
        /// speed and is controlled with the given keyboard Device.
        /// </summary>
        /// <param name="location">Location of the TurretHead in game</param>
        /// <param name="rotation">Rotation the TurretHead is facing</param>
        /// <param name="scale">Scale of the TurretHead</param>
        /// <param name="turretRotationSpeed">
        /// Speed the TurretHead can rotate at
        /// </param>
        /// <param name="keyboard">
        /// Keyboard Device used to control the TurretHead
        /// </param>
        public TurretHead(Vector3 location, Vector3 rotation, Vector3 scale, float headRotationSpeed, float barrelRotationSpeed, DI.Device keyboard)
            : base(location, rotation, scale)
        {
            this.headRotationSpeed = headRotationSpeed;
            this.barrelRotationSpeed = barrelRotationSpeed;
            this.keyboard = keyboard;
            this.barrels = new List<TurretBarrel>();

            this.scripts.Add(new TurretHeadRotationScript(this));
        }
Beispiel #23
0
        public RenderCamera(Control control)
        {
            Device = new DirectInput.Device(SystemGuid.Keyboard);
            Device.SetCooperativeLevel(control.FindForm().MdiParent, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

            HorizontalRadians = 0.0f;
            VerticalRadians   = 0.0f;
            Position          = new Vector3(0f, 0f, 0f);
            ComputePosition();
        }
Beispiel #24
0
        private void InitializeAsGamePad(ScreenAccess ParentForm, InputDeviceAccess.TypeOfDevices NewTypeOfDevice)
        {
            //Check to see if this type of device is available and try to get it for this user
            try
            {
                //Grab first attached gamepad that isnt already assigned
                foreach (DirectInput.DeviceInstance CurrDeviceInstance in DirectInput.Manager.GetDevices(DirectInput.DeviceClass.GameControl, DirectInput.EnumDevicesFlags.AttachedOnly))
                {
                    if (InputDeviceAccess.IsFreeDeviceGuid(CurrDeviceInstance.InstanceGuid) == true)
                    {
                        this.device = new DirectInput.Device(CurrDeviceInstance.InstanceGuid);

                        //If this device is dead throw an exception
                        if (this.device == null)
                        {
                            throw new Exception("found a gamepad GUID, but when we tried to make a device from it it was null");
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                //throw an exception if there is no device
                if (this.device == null)
                {
                    throw new Exception("A gamepad was assigned as an input device, but none were found.");
                }

                //Setup device
                this._TypeOfDevice = NewTypeOfDevice;
                this.device.SetDataFormat(DirectInput.DeviceDataFormat.Joystick);
                this.device.SetCooperativeLevel(ParentForm, DirectInput.CooperativeLevelFlags.Background | DirectInput.CooperativeLevelFlags.NonExclusive);
                this.device.Properties.AxisModeAbsolute = true;
                this.device.Acquire();

                //Determine how many users are suited for this device
                this._DeviceUserMax = 1;

                // Get space in the keytable for the number of device users
                this.KeyTable = new System.Collections.Hashtable[this._DeviceUserMax];

                //record guid as used
                InputDeviceAccess.AssignedGuids.Add(this.device.DeviceInformation.InstanceGuid);

                //Get the keys just so PressedKeys wont be null
                this.PollInput();
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        /// <summary>
        /// Initialize the keyboard device
        /// </summary>
        public void InitializeKeyboard()
        {
            // The first line allocates the system's default keyboard to your variable keyb.
            this.keyboardDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);

            // Then you set some flags that adds default keyboard behavior to keyb. For example, if your window loses focus, your keyboard won't be attached to it any longer.
            this.keyboardDevice.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

            // Don't forget to acquire your keyboard and to call this method from your Main method:
            this.keyboardDevice.Acquire();
        }
Beispiel #26
0
 public void Release()
 {
     if (joystick != null)
     {
         joystick.Unacquire();
         joystick.Dispose();
     }
     joystick      = null;
     isInitialized = false;
     // buttonMap.Clear();
 }
Beispiel #27
0
        public static void InitDX()
        {
            PresentParameters present_params = new PresentParameters();
            present_params.Windowed = true;
            present_params.SwapEffect = SwapEffect.Discard;

            dxDevice = new Device(0, DeviceType.Hardware, Program.mainForm, CreateFlags.SoftwareVertexProcessing, present_params);
            Keyboard = new Microsoft.DirectX.DirectInput.Device(DirectInput.SystemGuid.Keyboard);
            Keyboard.Acquire();
            sprite = new Sprite(dxDevice);
        }
Beispiel #28
0
        public void InitDevices()
        {
            mouse = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);

            mouse.Properties.AxisModeAbsolute = true;
            mouse.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
            mouse.Acquire();
            if (mouse == null)
            {
                throw new Exception("No mouse found.");
            }
        }
Beispiel #29
0
        public bool InitJoystick(Form1 zw, int deviceNum)
        {
            //DirectInput dinput = new DirectInput();
            //System.Collections.Generic.IList<DeviceInstance> deviceList = dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly);
            //DirectInput.DeviceList deviceList = DirectInput.Manager.GetDevices(DirectInput.DeviceClass.GameControl, DirectInput.EnumDevicesFlags.AttachedOnly);
            try {
                joystick = new DirectInput.Device(joystickList[deviceNum].InstanceGuid);
                joystick.SetCooperativeLevel(zw, DirectInput.CooperativeLevelFlags.NonExclusive | DirectInput.CooperativeLevelFlags.Background);
                joystick.SetDataFormat(DirectInput.DeviceDataFormat.Joystick);
                name = joystickList[deviceNum].ProductName;
            } catch (Microsoft.DirectX.DirectInput.InputException de) {
                System.Windows.Forms.MessageBox.Show("Couldn't connect to joystick!", "Joystick Problem", System.Windows.Forms.MessageBoxButtons.OK);
                return(false);
            }
            foreach (DirectInput.DeviceObjectInstance deviceObject in joystick.Objects)
            {
                if ((deviceObject.ObjectId & (int)DirectInput.DeviceObjectTypeFlags.Axis) != 0)
                {
                    joystick.Properties.SetRange(DirectInput.ParameterHow.ById,
                                                 deviceObject.ObjectId,
                                                 new DirectInput.InputRange(-1000, 1000));
                }

                //joystick.Properties.SetDeadZone(
                //                       DirectInput.ParameterHow.ById,
                //                       deviceObject.ObjectId,
                //                       2000);
            }
            // acquire the device
            try {
                joystick.Acquire();
            }
            catch (Microsoft.DirectX.DirectInput.InputException de) {
                System.Windows.Forms.MessageBox.Show(de.Message, "Joystick Error", System.Windows.Forms.MessageBoxButtons.OK);
                return(false);
            }

            //Initially no keys are mapped to buttons on the controller.

            /*for (int f = 0; f < joystick.Caps.NumberButtons; f++) {
             *  if (!buttonMap.ContainsKey(f))
             *      buttonMap.Add(f, -1);
             * }*/
            buttonMap = new int[joystick.Caps.NumberButtons];
            for (int f = 0; f < buttonMap.Length; f++)
            {
                buttonMap[f] = -1;
            }
            fireButtonIndex = 0; //Button 0 on the controller is 'fire' by default
            isInitialized   = true;
            return(true);
        }
Beispiel #30
0
        } // onPaint().fim

        private void inicializarTeclado()
        {
            // Cria o dispositivo de gerenciamento do teclado
            teclado = new DirectInput.Device(DirectInput.SystemGuid.Keyboard);

            // Configura nível de cooperação
            teclado.SetCooperativeLevel(this,
                                        DirectInput.CooperativeLevelFlags.Background |
                                        DirectInput.CooperativeLevelFlags.NonExclusive);

            // Adquire o teclado
            teclado.Acquire();
        } // inicializarTeclado().fim
        /// <summary>
        /// Initializes the mouse device.
        /// </summary>
        public MouseDevice(Form form)
        {
            mouseDevice = new DirectInput.Device(SystemGuid.Mouse);
            mouseDevice.SetCooperativeLevel(form, CooperativeLevelFlags.Background |
                CooperativeLevelFlags.NonExclusive);
            mouseDevice.SetDataFormat(DeviceDataFormat.Mouse);

            mouseDevice.Properties.AxisModeAbsolute = false;

            mouseDevice.Acquire();

            Update();
        }
Beispiel #32
0
        /// <summary>
        /// Initializes the keyboard device to poll from.
        /// </summary>
        /// <param name="window">Window to poll keyboard from.</param>
        public void Initialize(Form window)
        {
            Dispose();
            _window = window;
            _device = new Device(SystemGuid.Keyboard);

            if (_device != null)
            {
                _device.SetCooperativeLevel(window.Handle,
                                            CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
                _device.Acquire();
            }
        }
Beispiel #33
0
        /// <summary>
        /// Initializes the mouse device to poll from.
        /// </summary>
        /// <param name="window">Window to poll mouse from.</param>
        public void Initialize(Form window)
        {
            Dispose();
            _window = window;
            _device = new Device(SystemGuid.Mouse);

            if (_device != null)
            {
                _device.Properties.AxisModeAbsolute = false;
                _device.SetCooperativeLevel(window.Handle,
                                            CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
                _device.Acquire();
            }
        }
Beispiel #34
0
        private void Form1_Load(object sender, EventArgs e)
        {
            presentParameters                        = new PresentParameters();
            presentParameters.Windowed               = true;
            presentParameters.SwapEffect             = SwapEffect.Discard;
            presentParameters.EnableAutoDepthStencil = true;
            presentParameters.AutoDepthStencilFormat = DepthFormat.D16;
            direct3dDevice = new Microsoft.DirectX.Direct3D.Device(0,
                                                                   Microsoft.DirectX.Direct3D.DeviceType.Hardware, this,
                                                                   CreateFlags.HardwareVertexProcessing, presentParameters);
            direct3dDevice.Transform.Projection =
                Matrix.PerspectiveFovLH((float)Math.PI / 4, 4 / 3, 1, 100);

            direct3dDevice.Lights[0].Diffuse   = Color.White;
            direct3dDevice.Lights[0].Type      = LightType.Directional;
            direct3dDevice.Lights[0].Direction = new Vector3(0, -1, -2);
            direct3dDevice.Lights[0].Enabled   = true;

            directInputDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Mouse);
            directInputDevice.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive |
                                                  CooperativeLevelFlags.Foreground);

            try
            {
                meshLetters = Mesh.FromFile("letters.x", MeshFlags.Managed, direct3dDevice);
            }
            catch
            {
                MessageBox.Show("Отсуствует файл letters.x", "Ошибка",
                                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

            material                = new Material();
            material.Diffuse        = Color.White;
            direct3dDevice.Material = material;

            ArrayList arrListTextures = new ArrayList();

            for (int i = 0; i < 5; i++)
            {
                arrListTextures.Add(GenerateFractTexture(i));
            }
            textures = (Texture[])arrListTextures.ToArray(typeof(Texture));

            angleX   = angleY = 0;
            distance = 15;
            order    = 0;
            xCoord   = zCoord = 0;
        }
Beispiel #35
0
        } // MostrarTitulo().fim

        private void inicializarJoystick()
        {
            // Verifica os controles de videogames conectados
            DirectInput.DeviceList Dispositivos =
                DirectInput.Manager.GetDevices(DirectInput.DeviceClass.GameControl,
                                               DirectInput.EnumDevicesFlags.AttachedOnly);

            // Repassa a lista de controles e pega o primeiro item
            foreach (DirectInput.DeviceInstance dispositivo in Dispositivos)
            {
                joystick = new DirectInput.Device(dispositivo.InstanceGuid);

                // Quebre o foreach depois de pegar o primeiro item conectado
                break;
            }

            // Se não tiver Joystick vá embora da função...
            if (joystick == null)
            {
                return;
            }

            // Os dados do dispositivo serão tratados como dados de Joystick
            joystick.SetDataFormat(DirectInput.DeviceDataFormat.Joystick);

            // Configura nível de cooperação
            joystick.SetCooperativeLevel(this,
                                         DirectInput.CooperativeLevelFlags.Background |
                                         DirectInput.CooperativeLevelFlags.NonExclusive);

            // Configura eixo
            joystick.Properties.AxisModeAbsolute = true;

            // Configura faixa de valor retornado pelos eixos
            DirectInput.InputRange eixo_faixaValor;
            eixo_faixaValor = new DirectInput.InputRange(-5000, 5000);
            foreach (DirectInput.DeviceObjectInstance item in joystick.Objects)
            {
                int eixo_ok = item.ObjectId & (int)DirectInput.DeviceObjectTypeFlags.Axis;
                if (eixo_ok != 0)
                {
                    // Configura a faixa de valores do eixo encontrado
                    joystick.Properties.SetRange(DirectInput.ParameterHow.ById,
                                                 item.ObjectId, eixo_faixaValor);
                } // endif
            }     // endfor each

            joystick.Acquire();
        } // inicializarJoystick().fim
Beispiel #36
0
        /// <summary>
        /// Creates a single TurretBarrel which will be represented by the
        /// given Model at the given location facing the given rotation. The
        /// TurretBarrel will be controlled by the given keyboard Device.
        /// </summary>
        /// <param name="barrelModel">
        /// Model to represent the TurretBarrel
        /// </param>
        /// <param name="location">Location of the TurretBarrel</param>
        /// <param name="rotation">Rotation the TurretBarrel is facing</param>
        /// <param name="scale">Scale of the TurretBarrel</param>
        /// <param name="keyboard">
        /// Keyboard Device used to control the TurretBarrel
        /// </param>
        public TurretBarrel(Vector3 location, Vector3 rotation, Vector3 scale, Model barrelModel, float maxRotation,
            float minRotation, float shootDelay, float pushSpeed, float pullSpeed, DI.Device keyboard)
            : base(location, rotation, scale)
        {
            this.keyboard = keyboard;
            this.minRotation = minRotation;
            this.maxRotation = maxRotation;
            this.drawLocation = location;
            this.shootDelay = shootDelay;
            this.pushSpeed = pushSpeed;
            this.pullSpeed = pullSpeed;

            this.models.Add(barrelModel);
            this.scripts.Add(new TurretShootScript(this));
        }
Beispiel #37
0
        public xMouse(Control Owner, 
			Microsoft.DirectX.Direct3D.Device device, bool bWindowed)
        {
            m_Owner = Owner;
            d3ddevice = device;
            mouse = new Device(SystemGuid.Mouse);
            mouse.SetDataFormat(DeviceDataFormat.Mouse);
            mouse.SetCooperativeLevel(m_Owner,
                CooperativeLevelFlags.Background |
                CooperativeLevelFlags.NonExclusive);
            mouse.Properties.AxisModeAbsolute = false;
            buttons = new bool[256];
            m_bWindowed = bWindowed;
            m_XPos = 0f;
            m_YPos = 0f;
            m_ObjectSpace = new Vector3(0f, 0f, 0f);
            m_ObjectSpace2 = new Vector3(0f, 0f, 0f);
            m_Clicked = false;
        }
        public SplashButton(System.Windows.Forms.Form frm, 
                            D3D.Device device3D, Point location, Size dimension,
                            string normalFileName, string mouseOverFileName,
                            string mouseDownFileName, string disableFileName)
        {
            device3d = device3D;
            Location = location;
            size = dimension;

            int h = Location.Y + size.Height;
            int w = Location.X + size.Width;
            vertices = new D3D.CustomVertex.TransformedTextured[6];
            vertices[0] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, location.Y, 0f, 1f), 0, 0);
            vertices[1] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0);
            vertices[2] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1);
            vertices[3] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1);
            vertices[4] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0);
            vertices[5] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, h, 0f, 1f), 1, 1);
            normalTexture = D3D.TextureLoader.FromFile(device3d, normalFileName);
            mouseOverTexture = D3D.TextureLoader.FromFile(device3d, mouseOverFileName);
            mouseDownTexture = D3D.TextureLoader.FromFile(device3d, mouseDownFileName);
            disableTexture = D3D.TextureLoader.FromFile(device3d, disableFileName);
            Enable = true;
            //
            // set mouse device
            //
            try
            {
                MouseDevice = new DI.Device(DI.SystemGuid.Mouse);
                MouseDevice.SetDataFormat(DI.DeviceDataFormat.Mouse);
                MouseDevice.Acquire();
            }
            catch (DirectXException ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, ex.Source);
            }
            finally
            {
                frm.MouseMove += new System.Windows.Forms.MouseEventHandler(frm_MouseMove);
            }
        }
		/// <summary>
		/// 初始导演类
		/// </summary>
		/// <returns>是否初始化成功</returns>
		public bool Init()
		{
			try
			{
				//预设参数
				PresentParameters pp = new PresentParameters();
				pp.Windowed = true;
				pp.SwapEffect = SwapEffect.Discard;

				//创建设备
				d3dDevice = new Microsoft.DirectX.Direct3D.Device(
					0,
					Microsoft.DirectX.Direct3D.DeviceType.Hardware,
					this,
					CreateFlags.SoftwareVertexProcessing,
					pp
				);

				//input设备
				kbDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
				kbDevice.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
				kbDevice.Acquire();

				//if (instance != null) return false;
				instance = this;

				//设置每帧时间间隔
				PerFrameTick = 1000.0f / 60;
				
				return true;
			}
			catch (DirectXException e)
			{
				ErrorReport.New(e);
				return false;
			}


		}
Beispiel #40
0
        // ...4-02-06
        public userinterface(Form target)
        {
            mouseypos = 300;
            mousexpos = 400;
            mouseXdelta = 400;
            mouseYdelta = 300;

            try
            {
                targetform = target;
                mouseDev = new Device(SystemGuid.Mouse);
                keysDev = new Device(SystemGuid.Keyboard);
                keysDev.Properties.BufferSize = 0;

                if (OuterSpace.IsWindowMode)
                {
                    mouseDev.SetCooperativeLevel(target, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    keysDev.SetCooperativeLevel(target, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                }
                else
                {
                    mouseDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);
                    keysDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.NoWindowsKey);
                }

                mouseDev.Acquire();
                keysDev.Acquire();
                mouseStateData = mouseDev.CurrentMouseState;
            }
            catch (Exception)
            {
                MessageBox.Show("DirectInput Failed to Start (userinterface.vb). Outerspace will exit");
                targetform.Dispose();
                Application.Exit();
            }

            //text_input = New textInput(target.Handle) ' ...4-02-06
        }
Beispiel #41
0
        public void RestoreState(Form target)
        {
            keysDev.Dispose();
            mouseDev.Dispose();
            mouseDev = null;
            keysDev = null;

            try
            {
                //create our mouse device
                mouseDev = new Device(SystemGuid.Mouse);
                mouseDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive);
                mouseDev.Acquire();

                //create our keyboard device
                keysDev = new Device(SystemGuid.Keyboard);
                keysDev.Properties.BufferSize = 0;
                keysDev.SetCooperativeLevel(target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.NoWindowsKey);
                keysDev.Acquire();
            }
            catch (Exception )
            {
                MessageBox.Show("DirectInput Faild to Start (userinterface.vb). Outerspace will exit");
                target.Dispose();
                Application.Exit();
            }

            Cursor.Hide();
            needrestore = false;
        }
        private void InitializeGraphics()
        {
            try {
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed = true;
                presentParams.SwapEffect = SwapEffect.Discard;
                presentParams.BackBufferFormat = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;

                // Do we support a pure device?
                if (caps.DeviceCaps.SupportsPureDevice)
                    flags |= CreateFlags.PureDevice;

                device = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                tileSheet = TextureLoader.FromFile(device, MediaUtilities.FindFile("donuts.bmp"), 1024, 1024,
                    1, 0,Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked((int)0xff000000)));
                //Uncomment these lines to see the spite border areas
                //				donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile("donuts.bmp"), 1024, 1024,
                //					1, 0,Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, 0);

                tileSet = new TileSet(tileSheet, 0, 0, 6, 5, 32, 32);
                tilePosition = new Rectangle(tileSet.XOrigin, tileSet.YOrigin,tileSet.ExtentX*2, tileSet.ExtentY*2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                    DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive );
                kbd.Acquire();

                hrt.Start();

            }
            catch (DirectXException) {
                // Catch any errors and return a failure
            }
        }
Beispiel #43
0
        private void deviceSelectButton_Click(object sender, System.EventArgs e)
        {
            threadRescanButton.Enabled = false;
            threadHookBox.Enabled = false;
            foreach(DeviceInstance di in Manager.GetDevices(
                DeviceClass.GameControl,
                EnumDevicesFlags.AttachedOnly))
            {
                if(((string)controlSelect.SelectedItem).CompareTo(di.InstanceName) == 0)
                {
                    hookyStick = new Device(di.InstanceGuid);
                    if(hookyStick == null)
                    {
                        throw new Exception("Cannot instantiate joystick");
                    }
                    //set cooperative level.
                    hookyStick.SetCooperativeLevel(
                        this,
                        CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);
                    System.Diagnostics.Debug.WriteLine("Starting");
                    //Set joystick axis ranges.
                    foreach(DeviceObjectInstance doi in hookyStick.Objects)
                    {

                        if((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                        {
                            hookyStick.Properties.SetRange(
                                ParameterHow.ById,
                                doi.ObjectId,
                                new InputRange(-5000,5000));
                        }
                        else if((doi.ObjectId & (int)DeviceObjectTypeFlags.AbsoluteAxis) != 0)
                        {
                            hookyStick.Properties.SetRange(
                                ParameterHow.ById,
                                doi.ObjectId,
                                new InputRange(-5000,5000));
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine(doi.ToString());
                        }
                    }

                    //Set joystick axis mode absolute.
                    hookyStick.Properties.AxisModeAbsolute = true;
                    //Acquire joystick for capturing.
                    hookyStick.Acquire();
                }
            }
            threadRescanButton.Enabled = true;
        }
Beispiel #44
0
        /// <summary>
        /// Initialize the keyboard device
        /// </summary>
        public void InitializeKeyboard()
        {
            // The first line allocates the system's default keyboard to your variable keyb.
            this.keyboardDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);

            // Then you set some flags that adds default keyboard behavior to keyb. For example, if your window loses focus, your keyboard won't be attached to it any longer.
            this.keyboardDevice.SetCooperativeLevel(
                this,
                CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

            // Don't forget to acquire your keyboard and to call this method from your Main method:
            this.keyboardDevice.Acquire();
        }
Beispiel #45
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="gamepadInstanceGuid">The DirectInput device Guid</param>
 public PCGamepad(Guid gamepadInstanceGuid)
 {
     device = new DI.Device(gamepadInstanceGuid);
     device.SetDataFormat(DI.DeviceDataFormat.Joystick);
     device.Acquire();
     caps = device.Caps;
 }
Beispiel #46
0
 private void GetGamePads()
 {
     // Reference code from http://blogs.msdn.com/coding4fun/archive/2006/11/03/940908.aspx
     this.deviceInput = null;
     this.lblStatus.Text = "Game controller not found. Use sliders.";
     DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
     if (gameControllerList.Count > 0)
     {
         foreach (DeviceInstance deviceInstance in gameControllerList)
         {
             // not a loop, get the first one available, and then break
             this.deviceInput = new Microsoft.DirectX.DirectInput.Device(deviceInstance.InstanceGuid);
             this.deviceInput.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
             this.deviceInput.SetDataFormat(DeviceDataFormat.Joystick);
             this.lblStatus.Text = "Game controller connected. Use joystick.";
             this.slideSmooth.Visible = false; this.slideWidth.Visible = false; this.lblWidth.Visible = false; this.lblSmooth.Visible = false;
             break;
         }
     }
 }
Beispiel #47
0
        /// <summary>
        /// Initializes the Keyboard and Mouse.
        /// </summary>
        /// <exception cref="KeyboardNotFoundException">DirectInput could not aquire Keyboard</exception>
        /// <exception cref="MouseNotFoundException">DirectInput could not aquire Mouse</exception>
        private void InitializeInputDevices()
        {
            keyboard = new DI.Device(DI.SystemGuid.Keyboard);
            if (keyboard == null) throw new KeyboardNotFoundException("No keyboard found.");

            mouse = new DI.Device(DI.SystemGuid.Mouse);
            if (mouse == null) throw new MouseNotFoundException("No mouse found.");

            keyboard.SetCooperativeLevel(this, DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
            keyboard.Acquire();

            mouse.SetCooperativeLevel(this, DI.CooperativeLevelFlags.NonExclusive | DI.CooperativeLevelFlags.Background);
            mouse.Acquire();
        }
        private void Initialize()
        {
            try {
                //Common DirectX setup calls...
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed = true;
                presentParams.SwapEffect = SwapEffect.Discard;
                presentParams.BackBufferFormat = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;

                device = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                //Space Donuts setup
                donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile(TileSetFileName), 1024, 1024,
                    1, 0,Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked((int)0xff000000)));

                donutTileSet = new TileSet(donutTexture, 0, 0, 6, 5, 32, 32);
                pyramidTileSet = new TileSet(donutTexture, 0, 384, 4, 10, 16, 16);
                sphereTileSet = new TileSet(donutTexture, 0, 512, 2, 20, 8, 8);
                cubeTileSet = new TileSet(donutTexture, 0, 544, 2, 20, 8, 8);
                shipTileSet = new TileSet(donutTexture, 0, 576, 4, 10, 16, 16);
                nixiesTileSet = new TileSet(donutTexture, 0, 832, 1, 14, 8, 8);
                bulletTileSet = new TileSet(donutTexture, 304, 832, 1, 1, 8, 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                    DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                soundHandler = new SoundHandler(this);

                sm.OnCollisionDetected += new SpriteManager.HandleCollision(this.CollisionHandler);

                hrt.Start();
            }
            catch (DirectXException e) {
                Console.WriteLine("Exception is " + e.ErrorString);
                // Catch any errors and return a failure
            }
        }
 public void InitializeKeyboard()
 {
     keyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
     keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
     keyb.Acquire();
 }
        //privateなメソッド=====================
        /// <summary>
        /// デバイスの初期化
        /// </summary>
        static void Initialize()
        {
            //keyMap = PS2KeyMap;

            // DirectInputデバイスのリストを取得
            DInput.DeviceList controllers =
                DInput.Manager.GetDevices(
                    DInput.DeviceClass.GameControl,
                    DInput.EnumDevicesFlags.AllDevices);

            //Joystickのデバイスを作る器
            DInput.Device d;

            //取得したデバイスのリストをforeachして1つづつjoysticksに登録
            foreach (DInput.DeviceInstance i in controllers) {
                //デバイスの生成
                d = new DInput.Device(i.InstanceGuid);

                //各種フラグの設定。Backgroundだと第一引数のFormはnullでいい
                d.SetCooperativeLevel(null,
                    DInput.CooperativeLevelFlags.NonExclusive
                  | DInput.CooperativeLevelFlags.NoWindowsKey
                  | DInput.CooperativeLevelFlags.Background
                );

                //Joystickタイプのデータフォーマットを設定
                d.SetDataFormat(DInput.DeviceDataFormat.Joystick);

                //アナログスティックなどのAxis要素を持つDeviceObjectInstanceの出力レンジを設定
                foreach (DInput.DeviceObjectInstance oi in d.Objects) {
                    if ((oi.ObjectId & (int)DInput.DeviceObjectTypeFlags.Axis) != 0) {
                        d.Properties.SetRange(
                            DInput.ParameterHow.ById,
                            oi.ObjectId,
                            new DInput.InputRange(-1000, 1000));
                    }
                }

                //Axisの絶対位置モードを設定
                d.Properties.AxisModeAbsolute = true;

                //とりあえずデバイスを動かす
                try { d.Acquire(); }
                catch (Microsoft.DirectX.DirectXException) { }

                //作ったJoystickのDeviceをJoystickリストに追加
                joysticks.Add(d);

                //Joystickの状態を保持させる為のjsstatesを用意、とりあえず現在と以前の状態で2つ用意してみる
                //Geek:一個でよくね……?
                jsStates.Add(new DInput.JoystickState());
            }
        }
        /// <summary>
        ///		Prepares DirectInput for non-immediate input capturing.
        /// </summary>
        private void InitializeBufferedKeyboard()
        {
            // create the device
            keyboardDevice = new DInput.Device(SystemGuid.Keyboard);

            // Set the data format to the keyboard pre-defined format.
            keyboardDevice.SetDataFormat(DeviceDataFormat.Keyboard);

            // grab the keyboard
            // For debugging, use the background flag so we don't lose input when we are in the debugger.
            // For release, use the foreground flag, so input to other apps doesn't show up here
            CooperativeLevelFlags excl = ownKeyboard ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive;
            CooperativeLevelFlags background = (backgroundKeyboard && !ownKeyboard) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground;

            keyboardDevice.SetCooperativeLevel(control.FindForm(), excl | background);

            // set the buffer size to use for input
            keyboardDevice.Properties.BufferSize = BufferSize;

            // note: dont acquire yet, wait till capture
            //try {
            //    keyboardDevice.Acquire();
            //}
            //catch {
            //    throw new Exception("Unable to acquire a keyboard using DirectInput.");
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        private void InitializeBufferedMouse()
        {
            // create the device
            mouseDevice = new DInput.Device(SystemGuid.Mouse);

            mouseDevice.Properties.AxisModeAbsolute = true;

            // set the device format so DInput knows this device is a mouse
            mouseDevice.SetDataFormat(DeviceDataFormat.Mouse);

            // set the buffer size to use for input
            mouseDevice.Properties.BufferSize = BufferSize;

            CooperativeLevelFlags excl = ownMouse ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive;
            CooperativeLevelFlags background = (backgroundMouse && !ownMouse) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground;

            // set cooperation level
            mouseDevice.SetCooperativeLevel(control.FindForm(), excl | background);

            // note: dont acquire yet, wait till capture?
            //try {
            //    mouseDevice.Acquire();
            //} catch {
            //    throw new Exception("Unable to acquire a mouse using DirectInput.");
            //}
        }
Beispiel #53
0
        public bool InitializeDirectInput()
        {
            try
            {
                diDevice = new DirectInput.Device(SystemGuid.Keyboard);
                diDevice.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                diDevice.Acquire();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        ///     Called when the platform manager is shutting down.
        /// </summary>
        public override void Dispose()
        {
            if (keyboardDevice != null) {
                keyboardDevice.Unacquire();
                keyboardDevice.Dispose();
                keyboardDevice = null;
            }

            if (mouseDevice != null) {
                mouseDevice.Unacquire();
                mouseDevice.Dispose();
                mouseDevice = null;
            }

            control.MouseEnter -= new System.EventHandler(this.control_MouseEnter);
            control.MouseLeave -= new System.EventHandler(this.control_MouseLeave);
        }
        /// <summary>
        ///		Prepares DirectInput for immediate mouse input.
        /// </summary>
        private void InitializeImmediateMouse()
        {
            // create the device
            mouseDevice = new DInput.Device(SystemGuid.Mouse);

            mouseDevice.Properties.AxisModeAbsolute = true;

            // set the device format so DInput knows this device is a mouse
            mouseDevice.SetDataFormat(DeviceDataFormat.Mouse);

            CooperativeLevelFlags excl = ownMouse ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive;
            CooperativeLevelFlags background = (backgroundMouse && !ownMouse) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground;

            // set cooperation level
            mouseDevice.SetCooperativeLevel(control.FindForm(), excl | background);

            // note: dont acquire yet, wait till capture
        }
        /// <summary>
        ///		Initializes DirectInput for immediate input.
        /// </summary>
        private void InitializeImmediateKeyboard()
        {
            // Create the device.
            keyboardDevice = new DInput.Device(SystemGuid.Keyboard);

            // grab the keyboard
            CooperativeLevelFlags excl = ownKeyboard ? CooperativeLevelFlags.Exclusive : CooperativeLevelFlags.NonExclusive;
            CooperativeLevelFlags background = (backgroundKeyboard && !ownKeyboard) ? CooperativeLevelFlags.Background : CooperativeLevelFlags.Foreground;

            keyboardDevice.SetCooperativeLevel(control.FindForm(), excl | background);

            // Set the data format to the keyboard pre-defined format.
            keyboardDevice.SetDataFormat(DeviceDataFormat.Keyboard);

            try {
                keyboardDevice.Acquire();
            }
            catch {
                throw new Exception("Unable to acquire a keyboard using DirectInput.");
            }
        }
Beispiel #57
0
        public void Init(xEmulateForm form)
        {
            InfoTextManager.Instance.WriteLine("Initializing DirectInput...");
            this.form = form;
            m_keyboard = new DxI.Device(DxI.SystemGuid.Keyboard);
            m_keyboard.Properties.BufferSize = 20;
            m_keyboard.SetCooperativeLevel(form.Handle,
                                            DxI.CooperativeLevelFlags.Foreground |
                                            DxI.CooperativeLevelFlags.NonExclusive |
                                            DxI.CooperativeLevelFlags.NoWindowsKey);

            m_mouse = new DxI.Device(DxI.SystemGuid.Mouse);
            m_mouse.Properties.BufferSize = 20;

            m_mouse.SetCooperativeLevel(form,

            #if DEBUG
                                            DxI.CooperativeLevelFlags.Background |
                                            DxI.CooperativeLevelFlags.NonExclusive);
            #else
                                            DxI.CooperativeLevelFlags.Foreground |
                                            DxI.CooperativeLevelFlags.Exclusive);
            #endif

            InfoTextManager.Instance.Write("Complete.");
            InitJoy();
        }
Beispiel #58
0
        private void InitInput()
        {
            //create keyboard device.
            keyboard = new Input.Device(Input.SystemGuid.Keyboard);
            if (keyboard == null) {
                MessageBox.Show("No keyboard found.");
            }
            keyboard.SetCooperativeLevel(
            this,
            Input.CooperativeLevelFlags.NonExclusive |
            Input.CooperativeLevelFlags.Background);
            keyboard.Acquire();

            //create mouse device.
            mouse = new Input.Device(Input.SystemGuid.Mouse);
            if (mouse == null) {
                MessageBox.Show("No mouse found.");
            }
            mouse.Properties.AxisModeAbsolute = false;
            mouse.SetCooperativeLevel(
            this,
            Input.CooperativeLevelFlags.NonExclusive |
            Input.CooperativeLevelFlags.Background);
            mouse.Acquire();
        }
Beispiel #59
0
        private void controlSelect_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if(ffActuator != null)	ffActuator.Unacquire();
            feedbackAmountSlider.Enabled = false;
            objectGUIDValue.Enabled = false;
            xmlQueryButton.Enabled = false;
            foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.All, EnumDevicesFlags.ForceFeeback))
            {
                if(((string)controlSelect.SelectedItem).CompareTo(di.InstanceName) == 0)
                {
                    ffActuator = new Device(di.InstanceGuid);
                    if(ffActuator == null)
                    {
                        throw new Exception("Cannot instantiate joystick");
                    }
                    //set cooperative level.
                    ffActuator.SetCooperativeLevel(
                        this,
                        CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);

                    //Set axis mode absolute.
                    ffActuator.Properties.AxisModeAbsolute = true;

                    //Acquire joystick for capturing.
                    ffActuator.Acquire();

                    //Configure axes
                    foreach(DeviceObjectInstance doi in ffActuator.Objects)
                    {

                        //Set axes ranges.
                        if((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                        {
                            ffActuator.Properties.SetRange(
                                ParameterHow.ById,
                                doi.ObjectId,
                                new InputRange(-5000,5000));
                        }

                        int[] temp;

                        // Get info about first two FF axii on the device
                        if ((doi.Flags & (int)ObjectInstanceFlags.Actuator) != 0)
                        {
                            if (forceAxes != null)
                            {
                                temp = new int[forceAxes.Length + 1];
                                forceAxes.CopyTo(temp,0);
                                forceAxes = temp;
                            }
                            else
                            {
                                forceAxes = new int[1];
                            }

                            // Store the offset of each axis.
                            forceAxes[forceAxes.Length - 1] = doi.Offset;
                            if (forceAxes.Length == 2)
                            {
                                break;
                            }

                            string path =
                                @"C:\temp\force.ffe";
                            EffectList el = null;
                            el = ffActuator.GetEffects(path,FileEffectsFlags.ModifyIfNeeded);
                            EffectObject feo = null;
                            foreach(FileEffect fe in el)
                            {
                                constantVibrate = fe.EffectStruct;
                                feo = new EffectObject(
                                      fe.EffectGuid,
                                      fe.EffectStruct,
                                      ffActuator);
                                try
                                {
                                    feo.Download();
                                }
                                catch(Exception ex)
                                {
                                    throw new Exception("Could not download force feedback effect file.", ex);
                                }
                                eo = feo;
                                break;
                            }
                            constantVibrate.Constant.Magnitude = 0;
                            eo.SetParameters(constantVibrate, EffectParameterFlags.TypeSpecificParams);
                            eo.Download();
                            eo.Start(1);
                            feedbackAmountSlider.Enabled = true;
                            objectGUIDValue.Enabled = true;
                            xmlQueryButton.Enabled = true;
                        }
                    }
                    break;
                }
            }
        }
Beispiel #60
0
        public void InitJoy()
        {
            Xna.Input.GamePadState gamePadState = Xna.Input.GamePad.GetState(Xna.PlayerIndex.One);
            if (gamePadState.IsConnected)
            {
                this.useXInput = true;
                InfoTextManager.Instance.WriteLine("Initialized 1 XInput Controller, skipping Joysticks");
            }
            else
            {

                foreach (DxI.DeviceInstance pad in DxI.Manager.GetDevices(DxI.DeviceClass.GameControl, DxI.EnumDevicesFlags.AttachedOnly))
                {
                    m_joy = new DxI.Device(pad.InstanceGuid);
                    m_joy.SetCooperativeLevel(form, DxI.CooperativeLevelFlags.Background |
            #if DEBUG
                                            DxI.CooperativeLevelFlags.NonExclusive);
            #else
                                            DxI.CooperativeLevelFlags.Exclusive);
            #endif
                }

                if (m_joy != null)
                {
                    InfoTextManager.Instance.WriteLine("Initialized 1 Joystick");
                }
                else
                {
                    InfoTextManager.Instance.WriteLine("No Joysticks Found, Joystick functionality disabled");
                }
            }
        }