Example #1
0
 private void AllowAltF4ToCloseWindow()
 {
     if (Glfw.GetKey(nativeWindow, Key.LeftAlt) && Glfw.GetKey(nativeWindow, Key.F4))
     {
         CloseAfterFrame();
     }
 }
Example #2
0
 private void ProcessInput(Window window)
 {
     if (Glfw.GetKey(window, Keys.Escape) == InputState.Press)
     {
         Glfw.SetWindowShouldClose(window, true);
     }
 }
Example #3
0
        public void move(Glfw.Window window)
        {
            bool W     = Glfw.GetKey(window, (int)Glfw.KeyCode.W);
            bool D     = Glfw.GetKey(window, (int)Glfw.KeyCode.D);
            bool A     = Glfw.GetKey(window, (int)Glfw.KeyCode.A);
            bool S     = Glfw.GetKey(window, (int)Glfw.KeyCode.S);
            bool space = Glfw.GetKey(window, (int)Glfw.KeyCode.Space);
            bool c     = Glfw.GetKey(window, (int)Glfw.KeyCode.C);

            if (W)
            {
                positin.z -= 0.6f;
            }
            if (S)
            {
                positin.z += 0.6f;
            }
            if (D)
            {
                positin.x += 0.6f;
            }
            if (A)
            {
                positin.x -= 0.6f;
            }
            if (space)
            {
                positin.y += 0.6f;
            }
            if (c)
            {
                positin.y -= 0.6f;
            }
        }
Example #4
0
        public void move(Glfw.Window window)
        {
            bool W = Glfw.GetKey(window, (int)Glfw.KeyCode.W);
            bool D = Glfw.GetKey(window, (int)Glfw.KeyCode.D);
            bool A = Glfw.GetKey(window, (int)Glfw.KeyCode.A);
            bool S = Glfw.GetKey(window, (int)Glfw.KeyCode.S);


            if (W)
            {
                positin.z -= 0.1f;
            }
            if (S)
            {
                positin.z += 0.1f;
            }
            if (D)
            {
                positin.x += 0.1f;
            }
            if (A)
            {
                positin.x -= 0.1f;
            }
        }
Example #5
0
 public virtual void WindowInputProcess()
 {
     if (Glfw.GetKey(WindowInstance, Keys.Escape) == InputState.Press)
     {
         Glfw.SetWindowShouldClose(WindowInstance, true);
     }
 }
Example #6
0
        private void UpdateKeyState(Key key)
        {
            bool isKeyPressed = Glfw.GetKey(nativeWindow, ConvertToPencilKey(key));

            keyboardStates[(int)key] = keyboardStates[(int)key].UpdateOnNativePressing(isKeyPressed);
            if (keyboardStates[(int)key] == State.Pressing)
            {
                newlyPressedKeys.Add(key);
            }
        }
Example #7
0
        public KeyboardState(GameWindow window)
            : this()
        {
            GlfwWindowPtr ptr = window.GetPointer();

            keys = new Dictionary <Key, bool>(allKeys.Length);
            for (int i = 0; i < allKeys.Length; i++)
            {
                Key k = allKeys[i];
                keys[k] = Glfw.GetKey(ptr, k);
            }
        }
Example #8
0
        private unsafe static void ProcessInput(WindowHandle *window)
        {
            float camSpeed = (float)(2.5f * deltaTime);

            if (glfw.GetKey(window, Keys.Escape) == (int)InputAction.Press)
            {
                glfw.SetWindowShouldClose(window, true);
            }
            if (glfw.GetKey(window, Keys.W) == (int)InputAction.Press)
            {
                camera.Position += camera.GetDirection() * camSpeed;
            }
            if (glfw.GetKey(window, Keys.S) == (int)InputAction.Press)
            {
                camera.Position -= camera.GetDirection() * camSpeed;
            }
            if (glfw.GetKey(window, Keys.A) == (int)InputAction.Press)
            {
                camera.Position -= Vector3.Normalize(Vector3.Cross(camera.GetDirection(), camera.Up)) * camSpeed;
            }
            if (glfw.GetKey(window, Keys.D) == (int)InputAction.Press)
            {
                camera.Position += Vector3.Normalize(Vector3.Cross(camera.GetDirection(), camera.Up)) * camSpeed;
            }
            if (glfw.GetKey(window, Keys.G) == (int)InputAction.Press)
            {
                Console.WriteLine($"Dir: {camera.GetDirection()}, Pos: {camera.Position}, Yaw: {camera.Yaw}, Pitch: {camera.Pitch}");
            }
        }
Example #9
0
        public static void Main()
        {
            ToolBox.gl = new OpenGL();
            Glfw.Init();

            Glfw.SetErrorCallback((code, message) => Console.WriteLine($"GLFW {code}: {Marshal.PtrToStringAnsi(message)}"));

            Glfw.WindowHint(Hint.Resizable, false);
            Glfw.WindowHint(Hint.Visible, false);
            Glfw.WindowHint(Hint.ContextVersionMajor, 4);
            Glfw.WindowHint(Hint.ContextVersionMinor, 6);

            VideoMode mode   = Glfw.GetVideoMode(Glfw.PrimaryMonitor);
            Window    window = Glfw.CreateWindow(mode.Width, mode.Height, "Meinkraft", Glfw.PrimaryMonitor, Window.None);

            ToolBox.window = window;

            Glfw.MakeContextCurrent(window);
            Glfw.SetInputMode(window, InputMode.Cursor, (int)CursorMode.Disabled);


            ToolBox.gl.Enable(OpenGL.GL_DEPTH_TEST);

            ToolBox.gl.Enable(OpenGL.GL_CULL_FACE);
            ToolBox.gl.FrontFace(OpenGL.GL_CW);

            ToolBox.gl.ClearColor(0x87 / 255.0f, 0xCE / 255.0f, 0xFA / 255.0f, 0xFF / 255.0f);

            ToolBox.world = new World(window);

            while (!Glfw.WindowShouldClose(window))
            {
                Glfw.PollEvents();

                if (Glfw.GetKey(window, Keys.Escape) == InputState.Press)
                {
                    Glfw.SetWindowShouldClose(window, true);
                }

                ToolBox.world.update();

                ToolBox.gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);

                ToolBox.world.render();

                Glfw.SwapBuffers(window);
            }

            ToolBox.world.Dispose();

            Glfw.Terminate();
        }
Example #10
0
        // update the scene based on the time elapsed since last update
        private static void Update(double secondsElapsed)
        {
            //rotate by 1 degree
            float degreesPerSecond = 180.0f;

            _gDegreesRotated += (float)secondsElapsed * degreesPerSecond;

            //don't go over 360 degrees
            while (_gDegreesRotated > 360.0f)
            {
                _gDegreesRotated -= 360.0f;
            }

            //move position of camera based on WASD keys, and XZ keys for up and down
            float moveSpeed = 2.0f; //units per second

            if (Glfw.GetKey(_window, Key.S))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -_gCamera.Forward);
            }
            else if (Glfw.GetKey(_window, Key.W))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * _gCamera.Forward);
            }
            if (Glfw.GetKey(_window, Key.A))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -_gCamera.Right);
            }
            else if (Glfw.GetKey(_window, Key.D))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * _gCamera.Right);
            }
            if (Glfw.GetKey(_window, Key.Z))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -new Vector3(0, 1, 0));
            }
            else if (Glfw.GetKey(_window, Key.X))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * new Vector3(0, 1, 0));
            }

            //rotate camera based on mouse movement
            float  mouseSensitivity = 0.1f;
            double mouseX, mouseY;

            Glfw.GetCursorPos(_window, out mouseX, out mouseY);
            _gCamera.OffsetOrientation(mouseSensitivity * (float)mouseY, mouseSensitivity * (float)mouseX);
            Glfw.SetCursorPos(_window, 0, 0); //reset the mouse, so it doesn't go out of the window
        }
Example #11
0
        /// <inheritdoc />
        public void Update()
        {
            // Update the mouse position.
            Glfw.GetCursorPos(_win, out double posX, out double posY);
            _mousePosition.X = (float)posX;
            _mousePosition.Y = (float)posY;

            // Reset mouse scroll.
            _mouseScrollThisFrame = _mouseScroll;
            _mouseScroll          = _mouseScrollAccum;

            // Calculate mouse status.
            foreach (MouseKey key in _mouseKeys)
            {
                _mouseStatusShadow[key] = _mouseStatus[key];

                int state = Glfw.GetMouseButton(_win, (int)key);
                _mouseStatus[key] = state >= 1;
            }

            // Calculate keyboard status.
            foreach (KeyCode key in _allKeys)
            {
                // Transfer from last frame.
                _keyStatusShadow[key] = _keyStatus[key];

                int state = Glfw.GetKey(_win, (int)key);
                _keyStatus[key] = state >= 1;
            }

            // Update joysticks.
            foreach (KeyValuePair <int, GlfwJoystick> joystick in _loadedJoysticks)
            {
                joystick.Value.Update();
            }

            // Check for fullscreen toggling key combo.
            if (IsKeyHeld("LeftAlt") && IsKeyDown("Enter"))
            {
                Engine.Host.WindowMode = Engine.Host.WindowMode == WindowMode.Fullscreen ? WindowMode.Windowed : WindowMode.Fullscreen;
            }

            // Check for closing combo.
            if (IsKeyDown("Escape"))
            {
                Engine.Quit();
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            ///
            /// NOTE: All GL functions must come after the window and context are created
            ///
            gameWindow.createWindow();
            if (gameWindow.Equals(null))
            {
                Console.WriteLine("ERROR: Could not start game window\nPress any key to continue...");
                Console.ReadKey();
                Environment.Exit(1);
            }

            Console.WriteLine("Using OpenGL version {0}", gameWindow.getGLVersion());
            gameWindow.initGraphics();

            mesh   = new Mesh();
            shader = new Shader();

            Vertex[] data = new Vertex[3];

            data[0].Position = new Vector3(-1, -1, 0);
            data[1].Position = new Vector3(0, 1, 0);
            data[2].Position = new Vector3(1, -1, 0);

            mesh.addVertices(data);

            shader.addVertexShader(ResourceLoader.loadShader("example.vert"));
            shader.addFragmentShader(ResourceLoader.loadShader("example.frag"));
            shader.compileShader();

            while (!Glfw.WindowShouldClose(gameWindow.window))
            {
                Glfw.PollEvents();

                if (Glfw.GetKey(gameWindow.window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(gameWindow.window, true);
                }

                render();

                Glfw.SwapBuffers(gameWindow.window);
            }

            Glfw.Terminate();
        }
Example #13
0
        public void update()
        {
            float ratio = 1.0f;

            if (Glfw.GetKey(_window, Keys.LeftControl) == InputState.Press)
            {
                ratio = 0.1f;
            }

            if (Glfw.GetKey(_window, Keys.LeftShift) == InputState.Press)
            {
                ratio = 2f;
            }

            if (Glfw.GetKey(_window, Keys.W) == InputState.Press)
            {
                position += orientation * 0.05f * ratio;
            }

            if (Glfw.GetKey(_window, Keys.S) == InputState.Press)
            {
                position -= orientation * 0.05f * ratio;
            }

            if (Glfw.GetKey(_window, Keys.A) == InputState.Press)
            {
                position += _sideOrientation * 0.05f * ratio;
            }

            if (Glfw.GetKey(_window, Keys.D) == InputState.Press)
            {
                position -= _sideOrientation * 0.05f * ratio;
            }

            dvec2 mouseOffset = new dvec2();

            Glfw.GetCursorPosition(_window, out mouseOffset.x, out mouseOffset.y);
            mouseOffset -= _winCenter;

            if (Math.Abs(mouseOffset.x + mouseOffset.y) < 0.01f)
            {
                return;
            }

            rotate((float)-mouseOffset.y / 10.0f, (float)-mouseOffset.x / 10.0f);
            Glfw.SetCursorPosition(_window, _winCenter.x, _winCenter.y);
        }
Example #14
0
        public override void Update(float time)
        {
            curKeyPeriodDown = Glfw.GetKey('.');

            if (Area.Intersects(new Rectangle(UIElement.GetMouseRect())))
            {
                if (Game.MouseClickCurrent)
                {
                    Active = true;
                }
            }
            else if (Game.MouseClickCurrent)
            {
                Active = false;
            }

            if (Active)
            {
                foreach (KeyValuePair <char, Buffer2D <uint> > kvp in TextureTools.Font)
                {
                    char ch = kvp.Key;
                    try {
                        if (Game.CurrentKS [ch] && !Game.PreviousKS [ch])
                        {
                            Text += ch;
                        }
                    } catch (Exception) {
                        if (ch == '.')
                        {
                            if (curKeyPeriodDown && !prevKeyPeriodDown)
                            {
                                Text += ch;
                            }
                        }
                    }
                }

                if (Text.Length > 0 && Game.CurrentKS [Key.Backspace] && !Game.PreviousKS [Key.Backspace])
                {
                    Text = Text.Substring(0, Text.Length - 1);
                }
            }

            prevKeyPeriodDown = curKeyPeriodDown;
        }
Example #15
0
        public static void handle_input(GlfwWindowPtr window)
        {
            bool test = Glfw.GetKey(window, Key.Three);

            if (Glfw.GetKey(window, Key.Escape))
            {
                Glfw.SetWindowShouldClose(window, true);
            }

            if (Glfw.GetKey(window, Key.One))
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
            }

            if (Glfw.GetKey(window, Key.Two))
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            }
        }
Example #16
0
        public void checkInputs(Glfw.Window window)
        {
            bool W     = Glfw.GetKey(window, (int)Glfw.KeyCode.W);
            bool S     = Glfw.GetKey(window, (int)Glfw.KeyCode.S);
            bool D     = Glfw.GetKey(window, (int)Glfw.KeyCode.D);
            bool A     = Glfw.GetKey(window, (int)Glfw.KeyCode.A);
            bool space = Glfw.GetKey(window, (int)Glfw.KeyCode.Space);

            if (W)
            {
                currentSpeed = RUN_SPEED;
            }
            else if (S)
            {
                currentSpeed = -RUN_SPEED;
            }
            else
            {
                currentSpeed = 0;
            }


            if (D)
            {
                currentTurnSpeed = TURN_SPEED;
            }
            else if (A)
            {
                currentTurnSpeed = -TURN_SPEED;
            }
            else
            {
                currentTurnSpeed = 0;
            }

            if (space)
            {
                jump();
            }
        }
Example #17
0
        static void Main()
        {
            if (!Glfw.Init())
            {
                Glfw.Terminate();
                throw new Exception("GLFW Failed to Initialize");
            }

            Glfw.WindowHint(WindowAttrib.Resizable, false);

            var window = Glfw.CreateWindow(1024, 768, "Test");

            if (window.Equals(GlfwWindow.Null))
            {
                Glfw.Terminate();
                throw new Exception("GLFW failed to create window");
            }

            Glfw.CenterWindow(window);

            Glfw.MakeContextCurrent(window);

            Glfw.SwapInterval(1);

            while (!Glfw.WindowShouldClose(window))
            {
                Glfw.PollEvents();

                if (Glfw.GetKey(window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(window, true);
                }

                Glfw.SwapBuffers(window);
            }

            Glfw.DestroyWindow(window);
            Glfw.Terminate();
        }
Example #18
0
        public static bool IsKeyPressed(Key key)
        {
            InputState state = Glfw.GetKey(Application.Instance.Window.Handle, (Keys)key);

            return(state == InputState.Press || state == InputState.Repeat);
        }
Example #19
0
        static void Main(string[] args)
        {
            WebCore.Initialize(new WebConfig()
            {
                LogPath  = Environment.CurrentDirectory + "/awesomium.log",
                LogLevel = LogLevel.Verbose,
            });
            WebCore.CreateWebSession(new WebPreferences()
            {
                CustomCSS = "::-webkit-scrollbar { visibility: hidden; }"
            });


            var webView = WebCore.CreateWebView(800, 600);

            webView.IsTransparent = true;
            webView.Source        = new Uri("http://google.com");

            webView.LoadingFrameComplete += (s, e) =>
            {
                Console.WriteLine(String.Format("Frame Loaded: {0}", e.FrameId));

                // The main frame usually finishes loading last for a given page load.
                if (!e.IsMainFrame)
                {
                    return;
                }

                // Print some more information.
                Console.WriteLine(String.Format("Page Title: {0}", webView.Title));
                Console.WriteLine(String.Format("Loaded URL: {0}", webView.Source));

                // Take snapshots of the page.
                //TakeSnapshots((WebView)s);
            };

            WebCore.Run();
            // Initialize GLFW system
            Glfw.Init();

            // Create GLFW window
            var window = Glfw.CreateWindow(800, 600, "OpenCAD", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);

            // Enable the OpenGL context for the current window
            Glfw.MakeContextCurrent(window);

            while (!Glfw.WindowShouldClose(window))
            {
                // Poll GLFW window events
                Glfw.PollEvents();

                // If you press escape the window will close
                if (Glfw.GetKey(window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(window, true);
                }

                // Set OpenGL clear colour to red
                GL.ClearColor(1.0f, 0.0f, 0.0f, 1.0f);

                // Clear the screen
                GL.Clear(ClearBufferMask.ColorBufferBit);


                // Swap the front and back buffer, displaying the scene
                Glfw.SwapBuffers(window);
            }

            // Finally, clean up Glfw, and close the window
            Glfw.Terminate();
        }
Example #20
0
        public override void Run(Size size)
        {
            _gui = _guiManager.Create(size, ViewModel);
            Glfw.Init();
            // Create GLFW window
            _window = Glfw.CreateWindow(size.Width, size.Height, "OpenCAD", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
            Glfw.SetWindowSizeCallback(_window, (wnd, newwidth, newheight) =>
            {
                GL.Viewport(0, 0, newwidth, newheight);
                _gui.Resize(new Size(newwidth, newheight));
            });

            Glfw.SetCursorPosCallback(_window, (wnd, x, y) => _gui.MouseMove(new Point((int)x, (int)y)));
            Glfw.SetWindowFocusCallback(_window, (wnd, focus) => _messageAggregator.Add(new FocusChangedMessage(this, focus)));
            Glfw.SetMouseButtonCallback(_window, OnCbfun);
            // Enable the OpenGL context for the current window
            Glfw.MakeContextCurrent(_window);

            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.VertexArray);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            //var back = new BackgroundRenderer(new GradientBackground(Color.YellowGreen, Color.Blue, Color.Plum, Color.Aquamarine));
            var back = new BackgroundRenderer(new SolidBackground(Color.FromArgb(35, 30, 32)));
            var gui  = new GUIRenderer();

            _modelRenderer = new ModelRenderer();
            _gui.Resize(size);

            while (!Glfw.WindowShouldClose(_window))
            {
                // Poll GLFW window events
                Glfw.PollEvents();

                // If you press escape the window will close
                if (Glfw.GetKey(_window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(_window, true);
                }

                _gui.Update();
                if (_gui.IsDirty)
                {
                    //Console.WriteLine("Dirty");
                    gui.Texture.Update(_gui);
                }
                // Set OpenGL clear colour to red
                GL.ClearColor(1.0f, 0.0f, 0.0f, 1.0f);

                // Clear the screen
                GL.Clear(ClearBufferMask.ColorBufferBit);
                back.Render();

                var model = ViewModel as IHasScenes;
                if (model != null)
                {
                    _modelRenderer.Render(model.CurrentScene);
                }

                //if (CurrentScene != null)
                //{
                //    _modelRenderer.Render(CurrentScene);
                //}

                gui.Render();

                // Swap the front and back buffer, displaying the scene
                Glfw.SwapBuffers(_window);
            }

            // Finally, clean up Glfw, and close the window
            Glfw.Terminate();
        }
Example #21
0
 public KeyAction GetKeyState(Key key) => (KeyAction) Glfw.GetKey(Window.Handle, (int) key);
Example #22
0
        static void Main()
        {
            if (!Glfw.Init())
            {
                Glfw.Terminate();
                throw new Exception("GLFW Failed to Initialize");
            }

            Glfw.WindowHint(WindowAttrib.Resizable, false);

            var window = Glfw.CreateWindow(1024, 768, "Test");

            if (window.Equals(GlfwWindow.Null))
            {
                Glfw.Terminate();
                throw new Exception("GLFW failed to create window");
            }

            Glfw.CenterWindow(window);

            Glfw.MakeContextCurrent(window);

            string glVersion = GL.GetString(StringName.Version);

            Console.WriteLine("OpenGL Version: {0}", glVersion);

            Glfw.SwapInterval(1);

            /* Initialize Rendering Data */
            /* ==================================================================================== */

            float[] renderBuffer =
            {
                0.0f,   0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
                0.5f,  -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
                -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f
            };

            uint vbo = GL.CreateVBO(BufferTarget.ArrayBuffer, renderBuffer, BufferUsageHint.StaticDraw);

            uint vao = GL.GenVertexArray();

            GL.BindVertexArray(vao);

            GL.EnableVertexAttribArray(0);
            GL.EnableVertexAttribArray(1);

            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);

            int stride = 6 * sizeof(float);

            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, stride, IntPtr.Zero);
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, stride, new IntPtr(3 * sizeof(float)));

            string vertexShaderSrc = @"
                
                #version 400

                layout(location = 0) in vec3 vertexPos;
                layout(location = 1) in vec3 vertexColor;

                out vec3 fragmentColor;

                void main() {
                
                    gl_Position = vec4(vertexPos, 1.0);

                    fragmentColor = vertexColor;

                }                

            ";

            string fragShaderSrc = @"
                
                #version 400

                in vec3 fragmentColor;
                
                out vec4 finalColor;

                void main() {

                    finalColor = vec4(fragmentColor, 1.0);            

                }
    
            ";


            uint vShader = GL.CreateShader(ShaderType.VertexShader);

            GL.ShaderSource(vShader, vertexShaderSrc);

            GL.CompileShader(vShader);

            string log = GL.GetShaderInfoLog(vShader);

            if (!string.IsNullOrEmpty(log))
            {
                throw new Exception("Error on Vertex Shader: " + log);
            }

            uint fShader = GL.CreateShader(ShaderType.FragmentShader);

            GL.ShaderSource(fShader, fragShaderSrc);

            GL.CompileShader(fShader);

            log = GL.GetShaderInfoLog(fShader);

            if (!string.IsNullOrEmpty(log))
            {
                throw new Exception("Error on Fragment Shader: " + log);
            }

            uint shaderProg = GL.CreateProgram();

            GL.AttachShader(shaderProg, vShader);
            GL.AttachShader(shaderProg, fShader);

            GL.LinkProgram(shaderProg);

            /* ==================================================================================== */

            while (!Glfw.WindowShouldClose(window))
            {
                Glfw.PollEvents();

                if (Glfw.GetKey(window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(window, true);
                }

                GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                GL.Clear(ClearBufferMask.ColorBufferBit);

                /* DRAW TRIANGLE */

                GL.UseProgram(shaderProg);

                GL.BindVertexArray(vao);

                GL.DrawArrays(BeginMode.Triangles, 0, 3);

                GL.UseProgram(0);

                Glfw.SwapBuffers(window);
            }

            GL.DeleteShader(vShader);
            GL.DeleteShader(fShader);
            GL.DeleteBuffer(vbo);
            GL.DeleteVertexArray(vao);

            Glfw.DestroyWindow(window);
            Glfw.Terminate();
        }
Example #23
0
 public bool GetKey(Key key)
 {
     return(Glfw.GetKey(window, (int)key) == (int)State.True);
 }
Example #24
0
        // the pragram starts here
        private static void AppMain()
        {
            // initialize GLFW
            if (!Glfw.Init())
            {
                throw new Exception("glfwInit failed");
            }

            // open a window with GLFW
            Glfw.WindowHint(WindowHint.OpenGLProfile, (int)OpenGLProfile.Core);
            Glfw.WindowHint(WindowHint.ContextVersionMajor, 3);
            Glfw.WindowHint(WindowHint.ContextVersionMinor, 2);
            _window = Glfw.CreateWindow(ScreenSize.X, ScreenSize.Y, "", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
            if (_window.Equals(GlfwWindowPtr.Null))
            {
                throw new Exception("glfwOpenWindow failed. Can your hardware handle OpenGL 3.2?");
            }
            Glfw.MakeContextCurrent(_window);

            // GLFW settings
            Glfw.SetInputMode(_window, InputMode.CursorMode, CursorMode.CursorHidden | CursorMode.CursorCaptured);
            Glfw.SetCursorPos(_window, 0, 0);
            Glfw.SetScrollCallback(_window, new GlfwScrollFun((win, x, y) => {
                //increase or decrease field of view based on mouse wheel
                float zoomSensitivity = -0.2f;
                float fieldOfView     = _gCamera.FieldOfView + zoomSensitivity * (float)y;
                if (fieldOfView < 5.0f)
                {
                    fieldOfView = 5.0f;
                }
                if (fieldOfView > 130.0f)
                {
                    fieldOfView = 130.0f;
                }
                _gCamera.FieldOfView = fieldOfView;
            }));

            // TODO: GLEW in C#

            // print out some info about the graphics drivers
            Console.WriteLine("OpenGL version: {0}", GL.GetString(StringName.Version));
            Console.WriteLine("GLSL version: {0}", GL.GetString(StringName.ShadingLanguageVersion));
            Console.WriteLine("Vendor: {0}", GL.GetString(StringName.Vendor));
            Console.WriteLine("Renderer: {0}", GL.GetString(StringName.Renderer));

            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);

            // load vertex and fragment shaders into opengl
            LoadShaders();

            // load the texture
            LoadTexture();

            // create buffer and fill it with the points of the triangle
            LoadCube();

            _gCamera.Position            = new Vector3(0, 0, 4);
            _gCamera.ViewportAspectRatio = (float)ScreenSize.X / (float)ScreenSize.Y;

            double lastTime = Glfw.GetTime();

            // run while window is open
            while (!Glfw.WindowShouldClose(_window))
            {
                // update the scene based on the time elapsed since last update
                double thisTime = Glfw.GetTime();
                Update(thisTime - lastTime);
                lastTime = thisTime;

                // draw one frame
                Render();
                //exit program if escape key is pressed
                if (Glfw.GetKey(_window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(_window, true);
                }
            }

            // clean up and exit
            Glfw.Terminate();
        }
Example #25
0
        public bool IsKeyPressed(KeyCode key)
        {
            InputState state = Glfw.GetKey(window, (Keys)key);

            return(state == InputState.Press || state == InputState.Repeat);
        }
Example #26
0
        internal static void Update()              //TODO rewrite
        {
            bool[] nowButtons = GetMouseButtons(); // [0]-left [1]-right [2]-middle [3]-4th mouse button [4]-5th mouse button.....

            if (mouseLeftButton)
            {
                MouseLeftButtonClick = false;
            }
            else if (nowButtons[0])
            {
                MouseLeftButtonClick = true;
            }

            if (mouseRightButton)
            {
                MouseRightButtonClick = false;
            }
            else if (nowButtons[1])
            {
                MouseRightButtonClick = true;
            }

            if (mouseMiddleButton)
            {
                MouseMiddleButtonClick = false;
            }
            else if (nowButtons[2])
            {
                MouseMiddleButtonClick = true;
            }

            mouseLeftButton   = nowButtons[0];
            mouseRightButton  = nowButtons[1];
            mouseMiddleButton = nowButtons[2];

            for (short i = 0; i < MouseButtons.Length; ++i)
            {
                int mouse = Glfw.GetMouseButton(Engine.MainWindow.GlfwWindow, i);
                if (mouse == Glfw.PRESS)
                {
                    if (MouseButtons[i] != KeyState.Pressed)
                    {
                        foreach (KeyValuePair <int, MouseEventFunc> pair in mouseEvents)
                        {
                            if (pair.Value != null && pair.Value.Invoke(GetMousePosition(), i, KeyState.Pressed))
                            {
                                clickReceiver = pair.Value;
                                break;
                            }
                        }
                    }
                    MouseButtons[i] = KeyState.Pressed;
                }
                else if (mouse == Glfw.RELEASE)
                {
                    if (MouseButtons[i] == KeyState.Pressed)
                    {
                        foreach (KeyValuePair <int, MouseEventFunc> pair in mouseEvents)
                        {
                            Vector2 mousePos = GetMousePosition();

                            if (pair.Value != null && pair.Value.Invoke(mousePos, i, KeyState.Released))
                            {
                                if (clickReceiver != null && clickReceiver == pair.Value)
                                {
                                    clickReceiver(mousePos, i, KeyState.Clicked);
                                }
                            }
                        }
                        clickReceiver   = null;
                        MouseButtons[i] = KeyState.Clicked;
                    }
                    else if (MouseButtons[i] == KeyState.Clicked)
                    {
                        MouseButtons[i] = KeyState.Released;
                    }
                }
            }

            for (short i = 0; i < Keys.Length; ++i)
            {
                int key = Glfw.GetKey(Engine.MainWindow.GlfwWindow, i);
                if (key == Glfw.PRESS)
                {
                    Keys[i] = KeyState.Pressed;
                }
                else if (key == Glfw.RELEASE)
                {
                    if (Keys[i] == KeyState.Pressed)
                    {
                        Keys[i] = KeyState.Clicked;
                    }
                    else if (Keys[i] == KeyState.Clicked)
                    {
                        Keys[i] = KeyState.Released;
                    }
                }
            }

            UpdateActions();
        }
Example #27
0
        // update the scene based on the time elapsed since last update
        private static void Update(float secondsElapsed)
        {
            //rotate the first instance in `gInstances`
            float degreesPerSecond = 180.0f;

            _gDegreesRotated += secondsElapsed * degreesPerSecond;
            while (_gDegreesRotated > 360.0f)
            {
                _gDegreesRotated -= 360.0f;
            }
            _gInstances[0].Transform = Matrix.CreateFromAxisAngle(new Vector3(0, 1, 0), _gDegreesRotated);

            //move position of camera based on WASD keys, and XZ keys for up and down
            float moveSpeed = 4.0f; //units per second

            if (Glfw.GetKey(_window, Key.S))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -_gCamera.Forward);
            }
            else if (Glfw.GetKey(_window, Key.W))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * _gCamera.Forward);
            }
            if (Glfw.GetKey(_window, Key.A))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -_gCamera.Right);
            }
            else if (Glfw.GetKey(_window, Key.D))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * _gCamera.Right);
            }
            if (Glfw.GetKey(_window, Key.Z))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * -new Vector3(0, 1, 0));
            }
            else if (Glfw.GetKey(_window, Key.X))
            {
                _gCamera.OffsetPosition((float)secondsElapsed * moveSpeed * new Vector3(0, 1, 0));
            }

            if (Glfw.GetKey(_window, Key.One))
            {
                _gLight.Position = _gCamera.Position;
            }

            if (Glfw.GetKey(_window, Key.Two))
            {
                _gLight.Intensities = new Vector3(1, 0, 0); // red
            }
            else if (Glfw.GetKey(_window, Key.Three))
            {
                _gLight.Intensities = new Vector3(0, 1, 0); //green
            }
            else if (Glfw.GetKey(_window, Key.Four))
            {
                _gLight.Intensities = new Vector3(1, 1, 1); //white
            }
            //rotate camera based on mouse movement
            float  mouseSensitivity = 0.1f;
            double mouseX, mouseY;

            Glfw.GetCursorPos(_window, out mouseX, out mouseY);
            _gCamera.OffsetOrientation(mouseSensitivity * (float)mouseY, mouseSensitivity * (float)mouseX);
            Glfw.SetCursorPos(_window, 0, 0); //reset the mouse, so it doesn't go out of the window
        }
Example #28
0
        private static void Main()
        {
            if (!Glfw.Init())
            {
                Environment.Exit(-1);
            }

            Glfw.WindowHint(Glfw.Hint.Resizable, false);
            Glfw.WindowHint(Glfw.Hint.Doublebuffer, true);
            Glfw.WindowHint(Glfw.Hint.Samples, 4);
            Glfw.Window window = Glfw.CreateWindow(1280, 720, "Hello World!");

            if (!window)
            {
                Glfw.Terminate();
                Environment.Exit(-1);
            }

            Gl.Initialize();
            Glfw.MakeContextCurrent(window);

            Gl.Enable(EnableCap.Multisample);
            Gl.Enable(EnableCap.Texture2d);
            Gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
            Gl.Enable(EnableCap.Blend);

            System.Diagnostics.Trace.TraceInformation($"Renderer: {Gl.GetString(StringName.Renderer)}");
            System.Diagnostics.Trace.TraceInformation($"Version:  {Gl.GetString(StringName.Version)}");

            uint vao = Gl.GenVertexArray();

            Gl.BindVertexArray(vao);

            float[] points =
            {
                // Pos              color           tex
                -0.5f,  0.5f, 0f, 1f, 1f, 1f, 0f, 0f,
                0.5f,   0.5f, 0f, 1f, 1f, 1f, 1f, 0f,
                0.5f,  -0.5f, 0f, 1f, 1f, 1f, 1f, 1f,
                -0.5f, -0.5f, 0f, 1f, 1f, 1f, 0f, 1f,

                0f,       0f, 0f, 1f, 1f, 1f, 0f, 0f,
                1f,       0f, 0f, 1f, 1f, 1f, 1f, 0f,
                1f,      -1f, 0f, 1f, 1f, 1f, 1f, 1f,
                0f,      -1f, 0f, 1f, 1f, 1f, 0f, 1f
            };
            uint buffer = Gl.GenBuffer();

            Gl.BindBuffer(BufferTarget.ArrayBuffer, buffer);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)points.Length * 4, points, BufferUsage.StaticDraw);

            uint[] elements =
            {
                0, 1, 2,
                2, 3, 0,

                4, 5, 6,
                6, 7, 4
            };
            uint ebo = Gl.GenBuffer();

            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, ebo);
            Gl.BufferData(BufferTarget.ElementArrayBuffer, (uint)elements.Length * 4, elements, BufferUsage.StaticDraw);

            uint texture = Gl.CreateTexture(TextureTarget.Texture2d);
            {
                Gl.BindTexture(TextureTarget.Texture2d, texture);
                using (var image = new System.Drawing.Bitmap(".\\resources\\textures\\dirt.png")) {
                    System.Drawing.Imaging.BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    Gl.TexImage2D(TextureTarget.Texture2d, 0, InternalFormat.Rgba, data.Width, data.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
                    image.UnlockBits(data);
                }
                Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, Gl.NEAREST);
                Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, Gl.NEAREST);
            }

            ShaderProgram program;

            using (var vertexShader = Shader.FromFile(".\\src\\shaders\\SimpleVertexShader.vert", ShaderType.VertexShader))
                using (var fragmentShader = Shader.FromFile(".\\src\\shaders\\SimpleFragmentShader.frag", ShaderType.FragmentShader)) {
                    program = new ShaderProgram(
                        new[] { vertexShader, fragmentShader },
                        new string[] { "model", "projection" },
                        new[] { "position", "color", "texcoord" }
                        );
                }
            program.Use();

            var posAttrib = (uint)program.Attributes["position"];

            Gl.EnableVertexAttribArray(posAttrib);
            Gl.VertexAttribPointer(posAttrib, 3, VertexAttribType.Float, false, 8 * 4, IntPtr.Zero);
            var colAttrib = (uint)program.Attributes["color"];

            Gl.EnableVertexAttribArray(colAttrib);
            Gl.VertexAttribPointer(colAttrib, 3, VertexAttribType.Float, false, 8 * 4, new IntPtr(3 * 4));
            var texAttrib = (uint)program.Attributes["texcoord"];

            Gl.EnableVertexAttribArray(texAttrib);
            Gl.VertexAttribPointer(texAttrib, 2, VertexAttribType.Float, false, 8 * 4, new IntPtr(6 * 4));

            // var modelView = Matrix4x4f.Translated(0f, 0f, 0f);
            // var projection = Matrix4x4d.Ortho2D(-1f, 1f, -1f, 1f);
            // var modelAttrib = Gl.GetAttribLocation(programId, "model");

            //var viewAttrib = Gl.GetAttribLocation(programId, "view");
            //Gl.UniformMatrix4f(viewAttrib, 1, false, ref view);

            // var projectionAttrib = Gl.GetAttribLocation(programId, "projection");
            // Gl.UniformMatrix4f(projectionAttrib, 1, false, projection);

            while (!Glfw.WindowShouldClose(window))
            {
                Gl.ClearColor(1.0f, 0.0f, 1.0f, 1.0f);
                Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                // Gl.UniformMatrix4f(modelAttrib, 1, false, projection * modelView);
                Gl.DrawElements(PrimitiveType.Triangles, elements.Length, DrawElementsType.UnsignedInt, IntPtr.Zero);

                Glfw.SwapBuffers(window);

                Glfw.PollEvents();
                if (Glfw.GetKey(window, (int)Glfw.KeyCode.Escape))
                {
                    Glfw.SetWindowShouldClose(window, true);
                }
            }

            Console.WriteLine("Exiting...");

            Gl.DeleteBuffers(buffer);
            Gl.DeleteVertexArrays(vao);

            Glfw.Terminate();
        }
Example #29
0
        // the pragram starts here
        private static void AppMain()
        {
            // initialize GLFW
            if (!Glfw.Init())
            {
                throw new Exception("glfwInit failed");
            }

            // open a window with GLFW
            Glfw.WindowHint(WindowHint.OpenGLProfile, (int)OpenGLProfile.Core);
            Glfw.WindowHint(WindowHint.ContextVersionMajor, 3);
            Glfw.WindowHint(WindowHint.ContextVersionMinor, 2);
            _window = Glfw.CreateWindow(ScreenSize.X, ScreenSize.Y, "", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
            if (_window.Equals(GlfwWindowPtr.Null))
            {
                throw new Exception("glfwOpenWindow failed. Can your hardware handle OpenGL 3.2?");
            }
            Glfw.MakeContextCurrent(_window);

            // GLFW settings
            Glfw.SetInputMode(_window, InputMode.CursorMode, CursorMode.CursorHidden | CursorMode.CursorCaptured);
            Glfw.SetCursorPos(_window, 0, 0);
            Glfw.SetScrollCallback(_window, new GlfwScrollFun((win, x, y) => {
                //increase or decrease field of view based on mouse wheel
                float zoomSensitivity = -0.2f;
                float fieldOfView     = _gCamera.FieldOfView + zoomSensitivity * (float)y;
                if (fieldOfView < 5.0f)
                {
                    fieldOfView = 5.0f;
                }
                if (fieldOfView > 130.0f)
                {
                    fieldOfView = 130.0f;
                }
                _gCamera.FieldOfView = fieldOfView;
            }));

            // TODO: GLEW in C#

            // print out some info about the graphics drivers
            Console.WriteLine("OpenGL version: {0}", GL.GetString(StringName.Version));
            Console.WriteLine("GLSL version: {0}", GL.GetString(StringName.ShadingLanguageVersion));
            Console.WriteLine("Vendor: {0}", GL.GetString(StringName.Vendor));
            Console.WriteLine("Renderer: {0}", GL.GetString(StringName.Renderer));

            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);

            // initialise the gWoodenCrate asset
            LoadWoodenCrateAsset();

            // create all the instances in the 3D scene based on the gWoodenCrate asset
            CreateInstances();

            _gCamera.Position            = new Vector3(-4, 0, 17);
            _gCamera.ViewportAspectRatio = (float)ScreenSize.X / (float)ScreenSize.Y;
            _gCamera.SetNearAndFarPlanes(0.5f, 100.0f);

            // setup light
            _gLight = new Light()
            {
                Position           = _gCamera.Position,
                Intensities        = new Vector3(1, 1, 1), // white
                Attenuation        = 0.2f,
                AmbientCoefficient = 0.005f
            };

            float lastTime = (float)Glfw.GetTime();

            // run while window is open
            while (!Glfw.WindowShouldClose(_window))
            {
                // update the scene based on the time elapsed since last update
                float thisTime = (float)Glfw.GetTime();
                Update(thisTime - lastTime);
                lastTime = thisTime;

                // draw one frame
                Render();
                //exit program if escape key is pressed
                if (Glfw.GetKey(_window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(_window, true);
                }
            }

            // clean up and exit
            Glfw.Terminate();
        }
Example #30
0
 public static bool GetKeyDown(int key)
 {
     /* Debug.Assert(Program.window != null); */
     return(Glfw.GetKey(Program.window, key) == GLFW_PRESS);
 }