Convert Figma logo to code with AI

go-gl logoglfw

Go bindings for GLFW 3

1,559
182
1,559
23

Top Related Projects

12,827

A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input

2,197

SDL2 binding for Go

10,770

Ebitengine - A dead simple 2D game engine for Go

4,448

A hand-crafted 2D game library in Go

10,442

Qt binding for Go (Golang) with support for Windows / macOS / Linux / FreeBSD / Android / iOS / Sailfish OS / Raspberry Pi / AsteroidOS / Ubuntu Touch / JavaScript / WebAssembly

Quick Overview

go-gl/glfw is a Go binding for GLFW, a multi-platform library for creating windows, contexts, and handling input for OpenGL, OpenGL ES, and Vulkan applications. It provides a simple API for creating and managing windows, handling user input, and managing OpenGL contexts, making it easier to develop cross-platform graphics applications in Go.

Pros

  • Cross-platform compatibility (Windows, macOS, Linux)
  • Easy-to-use API for window management and input handling
  • Seamless integration with OpenGL and Vulkan
  • Active community and regular updates

Cons

  • Limited to desktop platforms (no mobile support)
  • Requires C dependencies (GLFW library)
  • May have performance overhead compared to native implementations
  • Learning curve for developers new to graphics programming

Code Examples

  1. Creating a window:
package main

import (
    "github.com/go-gl/glfw/v3.3/glfw"
)

func main() {
    if err := glfw.Init(); err != nil {
        panic(err)
    }
    defer glfw.Terminate()

    window, err := glfw.CreateWindow(640, 480, "My Window", nil, nil)
    if err != nil {
        panic(err)
    }

    window.MakeContextCurrent()

    for !window.ShouldClose() {
        glfw.PollEvents()
        window.SwapBuffers()
    }
}
  1. Handling keyboard input:
window.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
    if key == glfw.KeyEscape && action == glfw.Press {
        w.SetShouldClose(true)
    }
})
  1. Setting up OpenGL context:
glfw.WindowHint(glfw.ContextVersionMajor, 3)
glfw.WindowHint(glfw.ContextVersionMinor, 3)
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

window, err := glfw.CreateWindow(640, 480, "OpenGL Window", nil, nil)
if err != nil {
    panic(err)
}

Getting Started

  1. Install Go and set up your Go workspace.
  2. Install the GLFW library for your platform (e.g., sudo apt-get install libglfw3-dev on Ubuntu).
  3. Install the Go binding:
    go get -u github.com/go-gl/glfw/v3.3/glfw
    
  4. Import the package in your Go code:
    import "github.com/go-gl/glfw/v3.3/glfw"
    
  5. Initialize GLFW and create a window as shown in the first code example above.

Competitor Comparisons

12,827

A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input

Pros of GLFW

  • Original C implementation, providing direct access to GLFW functionality
  • Wider platform support, including Windows, macOS, Linux, and more
  • More frequent updates and active development

Cons of GLFW

  • Requires C knowledge and manual memory management
  • Less idiomatic for Go developers
  • May require additional bindings or wrappers for Go integration

Code Comparison

GLFW (C):

#include <GLFW/glfw3.h>

int main(void) {
    GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL);
    glfwMakeContextCurrent(window);
}

go-gl/glfw (Go):

import "github.com/go-gl/glfw/v3.3/glfw"

func main() {
    window, _ := glfw.CreateWindow(640, 480, "My Title", nil, nil)
    window.MakeContextCurrent()
}

Summary

GLFW is the original C library, offering broader platform support and more frequent updates. However, it requires C knowledge and may be less convenient for Go developers. go-gl/glfw provides a Go-specific wrapper, making it more idiomatic and easier to use in Go projects, but may lag behind in features and updates compared to the original GLFW library.

2,197

SDL2 binding for Go

Pros of SDL2

  • More comprehensive multimedia library, offering audio, input handling, and 2D rendering capabilities
  • Cross-platform support for a wider range of systems, including mobile platforms
  • Extensive documentation and large community support

Cons of SDL2

  • Larger library size and potentially more complex setup compared to GLFW
  • May have slightly higher overhead for simple windowing tasks
  • Less focused on OpenGL, which could be a drawback for specific OpenGL-centric projects

Code Comparison

SDL2 window creation:

window, err := sdl.CreateWindow("SDL2 Window", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
    800, 600, sdl.WINDOW_SHOWN)
if err != nil {
    panic(err)
}
defer window.Destroy()

GLFW window creation:

if err := glfw.Init(); err != nil {
    panic(err)
}
defer glfw.Terminate()
window, err := glfw.CreateWindow(800, 600, "GLFW Window", nil, nil)
if err != nil {
    panic(err)
}

Both libraries provide straightforward window creation, but SDL2 offers more built-in functionality for multimedia applications, while GLFW is more focused on providing a simple, lightweight solution for OpenGL context creation and basic windowing.

10,770

Ebitengine - A dead simple 2D game engine for Go

Pros of Ebiten

  • Higher-level API, simplifying game development
  • Cross-platform support, including mobile and web
  • Built-in game loop and input handling

Cons of Ebiten

  • Less flexibility for low-level graphics programming
  • Potentially higher resource usage due to abstraction layer
  • Limited to 2D graphics (as of the latest stable version)

Code Comparison

Ebiten (game loop):

func (g *Game) Update() error {
    // Update game logic here
    return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
    // Draw game elements here
}

GLFW (window creation and main loop):

window, err := glfw.CreateWindow(640, 480, "My Window", nil, nil)
if err != nil {
    panic(err)
}

for !window.ShouldClose() {
    // Main loop logic here
    window.SwapBuffers()
    glfw.PollEvents()
}

GLFW provides a lower-level interface for window management and OpenGL context creation, while Ebiten offers a more game-oriented API with built-in game loop and drawing functions. Ebiten simplifies 2D game development, whereas GLFW gives more control over the graphics pipeline and is suitable for both 2D and 3D applications.

4,448

A hand-crafted 2D game library in Go

Pros of Pixel

  • Higher-level abstraction for 2D graphics and game development
  • Simpler API for common game-related tasks like sprite handling and collision detection
  • Built-in support for efficient batch rendering

Cons of Pixel

  • Limited to 2D graphics, while GLFW supports both 2D and 3D
  • Less flexibility for low-level graphics programming
  • Smaller community and ecosystem compared to GLFW

Code Comparison

Pixel example:

win, err := pixelgl.NewWindow(pixelgl.WindowConfig{
    Title:  "Pixel Rocks!",
    Bounds: pixel.R(0, 0, 1024, 768),
})

GLFW example:

if err := glfw.Init(); err != nil {
    panic(err)
}
defer glfw.Terminate()

window, err := glfw.CreateWindow(640, 480, "GLFW Window", nil, nil)

Summary

Pixel is a higher-level 2D graphics library built on top of OpenGL, offering simplified game development features. GLFW, on the other hand, is a lower-level library providing cross-platform OpenGL context creation and input handling. Pixel is more suitable for 2D game development, while GLFW offers greater flexibility for both 2D and 3D graphics programming.

10,442

Qt binding for Go (Golang) with support for Windows / macOS / Linux / FreeBSD / Android / iOS / Sailfish OS / Raspberry Pi / AsteroidOS / Ubuntu Touch / JavaScript / WebAssembly

Pros of Qt

  • Comprehensive GUI toolkit with a wide range of widgets and controls
  • Cross-platform support for desktop and mobile applications
  • Rich set of tools for application development, including Qt Creator IDE

Cons of Qt

  • Larger learning curve due to its extensive feature set
  • Heavier resource usage compared to GLFW's lightweight approach
  • Licensing considerations for commercial applications

Code Comparison

GLFW (OpenGL window creation):

window, err := glfw.CreateWindow(640, 480, "GLFW Window", nil, nil)
if err != nil {
    panic(err)
}

Qt (QWidget-based window creation):

app := widgets.NewQApplication(len(os.Args), os.Args)
window := widgets.NewQMainWindow(nil, 0)
window.SetGeometry2(100, 100, 300, 200)
window.SetWindowTitle("Qt Window")
window.Show()

Summary

GLFW is a lightweight library focused on creating windows with OpenGL contexts, while Qt is a comprehensive framework for building cross-platform applications with rich GUI components. GLFW is simpler to use for basic graphics applications, while Qt offers more features for complex GUI development but requires more learning and resources.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GLFW 3.3 for Go Build Status GoDoc

Installation

  • GLFW C library source is included and built automatically as part of the Go package. But you need to make sure you have dependencies of GLFW:
    • On macOS, you need Xcode or Command Line Tools for Xcode (xcode-select --install) for required headers and libraries.
    • On Ubuntu/Debian-like Linux distributions, you need libgl1-mesa-dev and xorg-dev packages.
    • On CentOS/Fedora-like Linux distributions, you need libX11-devel libXcursor-devel libXrandr-devel libXinerama-devel mesa-libGL-devel libXi-devel libXxf86vm-devel packages.
    • On FreeBSD, you need the package pkgconf. To build for X, you also need the package xorg; and to build for Wayland, you need the package wayland.
    • On NetBSD, to build for X, you need the X11 sets installed. These are included in all graphical installs, and can be added to the system with sysinst(8) on non-graphical systems. Wayland support is incomplete, due to missing wscons support in upstream GLFW. To attempt to build for Wayland, you need to install the wayland libepoll-shim packages and set the environment variable PKG_CONFIG_PATH=/usr/pkg/libdata/pkgconfig.
    • On OpenBSD, you need the X11 sets. These are installed by default, and can be added from the ramdisk kernel at any time.
    • See here for full details.
  • Go 1.4+ is required on Windows (otherwise you must use MinGW v4.8.1 exactly, see Go issue 8811).
go get -u github.com/go-gl/glfw/v3.3/glfw

OpenGL ES

If your target system only provides an OpenGL ES implementation (true for some ARM boards), you need to link against that implementation. You do this by defining the appropriate build tags, e.g.

go get -u -tags=gles2 github.com/go-gl/glfw/v3.3/glfw

Supported tags are gles1, gles2, gles3 and vulkan. Note that required packages might differ from those listed above; consult your hardware's documentation.

Usage

package main

import (
	"runtime"
	"github.com/go-gl/glfw/v3.3/glfw"
)

func init() {
	// This is needed to arrange that main() runs on main thread.
	// See documentation for functions that are only allowed to be called from the main thread.
	runtime.LockOSThread()
}

func main() {
	err := glfw.Init()
	if err != nil {
		panic(err)
	}
	defer glfw.Terminate()

	window, err := glfw.CreateWindow(640, 480, "Testing", nil, nil)
	if err != nil {
		panic(err)
	}

	window.MakeContextCurrent()

	for !window.ShouldClose() {
		// Do OpenGL stuff.
		window.SwapBuffers()
		glfw.PollEvents()
	}
}

Changelog

GLFW 3.3 Specific Changes

  • Joystick functions now uses receivers instead of passing the joystick ID as argument.
  • Vulkan methods are intentionally not implemented. Window.Handle can be used to create a Vulkan surface via the this package.
  • Renamed Window.GLFWWindow to Window.Handle
  • Added function Window.SetAttrib.
  • Added function Window.RequestAttention.
  • Added function Window.GetContentScale.
  • Added function Window.GetOpacity.
  • Added function Window.SetOpacity.
  • Added function Window.SetMaximizeCallback.
  • Added function Window.SetContentScaleCallback.
  • Added function Monitor.GetWorkarea.
  • Added function Monitor.GetContentScale.
  • Added function Monitor.SetUserPointer.
  • Added function Monitor.GetUserPointer.
  • Added function InitHint.
  • Added function RawMouseMotionSupported
  • Added function GetKeyScancode.
  • Added function WindowHintString.
  • Added function GetClipboardString.
  • Added function SetClipboardString.
  • Added function Joystick.GetHats.
  • Added function Joystick.IsGamepad.
  • Added function Joystick.GetGUID.
  • Added function Joystick.GetGamepadName.
  • Added function Joystick.GetGamepadState.
  • Added function Joystick.SetUserPointer.
  • Added function Joystick.GetUserPointer.
  • Added function UpdateGamepadMappings.
  • Added function SetX11SelectionString.
  • Added function GetX11SelectionString.
  • Added gamepad button IDs.
  • Added gamepad axis IDs.
  • Added joystick hat state IDs.
  • Added ModifierKey ModCapsLock.
  • Added ModifierKey ModNumLock
  • Added InputMode LockKeyMods.
  • Added InputMode RawMouseMotion.
  • Added hint Hovered.
  • Added hint CenterCursor.
  • Added hint TransparentFramebuffer.
  • Added hint FocusOnShow.
  • Added hint ScaleToMonitor.
  • Added hint JoystickHatButtons.
  • Added hint CocoaChdirResources.
  • Added hint CocoaMenubar.
  • Added hint TransparentFramebuffer.
  • Added hint value OSMesaContextAPI.
  • Added hint value CocoaGraphicsSwitching.
  • Added hint value CocoaRetinaFramebuffer.
  • Added string hint value CocoaFrameNAME.
  • Added string hint value X11ClassName.
  • Added string hint value X11InstanceName.
  • MonitorEvent renamed to PeripheralEvent for reuse with joystick events.
  • Joystick.GetButtons Returns []Action instead of []byte.
  • SetMonitorCallback Returns MonitorCallback.
  • Focus No longer returns an error.
  • Iconify No longer returns an error.
  • Maximize No longer returns an error.
  • Restore No longer returns an error.
  • GetClipboardString No longer returns an error.

GLFW 3.2 Specfic Changes

  • Easy go get installation. GLFW source code is now included in-repo and compiled in so you don't have to build GLFW on your own and distribute shared libraries. The revision of GLFW C library used is listed in GLFW_C_REVISION.txt file.
  • The error callback is now set internally. Functions return an error with corresponding code and description (do a type assertion to glfw3.Error for accessing the variables) if the error is recoverable. If not a panic will occur.
  • Added function Window.SetSizeLimits.
  • Added function Window.SetAspectRatio.
  • Added function Window.SetMonitor.
  • Added function Window.Maximize.
  • Added function Window.SetIcon.
  • Added function Window.Focus.
  • Added function GetKeyName.
  • Added function VulkanSupported.
  • Added function GetTimerValue.
  • Added function GetTimerFrequency.
  • Added function WaitEventsTimeout.
  • Added function SetJoystickCallback.
  • Added window hint Maximized.
  • Added hint NoAPI.
  • Added hint NativeContextAPI.
  • Added hint EGLContextAPI.

GLFW 3.1 Specfic Changes

  • Added type Cursor.
  • Added function Window.SetDropCallback.
  • Added function Window.SetCharModsCallback.
  • Added function PostEmptyEvent.
  • Added function CreateCursor.
  • Added function CreateStandardCursor.
  • Added function Cursor.Destroy.
  • Added function Window.SetCursor.
  • Added function Window.GetFrameSize.
  • Added window hint Floating.
  • Added window hint AutoIconify.
  • Added window hint ContextReleaseBehavior.
  • Added window hint DoubleBuffer.
  • Added hint value AnyReleaseBehavior.
  • Added hint value ReleaseBehaviorFlush.
  • Added hint value ReleaseBehaviorNone.
  • Added hint value DontCare.

API changes

  • Window.Iconify Returns an error.
  • Window.Restore Returns an error.
  • Init Returns an error instead of bool.
  • GetJoystickAxes No longer returns an error.
  • GetJoystickButtons No longer returns an error.
  • GetJoystickName No longer returns an error.
  • GetMonitors No longer returns an error.
  • GetPrimaryMonitor No longer returns an error.
  • Monitor.GetGammaRamp No longer returns an error.
  • Monitor.GetVideoMode No longer returns an error.
  • Monitor.GetVideoModes No longer returns an error.
  • GetCurrentContext No longer returns an error.
  • Window.SetCharCallback Accepts rune instead of uint.
  • Added type Error.
  • Removed SetErrorCallback.
  • Removed error code NotInitialized.
  • Removed error code NoCurrentContext.
  • Removed error code InvalidEnum.
  • Removed error code InvalidValue.
  • Removed error code OutOfMemory.
  • Removed error code PlatformError.
  • Removed KeyBracket.
  • Renamed Window.SetCharacterCallback to Window.SetCharCallback.
  • Renamed Window.GetCursorPosition to GetCursorPos.
  • Renamed Window.SetCursorPosition to SetCursorPos.
  • Renamed CursorPositionCallback to CursorPosCallback.
  • Renamed Window.SetCursorPositionCallback to SetCursorPosCallback.
  • Renamed VideoMode to VidMode.
  • Renamed Monitor.GetPosition to Monitor.GetPos.
  • Renamed Window.GetPosition to Window.GetPos.
  • Renamed Window.SetPosition to Window.SetPos.
  • Renamed Window.GetAttribute to Window.GetAttrib.
  • Renamed Window.SetPositionCallback to Window.SetPosCallback.
  • Renamed PositionCallback to PosCallback.
  • Ranamed Cursor to CursorMode.
  • Renamed StickyKeys to StickyKeysMode.
  • Renamed StickyMouseButtons to StickyMouseButtonsMode.
  • Renamed ApiUnavailable to APIUnavailable.
  • Renamed ClientApi to ClientAPI.
  • Renamed OpenglForwardCompatible to OpenGLForwardCompatible.
  • Renamed OpenglDebugContext to OpenGLDebugContext.
  • Renamed OpenglProfile to OpenGLProfile.
  • Renamed SrgbCapable to SRGBCapable.
  • Renamed OpenglApi to OpenGLAPI.
  • Renamed OpenglEsApi to OpenGLESAPI.
  • Renamed OpenglAnyProfile to OpenGLAnyProfile.
  • Renamed OpenglCoreProfile to OpenGLCoreProfile.
  • Renamed OpenglCompatProfile to OpenGLCompatProfile.
  • Renamed KeyKp... to KeyKP....