Example #1
0
        /// <summary>
        /// 类初始化函数
        /// </summary>
        /// <param name="formName"></param>
        public Direct2D(string formName = "Default")
        {
            _keybord = new Keyboard(new DirectInput());
            _keybord.Acquire();

            RenderQuene = new List <RenderQuene_2D>();
            Resources   = new List <Resource_2D>();

            Mainform = new DrawFrom(formName);        //创建一个渲染窗口
            Mainform.AllowUserResizing = false;       //设置不可调整大小
            Mainform.KeyCallBackSet(KeyBordCallBack); //设置键盘回调
            Mainform.MouseCallBackSet(MouseCallBack); //设置鼠标回调


            CreateSwapChain(CreateDesc(Mainform));                                                //创建设备和交换链
            D2dFactory    = new SharpDX.Direct2D1.Factory();                                      //Direct2D1.Factory 是D2D渲染工厂
            FactoryDWrite = new SharpDX.DirectWrite.Factory();                                    //RW工厂
            DXGIFactory   = SwapChain.GetParent <SharpDX.DXGI.Factory>();                         //DXGI.Factory 是基础渲染工厂
            DXGIFactory.MakeWindowAssociation(Mainform.Handle, WindowAssociationFlags.IgnoreAll); //关联窗口 并忽略所有事件

            // 从backbuffer新建renderTargetView
            BackBuffer     = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);
            BackBufferView = new RenderTargetView(D2Ddevice, BackBuffer);
            using (Surface surface = BackBuffer.QueryInterface <Surface>())
            {
                D2dRenderTarget = new RenderTarget(D2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }

            DefaultBrush = new SolidColorBrush(D2dRenderTarget, Color.White);
        }
Example #2
0
        public void InitDirectX()
        {
            Form.InitDirectX();


            keyboard = new SlimDXTWKeyboard();


            diDevice   = new global::SlimDX.DirectInput.DirectInput();
            diKeyboard = new global::SlimDX.DirectInput.Keyboard(diDevice);
            diKeyboard.SetCooperativeLevel(Form.Form, CooperativeLevel.Nonexclusive | CooperativeLevel.Foreground);
            diKeyboard.Acquire();


            mouse   = new TWMouse();
            diMouse = new global::SlimDX.DirectInput.Mouse(new DirectInput());
            diMouse.SetCooperativeLevel(Form.Form, CooperativeLevel.Exclusive | CooperativeLevel.Foreground);

            SpectaterCamera = new SpectaterCamera();
            Camera          = SpectaterCamera;



            LineManager3D   = new LineManager3D(Form.Device);
            TextureRenderer = new TextureRenderer(Form.Device);
            HelperStates    = new HelperStatesContainer(Form.Device);
        }
Example #3
0
        private bool ReadKeyboard()
        {
            var resultCode = ResultCode.Ok;

            if (_keyboardState != null)
            {
                _keyboardState = null;
            }
            _keyboardState = new KeyboardState();

            try
            {
                _keyboard.GetCurrentState(ref _keyboardState);
            }
            catch (SharpDX.SharpDXException ex)
            {
                resultCode = ex.Descriptor; // ex.ResultCode;
                return(false);
            }

            if (resultCode == ResultCode.InputLost || resultCode == ResultCode.NotAcquired)
            {
                _keyboard.Acquire();
            }
            else if (resultCode != ResultCode.Ok)
            {
                return(false);
            }

            return(true);
        }
Example #4
0
        public PCKeyboardReader()
        {
            _dinput = new DirectInput();

            _keyboard = new Keyboard(_dinput);
            _mouse    = new Mouse(_dinput);

            ResourceManager stringManager = Properties.Resources.ResourceManager;

            try
            {
                _keyboard.Acquire();
            }
            catch (SharpDXException)
            {
                throw new IOException(stringManager.GetString("KeyboardCouldNotBeAcquired", CultureInfo.CurrentUICulture));
            }

            try
            {
                _mouse.Acquire();
            }
            catch (SharpDXException)
            {
                throw new IOException(stringManager.GetString("MouseCouldNotBeAcquired", CultureInfo.CurrentUICulture));
            }

            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(TIMER_MS)
            };
            _timer.Tick += Tick;
            _timer.Start();
        }
Example #5
0
        /// <summary>
        /// Gathers input from connected devices
        /// </summary>
        internal static void GatherInput()
        {
            // Return if the window does not have focus
            //if (_form == null) return;

            if (!_form.Focused)
            {
                _keyUp.Clear();
                _keyDown.Clear();
                _keyPressed.Clear();

                _mouseDown.Clear();
                _mouseUp.Clear();
                _mouseHeld.Clear();
                return;
            }

            // Poll keyboard
            _keyboard.Acquire();
            _keyboard.Poll();
            ParseKeyboardData(_keyboard.GetBufferedData());

            // Poll mouse
            _mouse.Acquire();
            _mouse.Poll();
            ParseMouseData(_mouse.GetBufferedData());
        }
Example #6
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            switch (deviceType)
            {
            case DeviceType.Keyboard:
            {
                if (keyboard.Acquire().IsSuccess)
                {
                    keyboardState = keyboard.GetCurrentState();
                    if (keyboardState.PressedKeys.Count > 0)
                    {
                        _inputName = keyboardState.PressedKeys[0].ToString();

                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        timer1.Enabled    = false;
                        this.Close();
                        return;
                    }
                }
                break;
            }

            case DeviceType.Joystick:
            {
                if (CheckJoystickInput())
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    timer1.Enabled    = false;
                    this.Close();
                    return;
                }
                break;
            }
            }
        }
Example #7
0
        public static void Update()
        {
            currState = null;
            if (keyboardDevice == null)
            {
                return;
            }
            if (keyboardDevice.Acquire().IsFailure)
            {
                return;
            }
            if (keyboardDevice.Poll().IsFailure)
            {
                return;
            }

            KeyboardState state = keyboardDevice.GetCurrentState();

            if (Result.Last.IsFailure)
            {
                return;
            }


            currState = state;
        }
Example #8
0
        private void ReadInput()
        {
            m_keyboard.Acquire();

            m_lastKeystate = m_curKeystate;
            m_curKeystate  = m_keyboard.GetCurrentState();

            IntPtr hForeground = User32Imports.GetForegroundWindow();

            if (hForeground == this.Handle || hForeground == m_pso2HWND)
            {
                KeyBinding hideUI = Program.Settings.HideUIHotkey;
                if (hideUI.CheckKeystate(m_curKeystate, m_lastKeystate) && (hForeground == m_pso2HWND || hideUI.HasModifier()))
                {
                    Program.Settings.HideUI ^= true;
                    chkHideAllUI.DataBindings["Checked"].ReadValue();
                }


                KeyBinding toggleInput = Program.Settings.ToggleInputModeHotkey;
                if (toggleInput.CheckKeystate(m_curKeystate, m_lastKeystate) && (hForeground == m_pso2HWND || toggleInput.HasModifier()))
                {
                    Program.Settings.WalkEnabled ^= true;
                    radRunning.DataBindings["Checked"].ReadValue();
                    radWalking.DataBindings["Checked"].ReadValue();
                }
            }
        }
Example #9
0
        public static void InitInput()
        {
            if (!m_bIsInitialized)
            {
                lock (m_inputMutex)
                {
                    for (int i = 0, count = (int)EInputClass.Count; i < count; i++)
                    {
                        m_inputListeners[i].callbacks = new List <ProcessInputEvents>(8);
                        m_inputListeners[i].bIsActive = true;
                    }

                    m_directInput = new DirectInput();
                    m_keyboard    = new Keyboard(m_directInput);
                    m_mouse       = new Mouse(m_directInput);

                    m_keyboard.Properties.BufferSize = 128;
                    m_mouse.Properties.BufferSize    = 128;

                    m_keyboard.Acquire();
                    m_mouse.Acquire();

                    PollInput();
                    m_bIsInitialized = true;
                }
            }
        }
        public SteeringStep Update()
        {
            try {
                if (_keyboard.Acquire().IsFailure)
                {
                    return(null);
                }

                if (_keyboard.Poll().IsFailure)
                {
                    return(null);
                }

                var state = _keyboard.GetCurrentState();
                if (!IsKeyboardUpdateRequired(state))
                {
                    return(null);
                }

                var step = new SteeringStep {
                    DirectionPercentage = VALOCITY, CamDirectionPercentage = VALOCITY
                };
                step.WithDirection(SteeringStep.MovingDirection.Left, state.PressedKeys.Contains(Key.A) && !state.PressedKeys.Contains(Key.D));
                step.WithDirection(SteeringStep.MovingDirection.Right, !state.PressedKeys.Contains(Key.A) && state.PressedKeys.Contains(Key.D));
                step.SpeedPercentage = state.PressedKeys.Contains(Key.W) ? VALOCITY : state.PressedKeys.Contains(Key.S) ? -VALOCITY : 0.0;
                step.WithCamDirection(SteeringStep.CameraDirection.Up, state.PressedKeys.Contains(Key.UpArrow) && !state.PressedKeys.Contains(Key.DownArrow));
                step.WithCamDirection(SteeringStep.CameraDirection.Down, state.PressedKeys.Contains(Key.DownArrow) && !state.PressedKeys.Contains(Key.UpArrow));
                step.WithCamDirection(SteeringStep.CameraDirection.Left, state.PressedKeys.Contains(Key.LeftArrow) && !state.PressedKeys.Contains(Key.RightArrow));
                step.WithCamDirection(SteeringStep.CameraDirection.Right, state.PressedKeys.Contains(Key.RightArrow) && !state.PressedKeys.Contains(Key.LeftArrow));
                return(step);
            } catch (Exception ex) {
                Trace.TraceError("Could not poll keyboard event(s): {0}", ex.StackTrace);
                return(null);
            } finally { }
        }
Example #11
0
        public void UpdateInput(ref KeyClass KClass)
        {
            if (keyboard.Acquire().IsFailure)
            {
                return;
            }
            Result result = keyboard.Poll();

            if (result.IsFailure)
            {
                return;
            }
            lastKeyboardState    = currentKeyboardState;
            currentKeyboardState = keyboard.GetCurrentState();
            result = Result.Last;
            if (result.IsFailure)
            {
                return;
            }
            KClass.ArrowLeft  = currentKeyboardState.IsPressed(Key.LeftArrow);
            KClass.ArrowRight = currentKeyboardState.IsPressed(Key.RightArrow);
            KClass.ArrowUp    = currentKeyboardState.IsPressed(Key.UpArrow);
            KClass.ArrowDown  = currentKeyboardState.IsPressed(Key.DownArrow);
            KClass.Key_Shift  = currentKeyboardState.IsPressed(Key.LeftShift);
            KClass.Key_Z      = currentKeyboardState.IsPressed(Key.Z) | currentKeyboardState.IsPressed(Key.Return);
            KClass.Key_X      = currentKeyboardState.IsPressed(Key.X);
            KClass.Key_C      = currentKeyboardState.IsPressed(Key.R);
            KClass.Key_Ctrl   = currentKeyboardState.IsPressed(Key.LeftControl);
            KClass.Key_ESC    = currentKeyboardState.IsPressed(Key.Escape);
            KClass.Key_plus   = currentKeyboardState.IsPressed(Key.Equals);
            KClass.Key_minus  = currentKeyboardState.IsPressed(Key.Minus);
            KClass.Key_plus  |= KClass.Key_Ctrl;
            KClass.Key_minus |= KClass.Key_Shift;
        }
Example #12
0
        /// <summary>
        /// Constructs a new input state.
        /// </summary>
        public Input()
        {
            _directInput = new DirectInput();

            // Initialize keyboard
            _keyboard = new Keyboard(_directInput);
            _keyboard.Properties.BufferSize = 256;

            // Set the cooperative level of the keyboard to not share with other programs.
            //_keyboard.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.Exclusive);

            _keyboard.Acquire();

            // Initialize mouse
            _mouse = new Mouse(_directInput);
            _mouse.Properties.AxisMode = DeviceAxisMode.Relative;

            // Set the cooperative level of the mouse to share with other programs.
            //_mouse.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            _mouse.Acquire();

            LastKeyboardState = new KeyboardState();
            KeyboardState     = new KeyboardState();

            LastMouseState = new MouseState();
            MouseState     = new MouseState();
        }
Example #13
0
        internal void Update()
        {
            // save old state
            LastInput = CurrentInput;
            // read keyboard state
            keyboard.Acquire();
            mouse.Acquire();
            KeyboardState ks         = keyboard.GetCurrentState();
            MouseState    ms         = mouse.GetCurrentState();
            FrameInput    frameInput = new FrameInput();

            frameInput.KeyboardState = ks;
            frameInput.MouseState    = ms;
            MouseLocation.X         += ms.X * GameSettings.MouseSensitivity;
            MouseLocation.Y         += -ms.Y * GameSettings.MouseSensitivity;
            // Cap mouse location
            if (MouseLocation.X < 0)
            {
                MouseLocation.X = 0;
            }
            if (MouseLocation.Y < 0)
            {
                MouseLocation.Y = 0;
            }
            if (MouseLocation.Y > TheGame.Instance.Height)
            {
                MouseLocation.Y = TheGame.Instance.Height - 1;
            }
            if (MouseLocation.X > TheGame.Instance.Width)
            {
                MouseLocation.X = TheGame.Instance.Width - 1;
            }
            frameInput.MouseLocation = MouseLocation;
            CurrentInput             = frameInput;
        }
        public override void Update()
        {
            turbo = !turbo;
            if (keyboard.Acquire().IsSuccess)
            {
                state = keyboard.GetCurrentState();
                DATA  = 0;

                if (state.IsPressed(KeyA))
                {
                    DATA |= 1;
                }

                if (state.IsPressed(KeyB))
                {
                    DATA |= 2;
                }

                if (state.IsPressed(KeyTurboA) && turbo)
                {
                    DATA |= 1;
                }

                if (state.IsPressed(KeyTurboB) && turbo)
                {
                    DATA |= 2;
                }

                if (state.IsPressed(KeySelect))
                {
                    DATA |= 4;
                }

                if (state.IsPressed(KeyStart))
                {
                    DATA |= 8;
                }

                if (state.IsPressed(KeyUp))
                {
                    DATA |= 0x10;
                }

                if (state.IsPressed(KeyDown))
                {
                    DATA |= 0x20;
                }

                if (state.IsPressed(KeyLeft))
                {
                    DATA |= 0x40;
                }

                if (state.IsPressed(KeyRight))
                {
                    DATA |= 0x80;
                }
            }
        }
Example #15
0
 // Initialize DirectInput and the keyboard
 public static void DInputInit(Control Handle)
 {
     m_input = new DirectInput();
     //get the default keyboard.
     diDev = new Keyboard(input);
     diDev.SetCooperativeLevel(Handle.Handle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);
     diDev.Acquire();
 }
Example #16
0
 static public void Start()
 {
     directInput = new DirectInput();
     keyboard    = new Keyboard(directInput);
     keyboard.SetCooperativeLevel(Graphics.form, CooperativeLevel.Nonexclusive | CooperativeLevel.Background);
     keyboard.Acquire();
     Console.WriteLine("Got Keyboard Input");
 }
        public void Acquire()
        {
            var directInput = new DirectInput();

            keyboard = new Keyboard(directInput);
            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();
        }
        public InputDeviceManager(Window window, MainWindow.ToggleOverlayCallback _toggleOverlayCallback)
        {
            InputConfig  = new InputConfiguration();
            _directInput = new DirectInput();
            var deviceInstances = _directInput.GetDevices();

            WindowHelper =
                new WindowInteropHelper(window);

            this._toggleOverlayCallback = _toggleOverlayCallback;

            foreach (var deviceInstance in deviceInstances)
            {
                //Workaround for Bad Devices that pretend to be joysticks
                if (!IsBlackListed(deviceInstance.ProductGuid))
                {
                    Logger.Info("Found " + deviceInstance.ProductGuid + " Instance: " + deviceInstance.InstanceGuid +
                                " " +
                                deviceInstance.ProductName.Trim().Replace("\0", "") + " Usage: " +
                                deviceInstance.UsagePage);


                    if (deviceInstance.Type == DeviceType.Keyboard)
                    {
                        Logger.Info("Adding " + deviceInstance.ProductGuid + " Instance: " + deviceInstance.InstanceGuid +
                                    " " +
                                    deviceInstance.ProductName.Trim().Replace("\0", ""));
                        var device = new Keyboard(_directInput);

                        device.SetCooperativeLevel(WindowHelper.Handle,
                                                   CooperativeLevel.Background | CooperativeLevel.NonExclusive);
                        device.Acquire();

                        _inputDevices.Add(device);
                    }
                    else if (deviceInstance.Type >= DeviceType.Joystick && deviceInstance.Type <= DeviceType.FirstPerson || IsWhiteListed(deviceInstance.ProductGuid))
                    {
                        var device = new Joystick(_directInput, deviceInstance.InstanceGuid);

                        Logger.Info("Adding " + deviceInstance.ProductGuid + " Instance: " +
                                    deviceInstance.InstanceGuid + " " +
                                    deviceInstance.ProductName.Trim().Replace("\0", ""));

                        device.SetCooperativeLevel(WindowHelper.Handle,
                                                   CooperativeLevel.Background | CooperativeLevel.NonExclusive);
                        device.Acquire();

                        _inputDevices.Add(device);
                    }
                }
                else
                {
                    Logger.Info("Found but ignoring " + deviceInstance.ProductGuid + " Instance: " +
                                deviceInstance.InstanceGuid + " " +
                                deviceInstance.ProductName.Trim().Replace("\0", "") + " Type: " + deviceInstance.Type);
                }
            }
        }
        // Methods.
        internal bool Initialize(DSystemConfiguration configuration, IntPtr windowsHandle)
        {
            // Screen the screen size which will be used for positioning the mouse cursor.
            _ScreenWidth  = configuration.Width;
            _ScreenHeight = configuration.Height;

            // Initialize the location of the mouse on the screen.
            _MouseX = 0;
            _MouseY = 0;

            // Initialize the main direct input interface.
            _DirectInput = new DirectInput();

            #region Keyboard related Initiailization
            // Initialize the direct interface for the keyboard.
            _Keyboard = new Keyboard(_DirectInput);
            _Keyboard.Properties.BufferSize = 256;

            // Set the cooperative level of the keyboard to not share with other programs.
            // use 'CooperativeLevel.Background' for debugging purpose on Both the Mouse and Keyboard as well as NonExclusive on the keybaord.
            _Keyboard.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            try
            {
                _Keyboard.Acquire();
            }
            catch (SharpDXException sEx)
            {
                if (sEx.ResultCode.Failure)
                {
                    return(false);
                }
            }
            #endregion

            #region Mouse related Initiailization
            // Initialize the direct interface for the mouse.
            _Mouse = new Mouse(_DirectInput);
            _Mouse.Properties.AxisMode = DeviceAxisMode.Relative;

            // Set the cooperative level of the mouse to share with other programs.
            _Mouse.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            try
            {
                _Mouse.Acquire();
            }
            catch (SharpDXException sEx)
            {
                if (sEx.ResultCode.Failure)
                {
                    return(false);
                }
            }
            #endregion

            return(true);
        }
        public DirectHotkey()
        {
            DirectInput   = new DirectInput();
            KeyboardState = new KeyboardState();

            MonitoredKeyboard = new Keyboard(DirectInput);
            MonitoredKeyboard.Properties.BufferSize = PollBufferSize;
            MonitoredKeyboard.Acquire();
        }
        public KeyboardHotkey()
        {
            var directInput = new DirectInput();
            var keyboard    = new Keyboard(directInput);

            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();
            this.keyboard = keyboard;
        }
Example #22
0
        public void LoadResources(RenderTarget render)
        {
            BackgroundColor = Color.CornflowerBlue;
            Tileset         = Resources.LoadImageFromFile(render, "breakout_pieces.png");

            DirectInput = new DirectInput();
            Keyboard    = new Keyboard(DirectInput);
            Keyboard.Acquire();
        }
Example #23
0
        public void Update()
        {
            //Log.Info("updating");
            while (true)
            {
                try {
                    _keyboard.Poll();
                    _keyState = _keyboard.GetCurrentState();


                    if (Result.Last.IsSuccess)
                    {
                        break;
                    }
                } catch (DirectInputException ex) {
                    Console.WriteLine(ex.Message);
                    _result = ex.ResultCode;
                    if (_result != ResultCode.InputLost && _result != ResultCode.NotAcquired)
                    {
                        return;
                    }
                    if ((_result = (_keyboard.Acquire())).IsFailure)
                    {
                        Log.Info("Failed to aquire keyboard");
                        //Log.Info(_result);
                        return;
                    }
                }
            }
            while (true)
            {
                try {
                    _mouse.Poll();
                    _mouseState = _mouse.GetCurrentState();
                    break;
                } catch (DirectInputException ex) {
                    _result = ex.ResultCode;
                    if (_result != ResultCode.InputLost && _result != ResultCode.NotAcquired)
                    {
                        return;
                    }
                    if (((_result = _mouse.Acquire())).IsFailure)
                    {
                        Log.Info("Failed to aquire mouse");
                        Log.Info(_result);
                        return;
                    }
                }
            }
            _position = Cursor.Position;
            if (!_window.IsDisposed)
            {
                _position = _window.PointToClient(_position);
            }
            _pressStamp++;
        }
Example #24
0
 public static void Init(Form mainWindow)
 {
     var dinput = new DirectInput();
     _keyboard = new Keyboard(dinput);
     _keyboard.Acquire();
     _mouse = new Mouse(dinput);
     _mouse.Acquire();
     dinput.Dispose();
     dinput = null;
 }
 public KeyboardController()
 {
     if (Context == null)
     {
         Context  = new DirectInput();
         Keyboard = new Keyboard(Context);
         Keyboard.Acquire();
         State = new KeyboardState();
     }
 }
Example #26
0
        public KeyboardDX()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            keyboard = new Keyboard(directInput);

            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();
        }
        public KeyboardInputService(GameContainer container)
        {
            directInput = new DirectInput();

            //キーボード
            if (directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices).Any())
            {
                keyboardDevice = new Keyboard(directInput);
                keyboardDevice.Acquire();
            }
        }
Example #28
0
        public static void Init()
        {
            input    = new DirectInput();
            keyboard = new Keyboard(input);
            keyboard.SetCooperativeLevel(Renderer.viewport.ParentForm, CooperativeLevel.Nonexclusive | CooperativeLevel.Background);
            keyboard.Acquire();

            mouseRel = new Mouse(input);
            mouseRel.SetCooperativeLevel(Renderer.viewport.ParentForm, CooperativeLevel.Nonexclusive | CooperativeLevel.Background);
            mouseRel.Acquire();
        }
Example #29
0
        public RForm(string text) : base(text)
        {
            this.ClientSize = new System.Drawing.Size(screenWidth, screenHeight);

            desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(this.ClientSize.Width, this.ClientSize.Height, new Rational(144, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = this.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain);
            d2dFactory = new SharpDX.Direct2D1.Factory();
            factory    = swapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAll);
            backBuffer                     = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            renderView                     = new RenderTargetView(device, backBuffer);
            surface                        = backBuffer.QueryInterface <Surface>();
            d2dRenderTarget                = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            solidColorBrush                = new SolidColorBrush(d2dRenderTarget, Color.White);
            solidColorBrush.Color          = Color.White;
            directInput                    = new DirectInput();
            keyboard                       = new Keyboard(directInput);
            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();
            userInputProcessor = new UserInputProcessor();
            scoreTextFormat    = new SharpDX.DirectWrite.TextFormat(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Isolated), "Gill Sans", FontWeight.UltraBold, FontStyle.Normal, 36);
            scoreTextArea      = new SharpDX.Mathematics.Interop.RawRectangleF(10, 10, 400, 400);
            livesTextArea      = new SharpDX.Mathematics.Interop.RawRectangleF(10, 46, 400, 400);
            gameOverTextFormat = new SharpDX.DirectWrite.TextFormat(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Isolated), "Gill Sans", FontWeight.UltraBold, FontStyle.Normal, 108);
            gameOverTextArea   = new SharpDX.Mathematics.Interop.RawRectangleF(0, 0, screenWidth, screenHeight);
            gameOverTextFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center;
            gameOverTextFormat.TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center;;
            rand = new Random();


            ship      = new Ship(screenWidth / 2, screenHeight / 2);
            bullets   = new List <Bullet>();
            asteroids = new List <Asteroid>();

            int count = rand.Next(10, 15);

            for (int i = 0; i < count; i++)
            {
                asteroids.Add(new Asteroid(rand.Next(-25, screenWidth + 25), rand.Next(-25, screenWidth + 25), rand.Next(1, 4) * 10, rand, d2dFactory));
            }

            gameInputTimer = new Stopwatch();
            gameInputTimer.Start();
        }
Example #30
0
        public Game(string windowName,
                    int windowWidth, int windowHeight,
                    bool isWindowed = true)
        {
            RenderForm                   = new RenderForm(windowName);
            RenderForm.Width             = windowWidth;
            RenderForm.Height            = windowHeight;
            RenderForm.AllowUserResizing = false;

            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription(
                        (int)(RenderForm.Width),
                        (int)(RenderForm.Height),
                        new Rational(60, 1),
                        Format.R8G8B8A8_UNorm),
                IsWindowed        = isWindowed,
                OutputHandle      = RenderForm.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware,
                                       DeviceCreationFlags.BgraSupport,
                                       new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 },
                                       desc, out Device, out SwapChain);

            Factory2D = new SharpDX.Direct2D1.Factory();
            Factory factory = SwapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(RenderForm.Handle,
                                          WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

            Surface = backBuffer.QueryInterface <Surface>();

            RenderTarget2D = new RenderTarget(Factory2D, Surface, new RenderTargetProperties(
                                                  new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            //WEB_SOCKET
            Connect();
            System.Threading.Tasks.Task.Delay(1000);

            _gameRender = new GameRender(RenderForm, Factory2D, RenderTarget2D);

            _directInput = new DirectInput();
            _keyboard    = new Keyboard(_directInput);
            _keyboard.Properties.BufferSize = 128;
            _keyboard.Acquire();
        }
Example #31
0
        public static void Init(Form mainWindow)
        {
            var dinput = new DirectInput();

            _keyboard = new Keyboard(dinput);
            _keyboard.Acquire();
            _mouse = new Mouse(dinput);
            _mouse.Acquire();
            dinput.Dispose();
            dinput = null;
        }
Example #32
0
        public TSOForm(TSOConfig tso_config, string[] args)
        {
            this.tso_config = tso_config;

            InitializeComponent();
            this.ClientSize = tso_config.ClientSize;

            this.DragDrop += new DragEventHandler(form_OnDragDrop);
            this.DragOver += new DragEventHandler(form_OnDragOver);

            this.UserResized += delegate(Object sender, EventArgs e)
            {
            userResized = true;
            };

            this.viewer = new Viewer();
            viewer.ScreenColor = tso_config.ScreenColor;

            this.fig_form = new FigureForm();

            if (viewer.InitializeApplication(this, tso_config))
            {
            viewer.figures.FigureEvent += delegate(object sender, EventArgs e)
            {
                Figure fig;
                if (viewer.figures.TryGetFigure(out fig))
                    fig_form.SetFigure(fig);
                else
                    fig_form.Clear();
            };
            viewer.Camera.SetTranslation(tso_config.Position);
            foreach (string arg in args)
                viewer.figures.LoadAnyFile(arg, true);
            if (viewer.figures.Count == 0)
                viewer.figures.LoadAnyFile(Path.Combine(save_path, @"system.tdcgsav.png"), true);
            //this.timer1.Enabled = true;
            }

            directInput = new DirectInput();
            keyboard = new Keyboard(directInput);
            keyboard.Acquire();

            keyboardState = keyboard.GetCurrentState();
        }
Example #33
0
        /// <summary>
        /// Initializes SlimDX and input devices.
        /// </summary>
        /// <param name="caption">Window caption string.</param>
        public FrameworkForm(string caption)
            : base(caption)
        {
            SwapChainDescription description = new SwapChainDescription()
            {
                BufferCount = 1,
                Flags = SwapChainFlags.None,
                IsWindowed = true,
                ModeDescription = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            try
            {
#if DEBUG
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out graphicsDevice, out swapChain);
#else
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out graphicsDevice, out swapChain);
#endif
            }
            catch
            {
                MessageBox.Show("An error has occurred during initialization process.");
                Environment.Exit(0);
            }
            finally
            {
                if (graphicsDevice.FeatureLevel != FeatureLevel.Level_11_0)
                {
                    MessageBox.Show("This program requires DirectX 11. Your version is " + graphicsDevice.FeatureLevel.ToString() + ".");
                    Environment.Exit(0);
                }
            }

            Factory factory = swapChain.GetParent<Factory>();
            factory.SetWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter);
            KeyDown += (o, e) =>
            {
                // Fixes Alt-Enter keyboard input bug in SlimDX.
                if (e.Alt && e.KeyCode == Keys.Enter)
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;

                // Makes screenshot.
                if (e.KeyCode == Keys.F12)
                    MakeScreenshot(Application.StartupPath);
            };

            SizeChanged += (o, e) =>
            {
                // Dispose old resources.
                if (renderTargetView != null)
                    renderTargetView.Dispose();
                if (backBufferTexture != null)
                    backBufferTexture.Dispose();

                // Resize buffers.
                swapChain.ResizeBuffers(1, ClientSize.Width, ClientSize.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

                InitializeOutputMerger();

                camera.UpdateProjection();

                postProcess.Initialize(ClientSize.Width, ClientSize.Height);
            };

            fillMode = FillMode.Solid;
            InitializeOutputMerger();

            // Initializes input devices.
            DirectInput directInput = new DirectInput();
            keyboard = new Keyboard(directInput);
            keyboard.Acquire();
            mouse = new Mouse(directInput);
            mouse.Acquire();

            camera = new Camera(graphicsDevice, new Vector3(50, 50, 50), new Vector3(0, 0, 0), 0.1f, 1000.0f);
            textures = new List<TexturePack>();
            postProcess = new PostProcess(graphicsDevice, ClientSize.Width, ClientSize.Height);
            quadRenderer = new QuadRenderer(graphicsDevice);
        }
Example #34
0
        internal bool Initialize(SystemConfiguration configuration, IntPtr windowsHandle)
        {
            // Screen the screen size which will be used for positioning the mouse cursor.
            _ScreenWidth = configuration.Width;
            _ScreenHeight = configuration.Height;

            // Initialize the location of the mouse on the screen.
            _MouseX = 0;
            _MouseY = 0;

            // Initialize the main direct input interface.
            _DirectInput = new DirectInput();

            // Initialize the direct interface for the keyboard.
            _Keyboard = new Keyboard(_DirectInput);
            _Keyboard.Properties.BufferSize = 256;

            // Set the cooperative level of the keyboard to not share with other programs.
            _Keyboard.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.Exclusive);

            // Now acquire the keyboard.
            if (_Keyboard.Acquire().Failure)
                return false;

            // Initialize the direct interface for the mouse.
            _Mouse = new Mouse(_DirectInput);
            _Mouse.Properties.AxisMode = DeviceAxisMode.Relative;

            // Set the cooperative level of the mouse to share with other programs.
            _Mouse.SetCooperativeLevel(windowsHandle, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);

            // Now acquire the mouse.
            if (_Mouse.Acquire().Failure)
                return false;

            return true;
        }
Example #35
0
        /// <summary>
        /// deviceを作成します。
        /// </summary>
        /// <param name="control">レンダリング先となるcontrol</param>
        /// <param name="ocu_config">設定</param>
        /// <returns>deviceの作成に成功したか</returns>
        public bool InitializeApplication(Control control, OcuConfig ocu_config)
        {
            this.ocu_config = ocu_config;
            oculus = new OculusWrap.Wrap();

            // Initialize the Oculus runtime.
            bool success = oculus.Initialize();
            if (!success)
            {
            MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
            }

            // Use the head mounted display, if it's available, otherwise use the debug HMD.
            int numberOfHeadMountedDisplays = oculus.Hmd_Detect();
            if (numberOfHeadMountedDisplays > 0)
            hmd = oculus.Hmd_Create(0);
            else
            hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2);

            if (hmd == null)
            {
            MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
            }

            if (hmd.ProductName == string.Empty)
            MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error);

            // Specify which head tracking capabilities to enable.
            hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction);

            // Start the sensor which informs of the Rift's pose and motion
            hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None);

            // Create DirectX drawing device.
            device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None);

            ctx = device.ImmediateContext;

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

            string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin");
            if (! File.Exists(effect_file))
            {
            Console.WriteLine("File not found: " + effect_file);
            return false;
            }
            try
            {
            var shader_bytecode = ShaderBytecode.FromFile(effect_file);
            effect = new Effect(device, shader_bytecode);
            }
            catch (SharpDX.CompilationException e)
            {
            Console.WriteLine(e.Message + ": " + effect_file);
            return false;
            }

            sw.Stop();
            Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed);

            string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt");
            if (!File.Exists(techmap_file))
            {
            Console.WriteLine("File not found: " + techmap_file);
            return false;
            }
            techmap.Load(techmap_file);

            control.MouseDown += new MouseEventHandler(form_OnMouseDown);

            // Define the properties of the swap chain.
            SwapChainDescription swapChainDescription = DefineSwapChainDescription(control);

            // Create DirectX Graphics Interface factory, used to create the swap chain.
            dxgi_factory = new SharpDX.DXGI.Factory();
            // Create the swap chain.
            swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription);

            // Retrieve the back buffer of the swap chain.
            buf0 = swap_chain.GetBackBuffer<Texture2D>(0);
            buf0_view = new RenderTargetView(device, buf0);

            // Create a depth buffer, using the same width and height as the back buffer.
            Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control);

            // Create the depth buffer.
            ztex = new Texture2D(device, depthBufferDescription);
            ztex_view = new DepthStencilView(device, ztex);

            ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view);

            viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f);
            ctx.Rasterizer.SetViewport(viewport);

            // Retrieve the DXGI device, in order to set the maximum frame latency.
            using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>())
            {
            dxgiDevice.MaximumFrameLatency = 1;
            }

            layers = new OculusWrap.Layers();
            layer_eye_fov = layers.AddLayerEyeFov();

            CreateEyeTextures();

            CreateMirrorTexture(control);

            World_variable = effect.GetVariableBySemantic("World").AsMatrix();
            WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix();
            WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix();
            /* for HUD */
            Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix();

            LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix();
            LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector();
            UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector();

            cb_variable = effect.GetConstantBufferByName("cb");

            ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource();
            ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource();

            //figures.Camera = camera;
            figures.TSOFileOpen += delegate(TSOFile tso)
            {
            tso.Open(device, effect);
            techmap.AssignTechniqueIndices(tso);
            };

            // Define an input layout to be passed to the vertex shader.
            var technique = effect.GetTechniqueByIndex(0);
            il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie);

            // Setup the immediate context to use the shaders and model we defined.
            ctx.InputAssembler.InputLayout = il;

            DefineBlendState();
            DefineDepthStencilState();
            DefineRasterizerState();

            main_camera = new Camera()
            {
            Position = ocu_config.Position,
            Rotation = Quaternion.Identity,
            };

            directInput = new DirectInput();
            keyboard = new Keyboard(directInput);
            keyboard.Acquire();

            keyboardState = keyboard.GetCurrentState();

            return true;
        }
Example #36
0
 public Main()
 {
     _graphicsDeviceManager = new GraphicsDeviceManager(this)
     {
         SynchronizeWithVerticalRetrace = false,
         PreferredBackBufferWidth = PreferredSize.Width,
         PreferredBackBufferHeight = PreferredSize.Height,
         PreferredBackBufferFormat = PixelFormat.R8G8B8A8.UNormSRgb,
         //DeviceCreationFlags = DeviceCreationFlags.Debug
     };
     IsFixedTimeStep = false;
     Content.RootDirectory = "Content";
     var directInput = new DirectInput();
     _keyboard = new Keyboard(directInput);
     _keyboard.Acquire();
     _mouse = new Mouse(directInput);
     _mouse.Acquire();
 }
Example #37
0
 /// <summary> Creates the input manager. </summary>
 private void CreateInput(RenderForm window)
 {
     directInput = new DirectInput();
     keyboard = new Keyboard(directInput);
     keyboard.SetCooperativeLevel(window.Handle, CooperativeLevel.NonExclusive | CooperativeLevel.Background);
     keyboard.Acquire();
 }