From 77aeccf1b006c31a69801ccb778e834853d6fea6 Mon Sep 17 00:00:00 2001 From: Geoffrey Casper Date: Sat, 4 May 2024 08:54:13 -0400 Subject: [PATCH] v3.3 copy - starting point --- v3.4/glfw/GLFW_C_REVISION.txt | 1 + v3.4/glfw/build.go | 53 ++ v3.4/glfw/build_cgo_hack.go | 19 + v3.4/glfw/c_glfw.go | 12 + v3.4/glfw/c_glfw_bsd.go | 30 + v3.4/glfw/c_glfw_darwin.go | 14 + v3.4/glfw/c_glfw_lin.go | 30 + v3.4/glfw/c_glfw_windows.go | 13 + v3.4/glfw/context.go | 94 +++ v3.4/glfw/error.c | 3 + v3.4/glfw/error.go | 203 +++++ v3.4/glfw/glfw.go | 118 +++ v3.4/glfw/glfw_tree_rebuild.go | 10 + v3.4/glfw/go.mod | 3 + v3.4/glfw/input.c | 49 ++ v3.4/glfw/input.go | 955 +++++++++++++++++++++++ v3.4/glfw/monitor.c | 19 + v3.4/glfw/monitor.go | 267 +++++++ v3.4/glfw/native_darwin.go | 40 + v3.4/glfw/native_linbsd_wayland.go | 48 ++ v3.4/glfw/native_linbsd_x11.go | 67 ++ v3.4/glfw/native_windows.go | 36 + v3.4/glfw/testdata/customcursor/main.go | 55 ++ v3.4/glfw/time.go | 42 + v3.4/glfw/util.go | 46 ++ v3.4/glfw/vulkan.go | 85 ++ v3.4/glfw/window.c | 40 + v3.4/glfw/window.go | 990 ++++++++++++++++++++++++ 28 files changed, 3342 insertions(+) create mode 100644 v3.4/glfw/GLFW_C_REVISION.txt create mode 100644 v3.4/glfw/build.go create mode 100644 v3.4/glfw/build_cgo_hack.go create mode 100644 v3.4/glfw/c_glfw.go create mode 100644 v3.4/glfw/c_glfw_bsd.go create mode 100644 v3.4/glfw/c_glfw_darwin.go create mode 100644 v3.4/glfw/c_glfw_lin.go create mode 100644 v3.4/glfw/c_glfw_windows.go create mode 100644 v3.4/glfw/context.go create mode 100644 v3.4/glfw/error.c create mode 100644 v3.4/glfw/error.go create mode 100644 v3.4/glfw/glfw.go create mode 100644 v3.4/glfw/glfw_tree_rebuild.go create mode 100644 v3.4/glfw/go.mod create mode 100644 v3.4/glfw/input.c create mode 100644 v3.4/glfw/input.go create mode 100644 v3.4/glfw/monitor.c create mode 100644 v3.4/glfw/monitor.go create mode 100644 v3.4/glfw/native_darwin.go create mode 100644 v3.4/glfw/native_linbsd_wayland.go create mode 100644 v3.4/glfw/native_linbsd_x11.go create mode 100644 v3.4/glfw/native_windows.go create mode 100644 v3.4/glfw/testdata/customcursor/main.go create mode 100644 v3.4/glfw/time.go create mode 100644 v3.4/glfw/util.go create mode 100644 v3.4/glfw/vulkan.go create mode 100644 v3.4/glfw/window.c create mode 100644 v3.4/glfw/window.go diff --git a/v3.4/glfw/GLFW_C_REVISION.txt b/v3.4/glfw/GLFW_C_REVISION.txt new file mode 100644 index 00000000..f4510d1a --- /dev/null +++ b/v3.4/glfw/GLFW_C_REVISION.txt @@ -0,0 +1 @@ +dc46d3f8129712e42856c20e99a604a3b08ad581 diff --git a/v3.4/glfw/build.go b/v3.4/glfw/build.go new file mode 100644 index 00000000..14a7ef3e --- /dev/null +++ b/v3.4/glfw/build.go @@ -0,0 +1,53 @@ +package glfw + +/* +// Windows Build Tags +// ---------------- +// GLFW Options: +#cgo windows CFLAGS: -D_GLFW_WIN32 -Iglfw/deps/mingw + +// Linker Options: +#cgo windows LDFLAGS: -lgdi32 + +#cgo !gles2,windows LDFLAGS: -lopengl32 +#cgo gles2,windows LDFLAGS: -lGLESv2 + +// Darwin Build Tags +// ---------------- +// GLFW Options: +#cgo darwin CFLAGS: -D_GLFW_COCOA -Wno-deprecated-declarations + +// Linker Options: +#cgo darwin LDFLAGS: -framework Cocoa -framework IOKit -framework CoreVideo + +#cgo !gles2,darwin LDFLAGS: -framework OpenGL +#cgo gles2,darwin LDFLAGS: -lGLESv2 + +// Linux Build Tags +// ---------------- +// GLFW Options: +#cgo linux,!wayland CFLAGS: -D_GLFW_X11 +#cgo linux,wayland CFLAGS: -D_GLFW_WAYLAND + +// Linker Options: +#cgo linux,!gles1,!gles2,!gles3,!vulkan LDFLAGS: -lGL +#cgo linux,gles1 LDFLAGS: -lGLESv1 +#cgo linux,gles2 LDFLAGS: -lGLESv2 +#cgo linux,gles3 LDFLAGS: -lGLESv3 +#cgo linux,vulkan LDFLAGS: -lvulkan +#cgo linux,!wayland LDFLAGS: -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm -lXinerama -ldl -lrt +#cgo linux,wayland LDFLAGS: -lwayland-client -lwayland-cursor -lwayland-egl -lxkbcommon -lm -ldl -lrt + +// BSD Build Tags +// ---------------- +// GLFW Options: +#cgo freebsd,!wayland netbsd,!wayland openbsd pkg-config: x11 xau xcb xdmcp +#cgo freebsd,wayland netbsd,wayland pkg-config: wayland-client wayland-cursor wayland-egl epoll-shim +#cgo freebsd netbsd openbsd CFLAGS: -D_GLFW_HAS_DLOPEN +#cgo freebsd,!wayland netbsd,!wayland openbsd CFLAGS: -D_GLFW_X11 -D_GLFW_HAS_GLXGETPROCADDRESSARB +#cgo freebsd,wayland netbsd,wayland CFLAGS: -D_GLFW_WAYLAND + +// Linker Options: +#cgo freebsd netbsd openbsd LDFLAGS: -lm +*/ +import "C" diff --git a/v3.4/glfw/build_cgo_hack.go b/v3.4/glfw/build_cgo_hack.go new file mode 100644 index 00000000..0bbd880b --- /dev/null +++ b/v3.4/glfw/build_cgo_hack.go @@ -0,0 +1,19 @@ +//go:build required +// +build required + +package glfw + +// This file exists purely to prevent the golang toolchain from stripping +// away the c source directories and files when `go mod vendor` is used +// to populate a `vendor/` directory of a project depending on `go-gl/glfw`. +// +// How it works: +// - every directory which only includes c source files receives a dummy.go file. +// - every directory we want to preserve is included here as a _ import. +// - this file is given a build to exclude it from the regular build. +import ( + // Prevent go tooling from stripping out the c source files. + _ "github.com/go-gl/glfw/v3.3/glfw/glfw/deps" + _ "github.com/go-gl/glfw/v3.3/glfw/glfw/include/GLFW" + _ "github.com/go-gl/glfw/v3.3/glfw/glfw/src" +) diff --git a/v3.4/glfw/c_glfw.go b/v3.4/glfw/c_glfw.go new file mode 100644 index 00000000..c5dbde62 --- /dev/null +++ b/v3.4/glfw/c_glfw.go @@ -0,0 +1,12 @@ +package glfw + +/* +#include "glfw/src/context.c" +#include "glfw/src/init.c" +#include "glfw/src/input.c" +#include "glfw/src/monitor.c" +#include "glfw/src/vulkan.c" +#include "glfw/src/window.c" +#include "glfw/src/osmesa_context.c" +*/ +import "C" diff --git a/v3.4/glfw/c_glfw_bsd.go b/v3.4/glfw/c_glfw_bsd.go new file mode 100644 index 00000000..2c704f0d --- /dev/null +++ b/v3.4/glfw/c_glfw_bsd.go @@ -0,0 +1,30 @@ +//go:build freebsd || netbsd || openbsd +// +build freebsd netbsd openbsd + +package glfw + +/* +#ifdef _GLFW_WAYLAND + #include "glfw/src/wl_init.c" + #include "glfw/src/wl_monitor.c" + #include "glfw/src/wl_window.c" + #include "glfw/src/wayland-idle-inhibit-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-pointer-constraints-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-relative-pointer-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-viewporter-client-protocol.c" + #include "glfw/src/wayland-xdg-decoration-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-xdg-shell-client-protocol.c" +#endif +#ifdef _GLFW_X11 + #include "glfw/src/x11_init.c" + #include "glfw/src/x11_monitor.c" + #include "glfw/src/x11_window.c" + #include "glfw/src/glx_context.c" +#endif +#include "glfw/src/null_joystick.c" +#include "glfw/src/posix_time.c" +#include "glfw/src/posix_thread.c" +#include "glfw/src/xkb_unicode.c" +#include "glfw/src/egl_context.c" +*/ +import "C" diff --git a/v3.4/glfw/c_glfw_darwin.go b/v3.4/glfw/c_glfw_darwin.go new file mode 100644 index 00000000..6fff2880 --- /dev/null +++ b/v3.4/glfw/c_glfw_darwin.go @@ -0,0 +1,14 @@ +package glfw + +/* +#cgo CFLAGS: -x objective-c +#include "glfw/src/cocoa_init.m" +#include "glfw/src/cocoa_joystick.m" +#include "glfw/src/cocoa_monitor.m" +#include "glfw/src/cocoa_window.m" +#include "glfw/src/cocoa_time.c" +#include "glfw/src/posix_thread.c" +#include "glfw/src/nsgl_context.m" +#include "glfw/src/egl_context.c" +*/ +import "C" diff --git a/v3.4/glfw/c_glfw_lin.go b/v3.4/glfw/c_glfw_lin.go new file mode 100644 index 00000000..64bfea12 --- /dev/null +++ b/v3.4/glfw/c_glfw_lin.go @@ -0,0 +1,30 @@ +//go:build linux +// +build linux + +package glfw + +/* +#ifdef _GLFW_WAYLAND + #include "glfw/src/wl_init.c" + #include "glfw/src/wl_monitor.c" + #include "glfw/src/wl_window.c" + #include "glfw/src/wayland-idle-inhibit-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-pointer-constraints-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-relative-pointer-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-viewporter-client-protocol.c" + #include "glfw/src/wayland-xdg-decoration-unstable-v1-client-protocol.c" + #include "glfw/src/wayland-xdg-shell-client-protocol.c" +#endif +#ifdef _GLFW_X11 + #include "glfw/src/x11_window.c" + #include "glfw/src/x11_init.c" + #include "glfw/src/x11_monitor.c" + #include "glfw/src/glx_context.c" +#endif +#include "glfw/src/linux_joystick.c" +#include "glfw/src/posix_time.c" +#include "glfw/src/posix_thread.c" +#include "glfw/src/xkb_unicode.c" +#include "glfw/src/egl_context.c" +*/ +import "C" diff --git a/v3.4/glfw/c_glfw_windows.go b/v3.4/glfw/c_glfw_windows.go new file mode 100644 index 00000000..7ff980ad --- /dev/null +++ b/v3.4/glfw/c_glfw_windows.go @@ -0,0 +1,13 @@ +package glfw + +/* +#include "glfw/src/win32_init.c" +#include "glfw/src/win32_joystick.c" +#include "glfw/src/win32_monitor.c" +#include "glfw/src/win32_time.c" +#include "glfw/src/win32_thread.c" +#include "glfw/src/win32_window.c" +#include "glfw/src/wgl_context.c" +#include "glfw/src/egl_context.c" +*/ +import "C" diff --git a/v3.4/glfw/context.go b/v3.4/glfw/context.go new file mode 100644 index 00000000..c4bb48dc --- /dev/null +++ b/v3.4/glfw/context.go @@ -0,0 +1,94 @@ +package glfw + +//#include +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +import "C" + +import ( + "unsafe" +) + +// MakeContextCurrent makes the context of the window current. +// Originally GLFW 3 passes a null pointer to detach the context. +// But since we're using receievers, DetachCurrentContext should +// be used instead. +func (w *Window) MakeContextCurrent() { + C.glfwMakeContextCurrent(w.data) + panicError() +} + +// DetachCurrentContext detaches the current context. +func DetachCurrentContext() { + C.glfwMakeContextCurrent(nil) + panicError() +} + +// GetCurrentContext returns the window whose context is current. +func GetCurrentContext() *Window { + w := C.glfwGetCurrentContext() + panicError() + if w == nil { + return nil + } + return windows.get(w) +} + +// SwapBuffers swaps the front and back buffers of the window. If the +// swap interval is greater than zero, the GPU driver waits the specified number +// of screen updates before swapping the buffers. +func (w *Window) SwapBuffers() { + C.glfwSwapBuffers(w.data) + panicError() +} + +// SwapInterval sets the swap interval for the current context, i.e. the number +// of screen updates to wait before swapping the buffers of a window and +// returning from SwapBuffers. This is sometimes called +// 'vertical synchronization', 'vertical retrace synchronization' or 'vsync'. +// +// Contexts that support either of the WGL_EXT_swap_control_tear and +// GLX_EXT_swap_control_tear extensions also accept negative swap intervals, +// which allow the driver to swap even if a frame arrives a little bit late. +// You can check for the presence of these extensions using +// ExtensionSupported. For more information about swap tearing, +// see the extension specifications. +// +// Some GPU drivers do not honor the requested swap interval, either because of +// user settings that override the request or due to bugs in the driver. +func SwapInterval(interval int) { + C.glfwSwapInterval(C.int(interval)) + panicError() +} + +// ExtensionSupported reports whether the specified OpenGL or context creation +// API extension is supported by the current context. For example, on Windows +// both the OpenGL and WGL extension strings are checked. +// +// As this functions searches one or more extension strings on each call, it is +// recommended that you cache its results if it's going to be used frequently. +// The extension strings will not change during the lifetime of a context, so +// there is no danger in doing this. +func ExtensionSupported(extension string) bool { + e := C.CString(extension) + defer C.free(unsafe.Pointer(e)) + ret := glfwbool(C.glfwExtensionSupported(e)) + panicError() + return ret +} + +// GetProcAddress returns the address of the specified OpenGL or OpenGL ES core +// or extension function, if it is supported by the current context. +// +// A context must be current on the calling thread. Calling this function +// without a current context will cause a GLFW_NO_CURRENT_CONTEXT error. +// +// This function is used to provide GL proc resolving capabilities to an +// external C library. +func GetProcAddress(procname string) unsafe.Pointer { + p := C.CString(procname) + defer C.free(unsafe.Pointer(p)) + ret := unsafe.Pointer(C.glfwGetProcAddress(p)) + panicError() + return ret +} diff --git a/v3.4/glfw/error.c b/v3.4/glfw/error.c new file mode 100644 index 00000000..0ef98715 --- /dev/null +++ b/v3.4/glfw/error.c @@ -0,0 +1,3 @@ +#include "_cgo_export.h" + +void glfwSetErrorCallbackCB() { glfwSetErrorCallback((GLFWerrorfun)goErrorCB); } diff --git a/v3.4/glfw/error.go b/v3.4/glfw/error.go new file mode 100644 index 00000000..55030a3a --- /dev/null +++ b/v3.4/glfw/error.go @@ -0,0 +1,203 @@ +package glfw + +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//void glfwSetErrorCallbackCB(); +import "C" + +import ( + "fmt" + "log" + "os" +) + +// ErrorCode corresponds to an error code. +type ErrorCode int + +// Error codes that are translated to panics and the programmer should not +// expect to handle. +const ( + notInitialized ErrorCode = C.GLFW_NOT_INITIALIZED // GLFW has not been initialized. + noCurrentContext ErrorCode = C.GLFW_NO_CURRENT_CONTEXT // No context is current. + invalidEnum ErrorCode = C.GLFW_INVALID_ENUM // One of the enum parameters for the function was given an invalid enum. + invalidValue ErrorCode = C.GLFW_INVALID_VALUE // One of the parameters for the function was given an invalid value. + outOfMemory ErrorCode = C.GLFW_OUT_OF_MEMORY // A memory allocation failed. + platformError ErrorCode = C.GLFW_PLATFORM_ERROR // A platform-specific error occurred that does not match any of the more specific categories. + noWindowContext ErrorCode = C.GLFW_NO_WINDOW_CONTEXT // A window that does not have an OpenGL or OpenGL ES context was passed to a function that requires it to have one. +) + +const ( + // APIUnavailable is the error code used when GLFW could not find support + // for the requested client API on the system. + // + // The installed graphics driver does not support the requested client API, + // or does not support it via the chosen context creation backend. Below + // are a few examples. + // + // Some pre-installed Windows graphics drivers do not support OpenGL. AMD + // only supports OpenGL ES via EGL, while Nvidia and Intel only supports it + // via a WGL or GLX extension. OS X does not provide OpenGL ES at all. The + // Mesa EGL, OpenGL and OpenGL ES libraries do not interface with the + // Nvidia binary driver. + APIUnavailable ErrorCode = C.GLFW_API_UNAVAILABLE + + // VersionUnavailable is the error code used when the requested OpenGL or + // OpenGL ES (including any requested profile or context option) is not + // available on this machine. + // + // The machine does not support your requirements. If your application is + // sufficiently flexible, downgrade your requirements and try again. + // Otherwise, inform the user that their machine does not match your + // requirements. + // + // Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if + // 5.0 comes out before the 4.x series gets that far, also fail with this + // error and not GLFW_INVALID_VALUE, because GLFW cannot know what future + // versions will exist. + VersionUnavailable ErrorCode = C.GLFW_VERSION_UNAVAILABLE + + // FormatUnavailable is the error code used for both window creation and + // clipboard querying format errors. + // + // If emitted during window creation, the requested pixel format is not + // supported. This means one or more hard constraints did not match any of + // the available pixel formats. If your application is sufficiently + // flexible, downgrade your requirements and try again. Otherwise, inform + // the user that their machine does not match your requirements. + // + // If emitted when querying the clipboard, the contents of the clipboard + // could not be converted to the requested format. You should ignore the + // error or report it to the user, as appropriate. + FormatUnavailable ErrorCode = C.GLFW_FORMAT_UNAVAILABLE +) + +func (e ErrorCode) String() string { + switch e { + case notInitialized: + return "NotInitialized" + case noCurrentContext: + return "NoCurrentContext" + case invalidEnum: + return "InvalidEnum" + case invalidValue: + return "InvalidValue" + case outOfMemory: + return "OutOfMemory" + case platformError: + return "PlatformError" + case noWindowContext: + return "NoWindowContext" + case APIUnavailable: + return "APIUnavailable" + case VersionUnavailable: + return "VersionUnavailable" + case FormatUnavailable: + return "FormatUnavailable" + default: + return fmt.Sprintf("ErrorCode(%d)", e) + } +} + +// Error holds error code and description. +type Error struct { + Code ErrorCode + Desc string +} + +// Error prints the error code and description in a readable format. +func (e *Error) Error() string { + return fmt.Sprintf("%s: %s", e.Code.String(), e.Desc) +} + +// Note: There are many cryptic caveats to proper error handling here. +// See: https://github.com/go-gl/glfw3/pull/86 + +// Holds the value of the last error. +var lastError = make(chan *Error, 1) + +//export goErrorCB +func goErrorCB(code C.int, desc *C.char) { + flushErrors() + err := &Error{ErrorCode(code), C.GoString(desc)} + select { + case lastError <- err: + default: + fmt.Fprintln(os.Stderr, "go-gl/glfw: internal error: an uncaught error has occurred:", err) + fmt.Fprintln(os.Stderr, "go-gl/glfw: Please report this in the Go package issue tracker.") + } +} + +// Set the glfw callback internally +func init() { + C.glfwSetErrorCallbackCB() +} + +// flushErrors is called by Terminate before it actually calls C.glfwTerminate, +// this ensures that any uncaught errors buffered in lastError are printed +// before the program exits. +func flushErrors() { + err := fetchError() + if err != nil { + fmt.Fprintln(os.Stderr, "go-gl/glfw: internal error: an uncaught error has occurred:", err) + fmt.Fprintln(os.Stderr, "go-gl/glfw: Please report this in the Go package issue tracker.") + } +} + +// acceptError fetches the next error from the error channel, it accepts only +// errors with one of the given error codes. If any other error is encountered, +// a panic will occur. +// +// Platform errors are always printed, for information why please see: +// +// https://github.com/go-gl/glfw/issues/127 +func acceptError(codes ...ErrorCode) error { + // Grab the next error, if there is one. + err := fetchError() + if err == nil { + return nil + } + + // Only if the error has the specific error code accepted by the caller, do + // we return the error. + for _, code := range codes { + if err.Code == code { + return err + } + } + + // The error isn't accepted by the caller. If the error code is not a code + // defined in the GLFW C documentation as a programmer error, then the + // caller should have accepted it. This is effectively a bug in this + // package. + switch err.Code { + case platformError: + log.Println(err) + return nil + case notInitialized, noCurrentContext, invalidEnum, invalidValue, outOfMemory, noWindowContext: + panic(err) + default: + fmt.Fprintln(os.Stderr, "go-gl/glfw: internal error: an invalid error was not accepted by the caller:", err) + fmt.Fprintln(os.Stderr, "go-gl/glfw: Please report this in the Go package issue tracker.") + panic(err) + } +} + +// panicError is a helper used by functions which expect no errors (except +// programmer errors) to occur. It will panic if it finds any such error. +func panicError() { + err := acceptError() + if err != nil { + panic(err) + } +} + +// fetchError fetches the next error from the error channel, it does not block +// and returns nil if there is no error present. +func fetchError() *Error { + select { + case err := <-lastError: + return err + default: + return nil + } +} diff --git a/v3.4/glfw/glfw.go b/v3.4/glfw/glfw.go new file mode 100644 index 00000000..501a4088 --- /dev/null +++ b/v3.4/glfw/glfw.go @@ -0,0 +1,118 @@ +package glfw + +//#include +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +import "C" +import "unsafe" + +// Version constants. +const ( + VersionMajor = C.GLFW_VERSION_MAJOR // This is incremented when the API is changed in non-compatible ways. + VersionMinor = C.GLFW_VERSION_MINOR // This is incremented when features are added to the API but it remains backward-compatible. + VersionRevision = C.GLFW_VERSION_REVISION // This is incremented when a bug fix release is made that does not contain any API changes. +) + +// Init initializes the GLFW library. Before most GLFW functions can be used, +// GLFW must be initialized, and before a program terminates GLFW should be +// terminated in order to free any resources allocated during or after +// initialization. +// +// If this function fails, it calls Terminate before returning. If it succeeds, +// you should call Terminate before the program exits. +// +// Additional calls to this function after successful initialization but before +// termination will succeed but will do nothing. +// +// This function may take several seconds to complete on some systems, while on +// other systems it may take only a fraction of a second to complete. +// +// On Mac OS X, this function will change the current directory of the +// application to the Contents/Resources subdirectory of the application's +// bundle, if present. +// +// This function may only be called from the main thread. +func Init() error { + C.glfwInit() + return acceptError(APIUnavailable) +} + +// Terminate destroys all remaining windows, frees any allocated resources and +// sets the library to an uninitialized state. Once this is called, you must +// again call Init successfully before you will be able to use most GLFW +// functions. +// +// If GLFW has been successfully initialized, this function should be called +// before the program exits. If initialization fails, there is no need to call +// this function, as it is called by Init before it returns failure. +// +// This function may only be called from the main thread. +func Terminate() { + flushErrors() + C.glfwTerminate() +} + +// InitHint function sets hints for the next initialization of GLFW. +// +// The values you set hints to are never reset by GLFW, but they only take +// effect during initialization. Once GLFW has been initialized, any values you +// set will be ignored until the library is terminated and initialized again. +// +// Some hints are platform specific. These may be set on any platform but they +// will only affect their specific platform. Other platforms will ignore them. +// Setting these hints requires no platform specific headers or functions. +// +// This function must only be called from the main thread. +func InitHint(hint Hint, value int) { + C.glfwInitHint(C.int(hint), C.int(value)) +} + +// GetVersion retrieves the major, minor and revision numbers of the GLFW +// library. It is intended for when you are using GLFW as a shared library and +// want to ensure that you are using the minimum required version. +// +// This function may be called before Init. +func GetVersion() (major, minor, revision int) { + var ( + maj C.int + min C.int + rev C.int + ) + + C.glfwGetVersion(&maj, &min, &rev) + return int(maj), int(min), int(rev) +} + +// GetVersionString returns a static string generated at compile-time according +// to which configuration macros were defined. This is intended for use when +// submitting bug reports, to allow developers to see which code paths are +// enabled in a binary. +// +// This function may be called before Init. +func GetVersionString() string { + return C.GoString(C.glfwGetVersionString()) +} + +// GetClipboardString returns the contents of the system clipboard, if it +// contains or is convertible to a UTF-8 encoded string. +// +// This function may only be called from the main thread. +func GetClipboardString() string { + cs := C.glfwGetClipboardString(nil) + if cs == nil { + acceptError(FormatUnavailable) + return "" + } + return C.GoString(cs) +} + +// SetClipboardString sets the system clipboard to the specified UTF-8 encoded +// string. +// +// This function may only be called from the main thread. +func SetClipboardString(str string) { + cp := C.CString(str) + defer C.free(unsafe.Pointer(cp)) + C.glfwSetClipboardString(nil, cp) + panicError() +} diff --git a/v3.4/glfw/glfw_tree_rebuild.go b/v3.4/glfw/glfw_tree_rebuild.go new file mode 100644 index 00000000..e9e792b9 --- /dev/null +++ b/v3.4/glfw/glfw_tree_rebuild.go @@ -0,0 +1,10 @@ +package glfw + +//go:generate ../../scripts/glfw_tree_rebuild.sh + +// upstreamTreeSHA is a recursive hash of the full contents of the upstream +// glfw, as generated by git (doesn't need to be committed) when you run `go +// generate` on this package. This exists to invalidate the build cache (see +// https://github.com/go-gl/glfw/issues/269), which is unaffected by C source +// inputs. +const upstreamTreeSHA = "a4a3bc8c0f4e37695a4de3f51cd7123bc186043b" diff --git a/v3.4/glfw/go.mod b/v3.4/glfw/go.mod new file mode 100644 index 00000000..64268f33 --- /dev/null +++ b/v3.4/glfw/go.mod @@ -0,0 +1,3 @@ +module github.com/go-gl/glfw/v3.3/glfw + +go 1.10 diff --git a/v3.4/glfw/input.c b/v3.4/glfw/input.c new file mode 100644 index 00000000..27e00cb4 --- /dev/null +++ b/v3.4/glfw/input.c @@ -0,0 +1,49 @@ +#include "_cgo_export.h" + +void glfwSetJoystickCallbackCB() { + glfwSetJoystickCallback((GLFWjoystickfun)goJoystickCB); +} + +void glfwSetKeyCallbackCB(GLFWwindow *window) { + glfwSetKeyCallback(window, (GLFWkeyfun)goKeyCB); +} + +void glfwSetCharCallbackCB(GLFWwindow *window) { + glfwSetCharCallback(window, (GLFWcharfun)goCharCB); +} + +void glfwSetCharModsCallbackCB(GLFWwindow *window) { + glfwSetCharModsCallback(window, (GLFWcharmodsfun)goCharModsCB); +} + +void glfwSetMouseButtonCallbackCB(GLFWwindow *window) { + glfwSetMouseButtonCallback(window, (GLFWmousebuttonfun)goMouseButtonCB); +} + +void glfwSetCursorPosCallbackCB(GLFWwindow *window) { + glfwSetCursorPosCallback(window, (GLFWcursorposfun)goCursorPosCB); +} + +void glfwSetCursorEnterCallbackCB(GLFWwindow *window) { + glfwSetCursorEnterCallback(window, (GLFWcursorenterfun)goCursorEnterCB); +} + +void glfwSetScrollCallbackCB(GLFWwindow *window) { + glfwSetScrollCallback(window, (GLFWscrollfun)goScrollCB); +} + +void glfwSetDropCallbackCB(GLFWwindow *window) { + glfwSetDropCallback(window, (GLFWdropfun)goDropCB); +} + +float GetAxisAtIndex(float *axis, int i) { return axis[i]; } + +unsigned char GetButtonsAtIndex(unsigned char *buttons, int i) { + return buttons[i]; +} + +unsigned char GetGamepadButtonAtIndex(GLFWgamepadstate *gp, int i) { + return gp->buttons[i]; +} + +float GetGamepadAxisAtIndex(GLFWgamepadstate *gp, int i) { return gp->axes[i]; } diff --git a/v3.4/glfw/input.go b/v3.4/glfw/input.go new file mode 100644 index 00000000..90759d6a --- /dev/null +++ b/v3.4/glfw/input.go @@ -0,0 +1,955 @@ +package glfw + +//#include +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//void glfwSetJoystickCallbackCB(); +//void glfwSetKeyCallbackCB(GLFWwindow *window); +//void glfwSetCharCallbackCB(GLFWwindow *window); +//void glfwSetCharModsCallbackCB(GLFWwindow *window); +//void glfwSetMouseButtonCallbackCB(GLFWwindow *window); +//void glfwSetCursorPosCallbackCB(GLFWwindow *window); +//void glfwSetCursorEnterCallbackCB(GLFWwindow *window); +//void glfwSetScrollCallbackCB(GLFWwindow *window); +//void glfwSetDropCallbackCB(GLFWwindow *window); +//float GetAxisAtIndex(float *axis, int i); +//unsigned char GetButtonsAtIndex(unsigned char *buttons, int i); +//float GetGamepadAxisAtIndex(GLFWgamepadstate *gp, int i); +//unsigned char GetGamepadButtonAtIndex(GLFWgamepadstate *gp, int i); +import "C" + +import ( + "image" + "unsafe" +) + +// Joystick corresponds to a joystick. +type Joystick int + +// Joystick IDs. +const ( + Joystick1 Joystick = C.GLFW_JOYSTICK_1 + Joystick2 Joystick = C.GLFW_JOYSTICK_2 + Joystick3 Joystick = C.GLFW_JOYSTICK_3 + Joystick4 Joystick = C.GLFW_JOYSTICK_4 + Joystick5 Joystick = C.GLFW_JOYSTICK_5 + Joystick6 Joystick = C.GLFW_JOYSTICK_6 + Joystick7 Joystick = C.GLFW_JOYSTICK_7 + Joystick8 Joystick = C.GLFW_JOYSTICK_8 + Joystick9 Joystick = C.GLFW_JOYSTICK_9 + Joystick10 Joystick = C.GLFW_JOYSTICK_10 + Joystick11 Joystick = C.GLFW_JOYSTICK_11 + Joystick12 Joystick = C.GLFW_JOYSTICK_12 + Joystick13 Joystick = C.GLFW_JOYSTICK_13 + Joystick14 Joystick = C.GLFW_JOYSTICK_14 + Joystick15 Joystick = C.GLFW_JOYSTICK_15 + Joystick16 Joystick = C.GLFW_JOYSTICK_16 + JoystickLast Joystick = C.GLFW_JOYSTICK_LAST +) + +// JoystickHatState corresponds to joystick hat states. +type JoystickHatState int + +// Joystick Hat State IDs. +const ( + HatCentered JoystickHatState = C.GLFW_HAT_CENTERED + HatUp JoystickHatState = C.GLFW_HAT_UP + HatRight JoystickHatState = C.GLFW_HAT_RIGHT + HatDown JoystickHatState = C.GLFW_HAT_DOWN + HatLeft JoystickHatState = C.GLFW_HAT_LEFT + HatRightUp JoystickHatState = C.GLFW_HAT_RIGHT_UP + HatRightDown JoystickHatState = C.GLFW_HAT_RIGHT_DOWN + HatLeftUp JoystickHatState = C.GLFW_HAT_LEFT_UP + HatLeftDown JoystickHatState = C.GLFW_HAT_LEFT_DOWN +) + +// GamepadAxis corresponds to a gamepad axis. +type GamepadAxis int + +// Gamepad axis IDs. +const ( + AxisLeftX GamepadAxis = C.GLFW_GAMEPAD_AXIS_LEFT_X + AxisLeftY GamepadAxis = C.GLFW_GAMEPAD_AXIS_LEFT_Y + AxisRightX GamepadAxis = C.GLFW_GAMEPAD_AXIS_RIGHT_X + AxisRightY GamepadAxis = C.GLFW_GAMEPAD_AXIS_RIGHT_Y + AxisLeftTrigger GamepadAxis = C.GLFW_GAMEPAD_AXIS_LEFT_TRIGGER + AxisRightTrigger GamepadAxis = C.GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER + AxisLast GamepadAxis = C.GLFW_GAMEPAD_AXIS_LAST +) + +// GamepadButton corresponds to a gamepad button. +type GamepadButton int + +// Gamepad button IDs. +const ( + ButtonA GamepadButton = C.GLFW_GAMEPAD_BUTTON_A + ButtonB GamepadButton = C.GLFW_GAMEPAD_BUTTON_B + ButtonX GamepadButton = C.GLFW_GAMEPAD_BUTTON_X + ButtonY GamepadButton = C.GLFW_GAMEPAD_BUTTON_Y + ButtonLeftBumper GamepadButton = C.GLFW_GAMEPAD_BUTTON_LEFT_BUMPER + ButtonRightBumper GamepadButton = C.GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER + ButtonBack GamepadButton = C.GLFW_GAMEPAD_BUTTON_BACK + ButtonStart GamepadButton = C.GLFW_GAMEPAD_BUTTON_START + ButtonGuide GamepadButton = C.GLFW_GAMEPAD_BUTTON_GUIDE + ButtonLeftThumb GamepadButton = C.GLFW_GAMEPAD_BUTTON_LEFT_THUMB + ButtonRightThumb GamepadButton = C.GLFW_GAMEPAD_BUTTON_RIGHT_THUMB + ButtonDpadUp GamepadButton = C.GLFW_GAMEPAD_BUTTON_DPAD_UP + ButtonDpadRight GamepadButton = C.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT + ButtonDpadDown GamepadButton = C.GLFW_GAMEPAD_BUTTON_DPAD_DOWN + ButtonDpadLeft GamepadButton = C.GLFW_GAMEPAD_BUTTON_DPAD_LEFT + ButtonLast GamepadButton = C.GLFW_GAMEPAD_BUTTON_LAST + ButtonCross GamepadButton = C.GLFW_GAMEPAD_BUTTON_CROSS + ButtonCircle GamepadButton = C.GLFW_GAMEPAD_BUTTON_CIRCLE + ButtonSquare GamepadButton = C.GLFW_GAMEPAD_BUTTON_SQUARE + ButtonTriangle GamepadButton = C.GLFW_GAMEPAD_BUTTON_TRIANGLE +) + +// GamepadState describes the input state of a gamepad. +type GamepadState struct { + Buttons [15]Action + Axes [6]float32 +} + +// Key corresponds to a keyboard key. +type Key int + +// These key codes are inspired by the USB HID Usage Tables v1.12 (p. 53-60), +// but re-arranged to map to 7-bit ASCII for printable keys (function keys are +// put in the 256+ range). +const ( + KeyUnknown Key = C.GLFW_KEY_UNKNOWN + KeySpace Key = C.GLFW_KEY_SPACE + KeyApostrophe Key = C.GLFW_KEY_APOSTROPHE + KeyComma Key = C.GLFW_KEY_COMMA + KeyMinus Key = C.GLFW_KEY_MINUS + KeyPeriod Key = C.GLFW_KEY_PERIOD + KeySlash Key = C.GLFW_KEY_SLASH + Key0 Key = C.GLFW_KEY_0 + Key1 Key = C.GLFW_KEY_1 + Key2 Key = C.GLFW_KEY_2 + Key3 Key = C.GLFW_KEY_3 + Key4 Key = C.GLFW_KEY_4 + Key5 Key = C.GLFW_KEY_5 + Key6 Key = C.GLFW_KEY_6 + Key7 Key = C.GLFW_KEY_7 + Key8 Key = C.GLFW_KEY_8 + Key9 Key = C.GLFW_KEY_9 + KeySemicolon Key = C.GLFW_KEY_SEMICOLON + KeyEqual Key = C.GLFW_KEY_EQUAL + KeyA Key = C.GLFW_KEY_A + KeyB Key = C.GLFW_KEY_B + KeyC Key = C.GLFW_KEY_C + KeyD Key = C.GLFW_KEY_D + KeyE Key = C.GLFW_KEY_E + KeyF Key = C.GLFW_KEY_F + KeyG Key = C.GLFW_KEY_G + KeyH Key = C.GLFW_KEY_H + KeyI Key = C.GLFW_KEY_I + KeyJ Key = C.GLFW_KEY_J + KeyK Key = C.GLFW_KEY_K + KeyL Key = C.GLFW_KEY_L + KeyM Key = C.GLFW_KEY_M + KeyN Key = C.GLFW_KEY_N + KeyO Key = C.GLFW_KEY_O + KeyP Key = C.GLFW_KEY_P + KeyQ Key = C.GLFW_KEY_Q + KeyR Key = C.GLFW_KEY_R + KeyS Key = C.GLFW_KEY_S + KeyT Key = C.GLFW_KEY_T + KeyU Key = C.GLFW_KEY_U + KeyV Key = C.GLFW_KEY_V + KeyW Key = C.GLFW_KEY_W + KeyX Key = C.GLFW_KEY_X + KeyY Key = C.GLFW_KEY_Y + KeyZ Key = C.GLFW_KEY_Z + KeyLeftBracket Key = C.GLFW_KEY_LEFT_BRACKET + KeyBackslash Key = C.GLFW_KEY_BACKSLASH + KeyRightBracket Key = C.GLFW_KEY_RIGHT_BRACKET + KeyGraveAccent Key = C.GLFW_KEY_GRAVE_ACCENT + KeyWorld1 Key = C.GLFW_KEY_WORLD_1 + KeyWorld2 Key = C.GLFW_KEY_WORLD_2 + KeyEscape Key = C.GLFW_KEY_ESCAPE + KeyEnter Key = C.GLFW_KEY_ENTER + KeyTab Key = C.GLFW_KEY_TAB + KeyBackspace Key = C.GLFW_KEY_BACKSPACE + KeyInsert Key = C.GLFW_KEY_INSERT + KeyDelete Key = C.GLFW_KEY_DELETE + KeyRight Key = C.GLFW_KEY_RIGHT + KeyLeft Key = C.GLFW_KEY_LEFT + KeyDown Key = C.GLFW_KEY_DOWN + KeyUp Key = C.GLFW_KEY_UP + KeyPageUp Key = C.GLFW_KEY_PAGE_UP + KeyPageDown Key = C.GLFW_KEY_PAGE_DOWN + KeyHome Key = C.GLFW_KEY_HOME + KeyEnd Key = C.GLFW_KEY_END + KeyCapsLock Key = C.GLFW_KEY_CAPS_LOCK + KeyScrollLock Key = C.GLFW_KEY_SCROLL_LOCK + KeyNumLock Key = C.GLFW_KEY_NUM_LOCK + KeyPrintScreen Key = C.GLFW_KEY_PRINT_SCREEN + KeyPause Key = C.GLFW_KEY_PAUSE + KeyF1 Key = C.GLFW_KEY_F1 + KeyF2 Key = C.GLFW_KEY_F2 + KeyF3 Key = C.GLFW_KEY_F3 + KeyF4 Key = C.GLFW_KEY_F4 + KeyF5 Key = C.GLFW_KEY_F5 + KeyF6 Key = C.GLFW_KEY_F6 + KeyF7 Key = C.GLFW_KEY_F7 + KeyF8 Key = C.GLFW_KEY_F8 + KeyF9 Key = C.GLFW_KEY_F9 + KeyF10 Key = C.GLFW_KEY_F10 + KeyF11 Key = C.GLFW_KEY_F11 + KeyF12 Key = C.GLFW_KEY_F12 + KeyF13 Key = C.GLFW_KEY_F13 + KeyF14 Key = C.GLFW_KEY_F14 + KeyF15 Key = C.GLFW_KEY_F15 + KeyF16 Key = C.GLFW_KEY_F16 + KeyF17 Key = C.GLFW_KEY_F17 + KeyF18 Key = C.GLFW_KEY_F18 + KeyF19 Key = C.GLFW_KEY_F19 + KeyF20 Key = C.GLFW_KEY_F20 + KeyF21 Key = C.GLFW_KEY_F21 + KeyF22 Key = C.GLFW_KEY_F22 + KeyF23 Key = C.GLFW_KEY_F23 + KeyF24 Key = C.GLFW_KEY_F24 + KeyF25 Key = C.GLFW_KEY_F25 + KeyKP0 Key = C.GLFW_KEY_KP_0 + KeyKP1 Key = C.GLFW_KEY_KP_1 + KeyKP2 Key = C.GLFW_KEY_KP_2 + KeyKP3 Key = C.GLFW_KEY_KP_3 + KeyKP4 Key = C.GLFW_KEY_KP_4 + KeyKP5 Key = C.GLFW_KEY_KP_5 + KeyKP6 Key = C.GLFW_KEY_KP_6 + KeyKP7 Key = C.GLFW_KEY_KP_7 + KeyKP8 Key = C.GLFW_KEY_KP_8 + KeyKP9 Key = C.GLFW_KEY_KP_9 + KeyKPDecimal Key = C.GLFW_KEY_KP_DECIMAL + KeyKPDivide Key = C.GLFW_KEY_KP_DIVIDE + KeyKPMultiply Key = C.GLFW_KEY_KP_MULTIPLY + KeyKPSubtract Key = C.GLFW_KEY_KP_SUBTRACT + KeyKPAdd Key = C.GLFW_KEY_KP_ADD + KeyKPEnter Key = C.GLFW_KEY_KP_ENTER + KeyKPEqual Key = C.GLFW_KEY_KP_EQUAL + KeyLeftShift Key = C.GLFW_KEY_LEFT_SHIFT + KeyLeftControl Key = C.GLFW_KEY_LEFT_CONTROL + KeyLeftAlt Key = C.GLFW_KEY_LEFT_ALT + KeyLeftSuper Key = C.GLFW_KEY_LEFT_SUPER + KeyRightShift Key = C.GLFW_KEY_RIGHT_SHIFT + KeyRightControl Key = C.GLFW_KEY_RIGHT_CONTROL + KeyRightAlt Key = C.GLFW_KEY_RIGHT_ALT + KeyRightSuper Key = C.GLFW_KEY_RIGHT_SUPER + KeyMenu Key = C.GLFW_KEY_MENU + KeyLast Key = C.GLFW_KEY_LAST +) + +// ModifierKey corresponds to a modifier key. +type ModifierKey int + +// Modifier keys. +const ( + ModShift ModifierKey = C.GLFW_MOD_SHIFT + ModControl ModifierKey = C.GLFW_MOD_CONTROL + ModAlt ModifierKey = C.GLFW_MOD_ALT + ModSuper ModifierKey = C.GLFW_MOD_SUPER + ModCapsLock ModifierKey = C.GLFW_MOD_CAPS_LOCK + ModNumLock ModifierKey = C.GLFW_MOD_NUM_LOCK +) + +// MouseButton corresponds to a mouse button. +type MouseButton int + +// Mouse buttons. +const ( + MouseButton1 MouseButton = C.GLFW_MOUSE_BUTTON_1 + MouseButton2 MouseButton = C.GLFW_MOUSE_BUTTON_2 + MouseButton3 MouseButton = C.GLFW_MOUSE_BUTTON_3 + MouseButton4 MouseButton = C.GLFW_MOUSE_BUTTON_4 + MouseButton5 MouseButton = C.GLFW_MOUSE_BUTTON_5 + MouseButton6 MouseButton = C.GLFW_MOUSE_BUTTON_6 + MouseButton7 MouseButton = C.GLFW_MOUSE_BUTTON_7 + MouseButton8 MouseButton = C.GLFW_MOUSE_BUTTON_8 + MouseButtonLast MouseButton = C.GLFW_MOUSE_BUTTON_LAST + MouseButtonLeft MouseButton = C.GLFW_MOUSE_BUTTON_LEFT + MouseButtonRight MouseButton = C.GLFW_MOUSE_BUTTON_RIGHT + MouseButtonMiddle MouseButton = C.GLFW_MOUSE_BUTTON_MIDDLE +) + +// StandardCursor corresponds to a standard cursor icon. +type StandardCursor int + +// Standard cursors +const ( + ArrowCursor StandardCursor = C.GLFW_ARROW_CURSOR + IBeamCursor StandardCursor = C.GLFW_IBEAM_CURSOR + CrosshairCursor StandardCursor = C.GLFW_CROSSHAIR_CURSOR + HandCursor StandardCursor = C.GLFW_HAND_CURSOR + HResizeCursor StandardCursor = C.GLFW_HRESIZE_CURSOR + VResizeCursor StandardCursor = C.GLFW_VRESIZE_CURSOR +) + +// Action corresponds to a key or button action. +type Action int + +// Action types. +const ( + Release Action = C.GLFW_RELEASE // The key or button was released. + Press Action = C.GLFW_PRESS // The key or button was pressed. + Repeat Action = C.GLFW_REPEAT // The key was held down until it repeated. +) + +// InputMode corresponds to an input mode. +type InputMode int + +// Input modes. +const ( + CursorMode InputMode = C.GLFW_CURSOR // See Cursor mode values + StickyKeysMode InputMode = C.GLFW_STICKY_KEYS // Value can be either 1 or 0 + StickyMouseButtonsMode InputMode = C.GLFW_STICKY_MOUSE_BUTTONS // Value can be either 1 or 0 + LockKeyMods InputMode = C.GLFW_LOCK_KEY_MODS // Value can be either 1 or 0 + RawMouseMotion InputMode = C.GLFW_RAW_MOUSE_MOTION // Value can be either 1 or 0 +) + +// Cursor mode values. +const ( + CursorNormal int = C.GLFW_CURSOR_NORMAL + CursorHidden int = C.GLFW_CURSOR_HIDDEN + CursorDisabled int = C.GLFW_CURSOR_DISABLED +) + +// Cursor represents a cursor. +type Cursor struct { + data *C.GLFWcursor +} + +var fJoystickHolder func(joy Joystick, event PeripheralEvent) + +//export goJoystickCB +func goJoystickCB(joy, event C.int) { + fJoystickHolder(Joystick(joy), PeripheralEvent(event)) +} + +//export goMouseButtonCB +func goMouseButtonCB(window unsafe.Pointer, button, action, mods C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fMouseButtonHolder(w, MouseButton(button), Action(action), ModifierKey(mods)) +} + +//export goCursorPosCB +func goCursorPosCB(window unsafe.Pointer, xpos, ypos C.double) { + w := windows.get((*C.GLFWwindow)(window)) + w.fCursorPosHolder(w, float64(xpos), float64(ypos)) +} + +//export goCursorEnterCB +func goCursorEnterCB(window unsafe.Pointer, entered C.int) { + w := windows.get((*C.GLFWwindow)(window)) + hasEntered := glfwbool(entered) + w.fCursorEnterHolder(w, hasEntered) +} + +//export goScrollCB +func goScrollCB(window unsafe.Pointer, xoff, yoff C.double) { + w := windows.get((*C.GLFWwindow)(window)) + w.fScrollHolder(w, float64(xoff), float64(yoff)) +} + +//export goKeyCB +func goKeyCB(window unsafe.Pointer, key, scancode, action, mods C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fKeyHolder(w, Key(key), int(scancode), Action(action), ModifierKey(mods)) +} + +//export goCharCB +func goCharCB(window unsafe.Pointer, character C.uint) { + w := windows.get((*C.GLFWwindow)(window)) + w.fCharHolder(w, rune(character)) +} + +//export goCharModsCB +func goCharModsCB(window unsafe.Pointer, character C.uint, mods C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fCharModsHolder(w, rune(character), ModifierKey(mods)) +} + +//export goDropCB +func goDropCB(window unsafe.Pointer, count C.int, names **C.char) { // TODO: The types of name can be `**C.char` or `unsafe.Pointer`, use whichever is better. + w := windows.get((*C.GLFWwindow)(window)) + namesSlice := make([]string, int(count)) // TODO: Make this better. This part is unfinished, hacky, probably not correct, and not idiomatic. + for i := 0; i < int(count); i++ { // TODO: Make this better. It should be cleaned up and vetted. + var x *C.char // TODO: Make this better. + p := (**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(names)) + uintptr(i)*unsafe.Sizeof(x))) // TODO: Make this better. + namesSlice[i] = C.GoString(*p) // TODO: Make this better. + } + w.fDropHolder(w, namesSlice) +} + +// GetInputMode returns the value of an input option of the window. +func (w *Window) GetInputMode(mode InputMode) int { + ret := int(C.glfwGetInputMode(w.data, C.int(mode))) + panicError() + return ret +} + +// SetInputMode sets an input option for the window. +func (w *Window) SetInputMode(mode InputMode, value int) { + C.glfwSetInputMode(w.data, C.int(mode), C.int(value)) + panicError() +} + +// RawMouseMotionSupported returns whether raw mouse motion is supported on the +// current system. This status does not change after GLFW has been initialized +// so you only need to check this once. If you attempt to enable raw motion on +// a system that does not support it, PlatformError will be emitted. +// +// Raw mouse motion is closer to the actual motion of the mouse across a +// surface. It is not affected by the scaling and acceleration applied to the +// motion of the desktop cursor. That processing is suitable for a cursor while +// raw motion is better for controlling for example a 3D camera. Because of +// this, raw mouse motion is only provided when the cursor is disabled. +// +// This function must only be called from the main thread. +func RawMouseMotionSupported() bool { + return int(C.glfwRawMouseMotionSupported()) == True +} + +// GetKeyScancode function returns the platform-specific scancode of the +// specified key. +// +// If the key is KeyUnknown or does not exist on the keyboard this method will +// return -1. +func GetKeyScancode(key Key) int { + return int(C.glfwGetKeyScancode(C.int(key))) +} + +// GetKey returns the last reported state of a keyboard key. The returned state +// is one of Press or Release. The higher-level state Repeat is only reported to +// the key callback. +// +// If the StickyKeys input mode is enabled, this function returns Press the first +// time you call this function after a key has been pressed, even if the key has +// already been released. +// +// The key functions deal with physical keys, with key tokens named after their +// use on the standard US keyboard layout. If you want to input text, use the +// Unicode character callback instead. +func (w *Window) GetKey(key Key) Action { + ret := Action(C.glfwGetKey(w.data, C.int(key))) + panicError() + return ret +} + +// GetKeyName returns the localized name of the specified printable key. +// +// If the key is glfw.KeyUnknown, the scancode is used, otherwise the scancode is ignored. +func GetKeyName(key Key, scancode int) string { + ret := C.glfwGetKeyName(C.int(key), C.int(scancode)) + panicError() + return C.GoString(ret) +} + +// GetMouseButton returns the last state reported for the specified mouse button. +// +// If the StickyMouseButtons input mode is enabled, this function returns Press +// the first time you call this function after a mouse button has been pressed, +// even if the mouse button has already been released. +func (w *Window) GetMouseButton(button MouseButton) Action { + ret := Action(C.glfwGetMouseButton(w.data, C.int(button))) + panicError() + return ret +} + +// GetCursorPos returns the last reported position of the cursor. +// +// If the cursor is disabled (with CursorDisabled) then the cursor position is +// unbounded and limited only by the minimum and maximum values of a double. +// +// The coordinate can be converted to their integer equivalents with the floor +// function. Casting directly to an integer type works for positive coordinates, +// but fails for negative ones. +func (w *Window) GetCursorPos() (x, y float64) { + var xpos, ypos C.double + C.glfwGetCursorPos(w.data, &xpos, &ypos) + panicError() + return float64(xpos), float64(ypos) +} + +// SetCursorPos sets the position of the cursor. The specified window must +// be focused. If the window does not have focus when this function is called, +// it fails silently. +// +// If the cursor is disabled (with CursorDisabled) then the cursor position is +// unbounded and limited only by the minimum and maximum values of a double. +func (w *Window) SetCursorPos(xpos, ypos float64) { + C.glfwSetCursorPos(w.data, C.double(xpos), C.double(ypos)) + panicError() +} + +// CreateCursor creates a new custom cursor image that can be set for a window with SetCursor. +// The cursor can be destroyed with Destroy. Any remaining cursors are destroyed by Terminate. +// +// The image is ideally provided in the form of *image.NRGBA. +// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight +// bits per channel with the red channel first. They are arranged canonically +// as packed sequential rows, starting from the top-left corner. If the image +// type is not *image.NRGBA, it will be converted to it. +// +// The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. +// Like all other coordinate systems in GLFW, the X-axis points to the right and the Y-axis points down. +func CreateCursor(img image.Image, xhot, yhot int) *Cursor { + imgC, free := imageToGLFW(img) + + c := C.glfwCreateCursor(&imgC, C.int(xhot), C.int(yhot)) + + free() + panicError() + + return &Cursor{c} +} + +// CreateStandardCursor returns a cursor with a standard shape, +// that can be set for a window with SetCursor. +func CreateStandardCursor(shape StandardCursor) *Cursor { + c := C.glfwCreateStandardCursor(C.int(shape)) + panicError() + return &Cursor{c} +} + +// Destroy destroys a cursor previously created with CreateCursor. +// Any remaining cursors will be destroyed by Terminate. +func (c *Cursor) Destroy() { + C.glfwDestroyCursor(c.data) + panicError() +} + +// SetCursor sets the cursor image to be used when the cursor is over the client area +// of the specified window. The set cursor will only be visible when the cursor mode of the +// window is CursorNormal. +// +// On some platforms, the set cursor may not be visible unless the window also has input focus. +func (w *Window) SetCursor(c *Cursor) { + if c == nil { + C.glfwSetCursor(w.data, nil) + } else { + C.glfwSetCursor(w.data, c.data) + } + panicError() +} + +// JoystickCallback is the joystick configuration callback. +type JoystickCallback func(joy Joystick, event PeripheralEvent) + +// SetJoystickCallback sets the joystick configuration callback, or removes the +// currently set callback. This is called when a joystick is connected to or +// disconnected from the system. +func SetJoystickCallback(cbfun JoystickCallback) (previous JoystickCallback) { + previous = fJoystickHolder + fJoystickHolder = cbfun + if cbfun == nil { + C.glfwSetJoystickCallback(nil) + } else { + C.glfwSetJoystickCallbackCB() + } + panicError() + return previous +} + +// KeyCallback is the key callback. +type KeyCallback func(w *Window, key Key, scancode int, action Action, mods ModifierKey) + +// SetKeyCallback sets the key callback which is called when a key is pressed, +// repeated or released. +// +// The key functions deal with physical keys, with layout independent key tokens +// named after their values in the standard US keyboard layout. If you want to +// input text, use the SetCharCallback instead. +// +// When a window loses focus, it will generate synthetic key release events for +// all pressed keys. You can tell these events from user-generated events by the +// fact that the synthetic ones are generated after the window has lost focus, +// i.e. Focused will be false and the focus callback will have already been +// called. +func (w *Window) SetKeyCallback(cbfun KeyCallback) (previous KeyCallback) { + previous = w.fKeyHolder + w.fKeyHolder = cbfun + if cbfun == nil { + C.glfwSetKeyCallback(w.data, nil) + } else { + C.glfwSetKeyCallbackCB(w.data) + } + panicError() + return previous +} + +// CharCallback is the character callback. +type CharCallback func(w *Window, char rune) + +// SetCharCallback sets the character callback which is called when a +// Unicode character is input. +// +// The character callback is intended for Unicode text input. As it deals with +// characters, it is keyboard layout dependent, whereas the +// key callback is not. Characters do not map 1:1 +// to physical keys, as a key may produce zero, one or more characters. If you +// want to know whether a specific physical key was pressed or released, see +// the key callback instead. +// +// The character callback behaves as system text input normally does and will +// not be called if modifier keys are held down that would prevent normal text +// input on that platform, for example a Super (Command) key on OS X or Alt key +// on Windows. There is a character with modifiers callback that receives these events. +func (w *Window) SetCharCallback(cbfun CharCallback) (previous CharCallback) { + previous = w.fCharHolder + w.fCharHolder = cbfun + if cbfun == nil { + C.glfwSetCharCallback(w.data, nil) + } else { + C.glfwSetCharCallbackCB(w.data) + } + panicError() + return previous +} + +// CharModsCallback is the character with modifiers callback. +type CharModsCallback func(w *Window, char rune, mods ModifierKey) + +// SetCharModsCallback sets the character with modifiers callback which is called when a +// Unicode character is input regardless of what modifier keys are used. +// +// Deprecated: Scheduled for removal in version 4.0. +// +// The character with modifiers callback is intended for implementing custom +// Unicode character input. For regular Unicode text input, see the +// character callback. Like the character callback, the character with modifiers callback +// deals with characters and is keyboard layout dependent. Characters do not +// map 1:1 to physical keys, as a key may produce zero, one or more characters. +// If you want to know whether a specific physical key was pressed or released, +// see the key callback instead. +func (w *Window) SetCharModsCallback(cbfun CharModsCallback) (previous CharModsCallback) { + previous = w.fCharModsHolder + w.fCharModsHolder = cbfun + if cbfun == nil { + C.glfwSetCharModsCallback(w.data, nil) + } else { + C.glfwSetCharModsCallbackCB(w.data) + } + panicError() + return previous +} + +// MouseButtonCallback is the mouse button callback. +type MouseButtonCallback func(w *Window, button MouseButton, action Action, mods ModifierKey) + +// SetMouseButtonCallback sets the mouse button callback which is called when a +// mouse button is pressed or released. +// +// When a window loses focus, it will generate synthetic mouse button release +// events for all pressed mouse buttons. You can tell these events from +// user-generated events by the fact that the synthetic ones are generated after +// the window has lost focus, i.e. Focused will be false and the focus +// callback will have already been called. +func (w *Window) SetMouseButtonCallback(cbfun MouseButtonCallback) (previous MouseButtonCallback) { + previous = w.fMouseButtonHolder + w.fMouseButtonHolder = cbfun + if cbfun == nil { + C.glfwSetMouseButtonCallback(w.data, nil) + } else { + C.glfwSetMouseButtonCallbackCB(w.data) + } + panicError() + return previous +} + +// CursorPosCallback the cursor position callback. +type CursorPosCallback func(w *Window, xpos float64, ypos float64) + +// SetCursorPosCallback sets the cursor position callback which is called +// when the cursor is moved. The callback is provided with the position relative +// to the upper-left corner of the client area of the window. +func (w *Window) SetCursorPosCallback(cbfun CursorPosCallback) (previous CursorPosCallback) { + previous = w.fCursorPosHolder + w.fCursorPosHolder = cbfun + if cbfun == nil { + C.glfwSetCursorPosCallback(w.data, nil) + } else { + C.glfwSetCursorPosCallbackCB(w.data) + } + panicError() + return previous +} + +// CursorEnterCallback is the cursor boundary crossing callback. +type CursorEnterCallback func(w *Window, entered bool) + +// SetCursorEnterCallback the cursor boundary crossing callback which is called +// when the cursor enters or leaves the client area of the window. +func (w *Window) SetCursorEnterCallback(cbfun CursorEnterCallback) (previous CursorEnterCallback) { + previous = w.fCursorEnterHolder + w.fCursorEnterHolder = cbfun + if cbfun == nil { + C.glfwSetCursorEnterCallback(w.data, nil) + } else { + C.glfwSetCursorEnterCallbackCB(w.data) + } + panicError() + return previous +} + +// ScrollCallback is the scroll callback. +type ScrollCallback func(w *Window, xoff float64, yoff float64) + +// SetScrollCallback sets the scroll callback which is called when a scrolling +// device is used, such as a mouse wheel or scrolling area of a touchpad. +func (w *Window) SetScrollCallback(cbfun ScrollCallback) (previous ScrollCallback) { + previous = w.fScrollHolder + w.fScrollHolder = cbfun + if cbfun == nil { + C.glfwSetScrollCallback(w.data, nil) + } else { + C.glfwSetScrollCallbackCB(w.data) + } + panicError() + return previous +} + +// DropCallback is the drop callback. +type DropCallback func(w *Window, names []string) + +// SetDropCallback sets the drop callback which is called when an object +// is dropped over the window. +func (w *Window) SetDropCallback(cbfun DropCallback) (previous DropCallback) { + previous = w.fDropHolder + w.fDropHolder = cbfun + if cbfun == nil { + C.glfwSetDropCallback(w.data, nil) + } else { + C.glfwSetDropCallbackCB(w.data) + } + panicError() + return previous +} + +// Present returns whether the specified joystick is present. +// +// There is no need to call this function before other methods of Joystick type +// as they all check for presence before performing any other work. +// +// This function must only be called from the main thread. +func (joy Joystick) Present() bool { + return glfwbool(C.glfwJoystickPresent(C.int(joy))) +} + +// GetAxes returns the values of all axes of the specified joystick. Each +// element in the array is a value between -1.0 and 1.0. +// +// If the specified joystick is not present this function will return nil but +// will not generate an error. This can be used instead of first calling +// Present. +// +// This function must only be called from the main thread. +func (joy Joystick) GetAxes() []float32 { + var length int + + axis := C.glfwGetJoystickAxes(C.int(joy), (*C.int)(unsafe.Pointer(&length))) + if axis == nil { + return nil + } + + a := make([]float32, length) + for i := 0; i < length; i++ { + a[i] = float32(C.GetAxisAtIndex(axis, C.int(i))) + } + return a +} + +// GetButtons returns the state of all buttons of the specified joystick. Each +// element in the array is either Press or Release. +// +// For backward compatibility with earlier versions that did not have GetHats, +// the button array also includes all hats, each represented as four buttons. +// The hats are in the same order as returned by GetHats and are in the order +// up, right, down and left. To disable these extra buttons, set the +// JoystickHatButtons init hint before initialization. +// +// If the specified joystick is not present this function will return nil but +// will not generate an error. This can be used instead of first calling +// Present. +// +// This function must only be called from the main thread. +func (joy Joystick) GetButtons() []Action { + var length int + + buttons := C.glfwGetJoystickButtons( + C.int(joy), + (*C.int)(unsafe.Pointer(&length)), + ) + if buttons == nil { + return nil + } + + b := make([]Action, length) + for i := 0; i < length; i++ { + b[i] = Action(C.GetButtonsAtIndex(buttons, C.int(i))) + } + return b +} + +// GetHats returns the state of all hats of the specified joystick. +// +// If the specified joystick is not present this function will return nil but +// will not generate an error. This can be used instead of first calling +// Present. +// +// This function must only be called from the main thread. +func (joy Joystick) GetHats() []JoystickHatState { + var length int + + hats := C.glfwGetJoystickHats(C.int(joy), (*C.int)(unsafe.Pointer(&length))) + if hats == nil { + return nil + } + + b := make([]JoystickHatState, length) + for i := 0; i < length; i++ { + b[i] = JoystickHatState(C.GetButtonsAtIndex(hats, C.int(i))) + } + return b +} + +// GetName returns the name, encoded as UTF-8, of the specified joystick. +// +// If the specified joystick is not present this function will return nil but +// will not generate an error. This can be used instead of first calling +// Present. +// +// This function must only be called from the main thread. +func (joy Joystick) GetName() string { + jn := C.glfwGetJoystickName(C.int(joy)) + return C.GoString(jn) +} + +// GetGUID returns the SDL compatible GUID, as a UTF-8 encoded +// hexadecimal string, of the specified joystick. +// +// The GUID is what connects a joystick to a gamepad mapping. A connected +// joystick will always have a GUID even if there is no gamepad mapping +// assigned to it. +// +// If the specified joystick is not present this function will return empty +// string but will not generate an error. This can be used instead of first +// calling JoystickPresent. +// +// The GUID uses the format introduced in SDL 2.0.5. This GUID tries to uniquely +// identify the make and model of a joystick but does not identify a specific +// unit, e.g. all wired Xbox 360 controllers will have the same GUID on that +// platform. The GUID for a unit may vary between platforms depending on what +// hardware information the platform specific APIs provide. +// +// This function must only be called from the main thread. +func (joy Joystick) GetGUID() string { + guid := C.glfwGetJoystickGUID(C.int(joy)) + return C.GoString(guid) +} + +// SetUserPointer sets the user-defined pointer of the joystick. The current value +// is retained until the joystick is disconnected. The initial value is nil. +// +// This function may be called from the joystick callback, even for a joystick +// that is being disconnected. +// +// This function may be called from any thread. Access is not synchronized. +func (joy Joystick) SetUserPointer(pointer unsafe.Pointer) { + C.glfwSetJoystickUserPointer(C.int(joy), pointer) +} + +// GetUserPointer returns the current value of the user-defined pointer of the +// joystick. The initial value is nil. +// +// This function may be called from the joystick callback, even for a joystick +// that is being disconnected. +// +// This function may be called from any thread. Access is not synchronized. +func (joy Joystick) GetUserPointer() unsafe.Pointer { + return C.glfwGetJoystickUserPointer(C.int(joy)) +} + +// IsGamepad returns whether the specified joystick is both present and +// has a gamepad mapping. +// +// If the specified joystick is present but does not have a gamepad mapping this +// function will return false but will not generate an error. Call Present to +// check if a joystick is present regardless of whether it has a mapping. +// +// This function must only be called from the main thread. +func (joy Joystick) IsGamepad() bool { + return glfwbool(C.glfwJoystickIsGamepad(C.int(joy))) +} + +// UpdateGamepadMappings parses the specified ASCII encoded string and updates +// the internal list with any gamepad mappings it finds. This string may contain +// either a single gamepad mapping or many mappings separated by newlines. The +// parser supports the full format of the gamecontrollerdb.txt source file +// including empty lines and comments. +// +// See Gamepad mappings for a description of the format. +// +// If there is already a gamepad mapping for a given GUID in the internal list, +// it will be replaced by the one passed to this function. If the library is +// terminated and re-initialized the internal list will revert to the built-in +// default. +// +// This function must only be called from the main thread. +func UpdateGamepadMappings(mapping string) bool { + m := C.CString(mapping) + defer C.free(unsafe.Pointer(m)) + return glfwbool(C.glfwUpdateGamepadMappings(m)) +} + +// GetGamepadName returns the human-readable name of the gamepad from the +// gamepad mapping assigned to the specified joystick. +// +// If the specified joystick is not present or does not have a gamepad mapping +// this function will return empty string but will not generate an error. Call +// Present to check whether it is present regardless of whether it has a +// mapping. +// +// This function must only be called from the main thread. +func (joy Joystick) GetGamepadName() string { + gn := C.glfwGetGamepadName(C.int(joy)) + return C.GoString(gn) +} + +// GetGamepadState retrives the state of the specified joystick remapped to an +// Xbox-like gamepad. +// +// If the specified joystick is not present or does not have a gamepad mapping +// this function will return nil but will not generate an error. Call +// Present to check whether it is present regardless of whether it has a +// mapping. +// +// The Guide button may not be available for input as it is often hooked by the +// system or the Steam client. +// +// Not all devices have all the buttons or axes provided by GamepadState. +// Unavailable buttons and axes will always report Release and 0.0 respectively. +// +// This function must only be called from the main thread. +func (joy Joystick) GetGamepadState() *GamepadState { + var ( + gs GamepadState + cgs C.GLFWgamepadstate + ) + + ret := C.glfwGetGamepadState(C.int(joy), &cgs) + if ret == C.GLFW_FALSE { + return nil + } + + for i := 0; i < 15; i++ { + gs.Buttons[i] = Action(C.GetGamepadButtonAtIndex(&cgs, C.int(i))) + } + + for i := 0; i < 6; i++ { + gs.Axes[i] = float32(C.GetGamepadAxisAtIndex(&cgs, C.int(i))) + } + + return &gs +} diff --git a/v3.4/glfw/monitor.c b/v3.4/glfw/monitor.c new file mode 100644 index 00000000..55107eab --- /dev/null +++ b/v3.4/glfw/monitor.c @@ -0,0 +1,19 @@ +#include "_cgo_export.h" + +GLFWmonitor *GetMonitorAtIndex(GLFWmonitor **monitors, int index) { + return monitors[index]; +} + +GLFWvidmode GetVidmodeAtIndex(GLFWvidmode *vidmodes, int index) { + return vidmodes[index]; +} + +void glfwSetMonitorCallbackCB() { + glfwSetMonitorCallback((GLFWmonitorfun)goMonitorCB); +} + +unsigned int GetGammaAtIndex(unsigned short *color, int i) { return color[i]; } + +void SetGammaAtIndex(unsigned short *color, int i, unsigned short value) { + color[i] = value; +} diff --git a/v3.4/glfw/monitor.go b/v3.4/glfw/monitor.go new file mode 100644 index 00000000..28757ad6 --- /dev/null +++ b/v3.4/glfw/monitor.go @@ -0,0 +1,267 @@ +package glfw + +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//GLFWmonitor* GetMonitorAtIndex(GLFWmonitor **monitors, int index); +//GLFWvidmode GetVidmodeAtIndex(GLFWvidmode *vidmodes, int index); +//void glfwSetMonitorCallbackCB(); +//unsigned int GetGammaAtIndex(unsigned short *color, int i); +//void SetGammaAtIndex(unsigned short *color, int i, unsigned short value); +import "C" + +import ( + "unsafe" +) + +// Monitor represents a monitor. +type Monitor struct { + data *C.GLFWmonitor +} + +// PeripheralEvent corresponds to a peripheral(Monitor or Joystick) +// configuration event. +type PeripheralEvent int + +// GammaRamp describes the gamma ramp for a monitor. +type GammaRamp struct { + Red []uint16 // A slice of value describing the response of the red channel. + Green []uint16 // A slice of value describing the response of the green channel. + Blue []uint16 // A slice of value describing the response of the blue channel. +} + +// PeripheralEvent events. +const ( + Connected PeripheralEvent = C.GLFW_CONNECTED + Disconnected PeripheralEvent = C.GLFW_DISCONNECTED +) + +// VidMode describes a single video mode. +type VidMode struct { + Width int // The width, in pixels, of the video mode. + Height int // The height, in pixels, of the video mode. + RedBits int // The bit depth of the red channel of the video mode. + GreenBits int // The bit depth of the green channel of the video mode. + BlueBits int // The bit depth of the blue channel of the video mode. + RefreshRate int // The refresh rate, in Hz, of the video mode. +} + +var fMonitorHolder func(monitor *Monitor, event PeripheralEvent) + +//export goMonitorCB +func goMonitorCB(monitor unsafe.Pointer, event C.int) { + fMonitorHolder(&Monitor{(*C.GLFWmonitor)(monitor)}, PeripheralEvent(event)) +} + +// GetMonitors returns a slice of handles for all currently connected monitors. +func GetMonitors() []*Monitor { + var length int + + mC := C.glfwGetMonitors((*C.int)(unsafe.Pointer(&length))) + panicError() + if mC == nil { + return nil + } + + m := make([]*Monitor, length) + + for i := 0; i < length; i++ { + m[i] = &Monitor{C.GetMonitorAtIndex(mC, C.int(i))} + } + + return m +} + +// GetPrimaryMonitor returns the primary monitor. This is usually the monitor +// where elements like the Windows task bar or the OS X menu bar is located. +func GetPrimaryMonitor() *Monitor { + m := C.glfwGetPrimaryMonitor() + panicError() + if m == nil { + return nil + } + return &Monitor{m} +} + +// GetPos returns the position, in screen coordinates, of the upper-left +// corner of the monitor. +func (m *Monitor) GetPos() (x, y int) { + var xpos, ypos C.int + C.glfwGetMonitorPos(m.data, &xpos, &ypos) + panicError() + return int(xpos), int(ypos) +} + +// GetWorkarea returns the position, in screen coordinates, of the upper-left +// corner of the work area of the specified monitor along with the work area +// size in screen coordinates. The work area is defined as the area of the +// monitor not occluded by the operating system task bar where present. If no +// task bar exists then the work area is the monitor resolution in screen +// coordinates. +// +// This function must only be called from the main thread. +func (m *Monitor) GetWorkarea() (x, y, width, height int) { + var cX, cY, cWidth, cHeight C.int + C.glfwGetMonitorWorkarea(m.data, &cX, &cY, &cWidth, &cHeight) + x, y, width, height = int(cX), int(cY), int(cWidth), int(cHeight) + return +} + +// GetContentScale function retrieves the content scale for the specified monitor. +// The content scale is the ratio between the current DPI and the platform's +// default DPI. If you scale all pixel dimensions by this scale then your content +// should appear at an appropriate size. This is especially important for text +// and any UI elements. +// +// This function must only be called from the main thread. +func (m *Monitor) GetContentScale() (float32, float32) { + var x, y C.float + C.glfwGetMonitorContentScale(m.data, &x, &y) + return float32(x), float32(y) +} + +// SetUserPointer sets the user-defined pointer of the monitor. The current value +// is retained until the monitor is disconnected. The initial value is nil. +// +// This function may be called from the monitor callback, even for a monitor +// that is being disconnected. +// +// This function may be called from any thread. Access is not synchronized. +func (m *Monitor) SetUserPointer(pointer unsafe.Pointer) { + C.glfwSetMonitorUserPointer(m.data, pointer) +} + +// GetUserPointer returns the current value of the user-defined pointer of the +// monitor. The initial value is nil. +// +// This function may be called from the monitor callback, even for a monitor +// that is being disconnected. +// +// This function may be called from any thread. Access is not synchronized. +func (m *Monitor) GetUserPointer() unsafe.Pointer { + return C.glfwGetMonitorUserPointer(m.data) +} + +// GetPhysicalSize returns the size, in millimetres, of the display area of the +// monitor. +// +// Note: Some operating systems do not provide accurate information, either +// because the monitor's EDID data is incorrect, or because the driver does not +// report it accurately. +func (m *Monitor) GetPhysicalSize() (width, height int) { + var wi, h C.int + C.glfwGetMonitorPhysicalSize(m.data, &wi, &h) + panicError() + return int(wi), int(h) +} + +// GetName returns a human-readable name of the monitor, encoded as UTF-8. +func (m *Monitor) GetName() string { + mn := C.glfwGetMonitorName(m.data) + panicError() + if mn == nil { + return "" + } + return C.GoString(mn) +} + +// MonitorCallback is the signature for monitor configuration callback +// functions. +type MonitorCallback func(monitor *Monitor, event PeripheralEvent) + +// SetMonitorCallback sets the monitor configuration callback, or removes the +// currently set callback. This is called when a monitor is connected to or +// disconnected from the system. +// +// This function must only be called from the main thread. +func SetMonitorCallback(cbfun MonitorCallback) MonitorCallback { + previous := fMonitorHolder + fMonitorHolder = cbfun + if cbfun == nil { + C.glfwSetMonitorCallback(nil) + } else { + C.glfwSetMonitorCallbackCB() + } + return previous +} + +// GetVideoModes returns an array of all video modes supported by the monitor. +// The returned array is sorted in ascending order, first by color bit depth +// (the sum of all channel depths) and then by resolution area (the product of +// width and height). +func (m *Monitor) GetVideoModes() []*VidMode { + var length int + + vC := C.glfwGetVideoModes(m.data, (*C.int)(unsafe.Pointer(&length))) + panicError() + if vC == nil { + return nil + } + + v := make([]*VidMode, length) + + for i := 0; i < length; i++ { + t := C.GetVidmodeAtIndex(vC, C.int(i)) + v[i] = &VidMode{int(t.width), int(t.height), int(t.redBits), int(t.greenBits), int(t.blueBits), int(t.refreshRate)} + } + + return v +} + +// GetVideoMode returns the current video mode of the monitor. If you +// are using a full screen window, the return value will therefore depend on +// whether it is focused. +func (m *Monitor) GetVideoMode() *VidMode { + t := C.glfwGetVideoMode(m.data) + if t == nil { + return nil + } + panicError() + return &VidMode{int(t.width), int(t.height), int(t.redBits), int(t.greenBits), int(t.blueBits), int(t.refreshRate)} +} + +// SetGamma generates a 256-element gamma ramp from the specified exponent and then calls +// SetGamma with it. +func (m *Monitor) SetGamma(gamma float32) { + C.glfwSetGamma(m.data, C.float(gamma)) + panicError() +} + +// GetGammaRamp retrieves the current gamma ramp of the monitor. +func (m *Monitor) GetGammaRamp() *GammaRamp { + var ramp GammaRamp + + rampC := C.glfwGetGammaRamp(m.data) + panicError() + if rampC == nil { + return nil + } + + length := int(rampC.size) + ramp.Red = make([]uint16, length) + ramp.Green = make([]uint16, length) + ramp.Blue = make([]uint16, length) + + for i := 0; i < length; i++ { + ramp.Red[i] = uint16(C.GetGammaAtIndex(rampC.red, C.int(i))) + ramp.Green[i] = uint16(C.GetGammaAtIndex(rampC.green, C.int(i))) + ramp.Blue[i] = uint16(C.GetGammaAtIndex(rampC.blue, C.int(i))) + } + + return &ramp +} + +// SetGammaRamp sets the current gamma ramp for the monitor. +func (m *Monitor) SetGammaRamp(ramp *GammaRamp) { + var rampC C.GLFWgammaramp + + length := len(ramp.Red) + + for i := 0; i < length; i++ { + C.SetGammaAtIndex(rampC.red, C.int(i), C.ushort(ramp.Red[i])) + C.SetGammaAtIndex(rampC.green, C.int(i), C.ushort(ramp.Green[i])) + C.SetGammaAtIndex(rampC.blue, C.int(i), C.ushort(ramp.Blue[i])) + } + + C.glfwSetGammaRamp(m.data, &rampC) + panicError() +} diff --git a/v3.4/glfw/native_darwin.go b/v3.4/glfw/native_darwin.go new file mode 100644 index 00000000..891827b1 --- /dev/null +++ b/v3.4/glfw/native_darwin.go @@ -0,0 +1,40 @@ +package glfw + +/* +#define GLFW_EXPOSE_NATIVE_COCOA +#define GLFW_EXPOSE_NATIVE_NSGL +#include "glfw/include/GLFW/glfw3.h" +#include "glfw/include/GLFW/glfw3native.h" + +// workaround wrappers needed due to a cgo and/or LLVM bug. +// See: https://github.com/go-gl/glfw/issues/136 +void *workaround_glfwGetCocoaWindow(GLFWwindow *w) { + return (void *)glfwGetCocoaWindow(w); +} +void *workaround_glfwGetNSGLContext(GLFWwindow *w) { + return (void *)glfwGetNSGLContext(w); +} +*/ +import "C" +import "unsafe" + +// GetCocoaMonitor returns the CGDirectDisplayID of the monitor. +func (m *Monitor) GetCocoaMonitor() uintptr { + ret := uintptr(C.glfwGetCocoaMonitor(m.data)) + panicError() + return ret +} + +// GetCocoaWindow returns the NSWindow of the window. +func (w *Window) GetCocoaWindow() unsafe.Pointer { + ret := C.workaround_glfwGetCocoaWindow(w.data) + panicError() + return ret +} + +// GetNSGLContext returns the NSOpenGLContext of the window. +func (w *Window) GetNSGLContext() unsafe.Pointer { + ret := C.workaround_glfwGetNSGLContext(w.data) + panicError() + return ret +} diff --git a/v3.4/glfw/native_linbsd_wayland.go b/v3.4/glfw/native_linbsd_wayland.go new file mode 100644 index 00000000..d4118c15 --- /dev/null +++ b/v3.4/glfw/native_linbsd_wayland.go @@ -0,0 +1,48 @@ +//go:build (linux && wayland) || (freebsd && wayland) || (netbsd && wayland) || (openbsd && wayland) +// +build linux,wayland freebsd,wayland netbsd,wayland openbsd,wayland + +package glfw + +//#include +//#define GLFW_EXPOSE_NATIVE_WAYLAND +//#define GLFW_EXPOSE_NATIVE_EGL +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//#include "glfw/include/GLFW/glfw3native.h" +import "C" + +func GetWaylandDisplay() *C.struct_wl_display { + ret := C.glfwGetWaylandDisplay() + panicError() + return ret +} + +func (m *Monitor) GetWaylandMonitor() *C.struct_wl_output { + ret := C.glfwGetWaylandMonitor(m.data) + panicError() + return ret +} + +func (w *Window) GetWaylandWindow() *C.struct_wl_surface { + ret := C.glfwGetWaylandWindow(w.data) + panicError() + return ret +} + +func GetEGLDisplay() C.EGLDisplay { + ret := C.glfwGetEGLDisplay() + panicError() + return ret +} + +func (w *Window) GetEGLContext() C.EGLContext { + ret := C.glfwGetEGLContext(w.data) + panicError() + return ret +} + +func (w *Window) GetEGLSurface() C.EGLSurface { + ret := C.glfwGetEGLSurface(w.data) + panicError() + return ret +} diff --git a/v3.4/glfw/native_linbsd_x11.go b/v3.4/glfw/native_linbsd_x11.go new file mode 100644 index 00000000..83125e26 --- /dev/null +++ b/v3.4/glfw/native_linbsd_x11.go @@ -0,0 +1,67 @@ +//go:build (linux && !wayland) || (freebsd && !wayland) || (netbsd && !wayland) || (openbsd && !wayland) +// +build linux,!wayland freebsd,!wayland netbsd,!wayland openbsd,!wayland + +package glfw + +//#include +//#define GLFW_EXPOSE_NATIVE_X11 +//#define GLFW_EXPOSE_NATIVE_GLX +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//#include "glfw/include/GLFW/glfw3native.h" +import "C" +import "unsafe" + +func GetX11Display() *C.Display { + ret := C.glfwGetX11Display() + panicError() + return ret +} + +// GetX11Adapter returns the RRCrtc of the monitor. +func (m *Monitor) GetX11Adapter() C.RRCrtc { + ret := C.glfwGetX11Adapter(m.data) + panicError() + return ret +} + +// GetX11Monitor returns the RROutput of the monitor. +func (m *Monitor) GetX11Monitor() C.RROutput { + ret := C.glfwGetX11Monitor(m.data) + panicError() + return ret +} + +// GetX11Window returns the Window of the window. +func (w *Window) GetX11Window() C.Window { + ret := C.glfwGetX11Window(w.data) + panicError() + return ret +} + +// GetGLXContext returns the GLXContext of the window. +func (w *Window) GetGLXContext() C.GLXContext { + ret := C.glfwGetGLXContext(w.data) + panicError() + return ret +} + +// GetGLXWindow returns the GLXWindow of the window. +func (w *Window) GetGLXWindow() C.GLXWindow { + ret := C.glfwGetGLXWindow(w.data) + panicError() + return ret +} + +// SetX11SelectionString sets the X11 selection string. +func SetX11SelectionString(str string) { + s := C.CString(str) + defer C.free(unsafe.Pointer(s)) + C.glfwSetX11SelectionString(s) +} + +// GetX11SelectionString gets the X11 selection string. +func GetX11SelectionString() string { + s := C.glfwGetX11SelectionString() + return C.GoString(s) +} diff --git a/v3.4/glfw/native_windows.go b/v3.4/glfw/native_windows.go new file mode 100644 index 00000000..3a8a5c12 --- /dev/null +++ b/v3.4/glfw/native_windows.go @@ -0,0 +1,36 @@ +package glfw + +//#define GLFW_EXPOSE_NATIVE_WIN32 +//#define GLFW_EXPOSE_NATIVE_WGL +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//#include "glfw/include/GLFW/glfw3native.h" +import "C" + +// GetWin32Adapter returns the adapter device name of the monitor. +func (m *Monitor) GetWin32Adapter() string { + ret := C.glfwGetWin32Adapter(m.data) + panicError() + return C.GoString(ret) +} + +// GetWin32Monitor returns the display device name of the monitor. +func (m *Monitor) GetWin32Monitor() string { + ret := C.glfwGetWin32Monitor(m.data) + panicError() + return C.GoString(ret) +} + +// GetWin32Window returns the HWND of the window. +func (w *Window) GetWin32Window() C.HWND { + ret := C.glfwGetWin32Window(w.data) + panicError() + return ret +} + +// GetWGLContext returns the HGLRC of the window. +func (w *Window) GetWGLContext() C.HGLRC { + ret := C.glfwGetWGLContext(w.data) + panicError() + return ret +} diff --git a/v3.4/glfw/testdata/customcursor/main.go b/v3.4/glfw/testdata/customcursor/main.go new file mode 100644 index 00000000..d5ae454e --- /dev/null +++ b/v3.4/glfw/testdata/customcursor/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "image" + "image/color" + "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, "Custom Cursor", nil, nil) + if err != nil { + panic(err) + } + + window.MakeContextCurrent() + + // Creating a custom cursor. + cursor := glfw.CreateCursor(whiteTriangle, 0, 0) + window.SetCursor(cursor) + + // Setting a custom cursor. + window.SetIcon([]image.Image{whiteTriangle}) + + for !window.ShouldClose() { + // Do OpenGL stuff. + window.SwapBuffers() + glfw.PollEvents() + } +} + +var whiteTriangle = func() *image.NRGBA { + c := color.NRGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0xFF} + const size = 16 + m := image.NewNRGBA(image.Rect(0, 0, size, size)) + for y := 0; y < size; y++ { + for x := 0; x < size-y; x++ { + m.SetNRGBA(x, y, c) + } + } + return m +}() diff --git a/v3.4/glfw/time.go b/v3.4/glfw/time.go new file mode 100644 index 00000000..4c89b14e --- /dev/null +++ b/v3.4/glfw/time.go @@ -0,0 +1,42 @@ +package glfw + +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +import "C" + +// GetTime returns the value of the GLFW timer. Unless the timer has been set +// using SetTime, the timer measures time elapsed since GLFW was initialized. +// +// The resolution of the timer is system dependent, but is usually on the order +// of a few micro- or nanoseconds. It uses the highest-resolution monotonic time +// source on each supported platform. +func GetTime() float64 { + ret := float64(C.glfwGetTime()) + panicError() + return ret +} + +// SetTime sets the value of the GLFW timer. It then continues to count up from +// that value. +// +// The resolution of the timer is system dependent, but is usually on the order +// of a few micro- or nanoseconds. It uses the highest-resolution monotonic time +// source on each supported platform. +func SetTime(time float64) { + C.glfwSetTime(C.double(time)) + panicError() +} + +// GetTimerFrequency returns frequency of the timer, in Hz, or zero if an error occurred. +func GetTimerFrequency() uint64 { + ret := uint64(C.glfwGetTimerFrequency()) + panicError() + return ret +} + +// GetTimerValue returns the current value of the raw timer, measured in 1 / frequency seconds. +func GetTimerValue() uint64 { + ret := uint64(C.glfwGetTimerValue()) + panicError() + return ret +} diff --git a/v3.4/glfw/util.go b/v3.4/glfw/util.go new file mode 100644 index 00000000..aee7dea8 --- /dev/null +++ b/v3.4/glfw/util.go @@ -0,0 +1,46 @@ +package glfw + +//#include +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +import "C" + +import ( + "image" + "image/draw" +) + +func glfwbool(b C.int) bool { + return b == C.int(True) +} + +func bytes(origin []byte) (pointer *uint8, free func()) { + n := len(origin) + if n == 0 { + return nil, func() {} + } + + ptr := C.CBytes(origin) + return (*uint8)(ptr), func() { C.free(ptr) } +} + +// imageToGLFW converts img to be compatible with C.GLFWimage. +func imageToGLFW(img image.Image) (r C.GLFWimage, free func()) { + b := img.Bounds() + + r.width = C.int(b.Dx()) + r.height = C.int(b.Dy()) + + var pixels []byte + if m, ok := img.(*image.NRGBA); ok && m.Stride == b.Dx()*4 { + pixels = m.Pix[:m.PixOffset(m.Rect.Min.X, m.Rect.Max.Y)] + } else { + m := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) + draw.Draw(m, m.Bounds(), img, b.Min, draw.Src) + pixels = m.Pix + } + + pix, free := bytes(pixels) + r.pixels = (*C.uchar)(pix) + return r, free +} diff --git a/v3.4/glfw/vulkan.go b/v3.4/glfw/vulkan.go new file mode 100644 index 00000000..1ac29504 --- /dev/null +++ b/v3.4/glfw/vulkan.go @@ -0,0 +1,85 @@ +package glfw + +/* +#include "glfw/src/internal.h" + +GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); +GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); + +// Helper function for doing raw pointer arithmetic +static inline const char* getArrayIndex(const char** array, unsigned int index) { + return array[index]; +} + +void* getVulkanProcAddr() { + return glfwGetInstanceProcAddress; +} +*/ +import "C" +import ( + "errors" + "fmt" + "reflect" + "unsafe" +) + +// VulkanSupported reports whether the Vulkan loader has been found. This check is performed by Init. +// +// The availability of a Vulkan loader does not by itself guarantee that window surface creation or +// even device creation is possible. Call GetRequiredInstanceExtensions to check whether the +// extensions necessary for Vulkan surface creation are available and GetPhysicalDevicePresentationSupport +// to check whether a queue family of a physical device supports image presentation. +func VulkanSupported() bool { + return glfwbool(C.glfwVulkanSupported()) +} + +// GetVulkanGetInstanceProcAddress returns the function pointer used to find Vulkan core or +// extension functions. The return value of this function can be passed to the Vulkan library. +// +// Note that this function does not work the same way as the glfwGetInstanceProcAddress. +func GetVulkanGetInstanceProcAddress() unsafe.Pointer { + return C.getVulkanProcAddr() +} + +// GetRequiredInstanceExtensions returns a slice of Vulkan instance extension names required +// by GLFW for creating Vulkan surfaces for GLFW windows. If successful, the list will always +// contain VK_KHR_surface, so if you don't require any additional extensions you can pass this list +// directly to the VkInstanceCreateInfo struct. +// +// If Vulkan is not available on the machine, this function returns nil. Call +// VulkanSupported to check whether Vulkan is available. +// +// If Vulkan is available but no set of extensions allowing window surface creation was found, this +// function returns nil. You may still use Vulkan for off-screen rendering and compute work. +func (window *Window) GetRequiredInstanceExtensions() []string { + var count C.uint32_t + strarr := C.glfwGetRequiredInstanceExtensions(&count) + if count == 0 { + return nil + } + + extensions := make([]string, count) + for i := uint(0); i < uint(count); i++ { + extensions[i] = C.GoString(C.getArrayIndex(strarr, C.uint(i))) + } + return extensions +} + +// CreateWindowSurface creates a Vulkan surface for this window. +func (window *Window) CreateWindowSurface(instance interface{}, allocCallbacks unsafe.Pointer) (surface uintptr, err error) { + if instance == nil { + return 0, errors.New("vulkan: instance is nil") + } + val := reflect.ValueOf(instance) + if val.Kind() != reflect.Ptr { + return 0, fmt.Errorf("vulkan: instance is not a VkInstance (expected kind Ptr, got %s)", val.Kind()) + } + var vulkanSurface C.VkSurfaceKHR + ret := C.glfwCreateWindowSurface( + (C.VkInstance)(unsafe.Pointer(reflect.ValueOf(instance).Pointer())), window.data, + (*C.VkAllocationCallbacks)(allocCallbacks), (*C.VkSurfaceKHR)(unsafe.Pointer(&vulkanSurface))) + if ret != C.VK_SUCCESS { + return 0, fmt.Errorf("vulkan: error creating window surface: %d", ret) + } + return uintptr(unsafe.Pointer(&vulkanSurface)), nil +} diff --git a/v3.4/glfw/window.c b/v3.4/glfw/window.c new file mode 100644 index 00000000..17cf713d --- /dev/null +++ b/v3.4/glfw/window.c @@ -0,0 +1,40 @@ +#include "_cgo_export.h" + +void glfwSetWindowPosCallbackCB(GLFWwindow *window) { + glfwSetWindowPosCallback(window, (GLFWwindowposfun)goWindowPosCB); +} + +void glfwSetWindowSizeCallbackCB(GLFWwindow *window) { + glfwSetWindowSizeCallback(window, (GLFWwindowsizefun)goWindowSizeCB); +} + +void glfwSetWindowCloseCallbackCB(GLFWwindow *window) { + glfwSetWindowCloseCallback(window, (GLFWwindowclosefun)goWindowCloseCB); +} + +void glfwSetWindowRefreshCallbackCB(GLFWwindow *window) { + glfwSetWindowRefreshCallback(window, (GLFWwindowrefreshfun)goWindowRefreshCB); +} + +void glfwSetWindowFocusCallbackCB(GLFWwindow *window) { + glfwSetWindowFocusCallback(window, (GLFWwindowfocusfun)goWindowFocusCB); +} + +void glfwSetWindowIconifyCallbackCB(GLFWwindow *window) { + glfwSetWindowIconifyCallback(window, (GLFWwindowiconifyfun)goWindowIconifyCB); +} + +void glfwSetFramebufferSizeCallbackCB(GLFWwindow *window) { + glfwSetFramebufferSizeCallback(window, + (GLFWframebuffersizefun)goFramebufferSizeCB); +} + +void glfwSetWindowMaximizeCallbackCB(GLFWwindow *window) { + glfwSetWindowMaximizeCallback(window, + (GLFWwindowmaximizefun)goWindowMaximizeCB); +} + +void glfwSetWindowContentScaleCallbackCB(GLFWwindow *window) { + glfwSetWindowContentScaleCallback( + window, (GLFWwindowcontentscalefun)goWindowContentScaleCB); +} diff --git a/v3.4/glfw/window.go b/v3.4/glfw/window.go new file mode 100644 index 00000000..cdbf2c34 --- /dev/null +++ b/v3.4/glfw/window.go @@ -0,0 +1,990 @@ +package glfw + +//#include +//#define GLFW_INCLUDE_NONE +//#include "glfw/include/GLFW/glfw3.h" +//void glfwSetWindowPosCallbackCB(GLFWwindow *window); +//void glfwSetWindowSizeCallbackCB(GLFWwindow *window); +//void glfwSetFramebufferSizeCallbackCB(GLFWwindow *window); +//void glfwSetWindowCloseCallbackCB(GLFWwindow *window); +//void glfwSetWindowRefreshCallbackCB(GLFWwindow *window); +//void glfwSetWindowFocusCallbackCB(GLFWwindow *window); +//void glfwSetWindowIconifyCallbackCB(GLFWwindow *window); +//void glfwSetWindowMaximizeCallbackCB(GLFWwindow *window); +//void glfwSetWindowContentScaleCallbackCB(GLFWwindow *window); +import "C" + +import ( + "image" + "sync" + "unsafe" +) + +// Internal window list stuff +type windowList struct { + l sync.Mutex + m map[*C.GLFWwindow]*Window +} + +var windows = windowList{m: map[*C.GLFWwindow]*Window{}} + +func (w *windowList) put(wnd *Window) { + w.l.Lock() + defer w.l.Unlock() + w.m[wnd.data] = wnd +} + +func (w *windowList) remove(wnd *C.GLFWwindow) { + w.l.Lock() + defer w.l.Unlock() + delete(w.m, wnd) +} + +func (w *windowList) get(wnd *C.GLFWwindow) *Window { + w.l.Lock() + defer w.l.Unlock() + return w.m[wnd] +} + +// Hint corresponds to hints that can be set before creating a window. +// +// Hint also corresponds to the attributes of the window that can be get after +// its creation. +type Hint int + +// Init related hints. (Use with glfw.InitHint) +const ( + JoystickHatButtons Hint = C.GLFW_JOYSTICK_HAT_BUTTONS // Specifies whether to also expose joystick hats as buttons, for compatibility with earlier versions of GLFW that did not have glfwGetJoystickHats. + CocoaChdirResources Hint = C.GLFW_COCOA_CHDIR_RESOURCES // Specifies whether to set the current directory to the application to the Contents/Resources subdirectory of the application's bundle, if present. + CocoaMenubar Hint = C.GLFW_COCOA_MENUBAR // Specifies whether to create a basic menu bar, either from a nib or manually, when the first window is created, which is when AppKit is initialized. +) + +// Window related hints/attributes. +const ( + Focused Hint = C.GLFW_FOCUSED // Specifies whether the window will be given input focus when created. This hint is ignored for full screen and initially hidden windows. + Iconified Hint = C.GLFW_ICONIFIED // Specifies whether the window will be minimized. + Maximized Hint = C.GLFW_MAXIMIZED // Specifies whether the window is maximized. + Visible Hint = C.GLFW_VISIBLE // Specifies whether the window will be initially visible. + Hovered Hint = C.GLFW_HOVERED // Specifies whether the cursor is currently directly over the content area of the window, with no other windows between. See Cursor enter/leave events for details. + Resizable Hint = C.GLFW_RESIZABLE // Specifies whether the window will be resizable by the user. + Decorated Hint = C.GLFW_DECORATED // Specifies whether the window will have window decorations such as a border, a close widget, etc. + Floating Hint = C.GLFW_FLOATING // Specifies whether the window will be always-on-top. + AutoIconify Hint = C.GLFW_AUTO_ICONIFY // Specifies whether fullscreen windows automatically iconify (and restore the previous video mode) on focus loss. + CenterCursor Hint = C.GLFW_CENTER_CURSOR // Specifies whether the cursor should be centered over newly created full screen windows. This hint is ignored for windowed mode windows. + TransparentFramebuffer Hint = C.GLFW_TRANSPARENT_FRAMEBUFFER // Specifies whether the framebuffer should be transparent. + FocusOnShow Hint = C.GLFW_FOCUS_ON_SHOW // Specifies whether the window will be given input focus when glfwShowWindow is called. + ScaleToMonitor Hint = C.GLFW_SCALE_TO_MONITOR // Specified whether the window content area should be resized based on the monitor content scale of any monitor it is placed on. This includes the initial placement when the window is created. +) + +// Context related hints. +const ( + ClientAPI Hint = C.GLFW_CLIENT_API // Specifies which client API to create the context for. Hard constraint. + ContextVersionMajor Hint = C.GLFW_CONTEXT_VERSION_MAJOR // Specifies the client API version that the created context must be compatible with. + ContextVersionMinor Hint = C.GLFW_CONTEXT_VERSION_MINOR // Specifies the client API version that the created context must be compatible with. + ContextRobustness Hint = C.GLFW_CONTEXT_ROBUSTNESS // Specifies the robustness strategy to be used by the context. + ContextReleaseBehavior Hint = C.GLFW_CONTEXT_RELEASE_BEHAVIOR // Specifies the release behavior to be used by the context. + OpenGLForwardCompatible Hint = C.GLFW_OPENGL_FORWARD_COMPAT // Specifies whether the OpenGL context should be forward-compatible. Hard constraint. + OpenGLDebugContext Hint = C.GLFW_OPENGL_DEBUG_CONTEXT // Specifies whether to create a debug OpenGL context, which may have additional error and performance issue reporting functionality. If OpenGL ES is requested, this hint is ignored. + OpenGLProfile Hint = C.GLFW_OPENGL_PROFILE // Specifies which OpenGL profile to create the context for. Hard constraint. + ContextCreationAPI Hint = C.GLFW_CONTEXT_CREATION_API // Specifies which context creation API to use to create the context. +) + +// Framebuffer related hints. +const ( + ContextRevision Hint = C.GLFW_CONTEXT_REVISION + RedBits Hint = C.GLFW_RED_BITS // Specifies the desired bit depth of the default framebuffer. + GreenBits Hint = C.GLFW_GREEN_BITS // Specifies the desired bit depth of the default framebuffer. + BlueBits Hint = C.GLFW_BLUE_BITS // Specifies the desired bit depth of the default framebuffer. + AlphaBits Hint = C.GLFW_ALPHA_BITS // Specifies the desired bit depth of the default framebuffer. + DepthBits Hint = C.GLFW_DEPTH_BITS // Specifies the desired bit depth of the default framebuffer. + StencilBits Hint = C.GLFW_STENCIL_BITS // Specifies the desired bit depth of the default framebuffer. + AccumRedBits Hint = C.GLFW_ACCUM_RED_BITS // Specifies the desired bit depth of the accumulation buffer. + AccumGreenBits Hint = C.GLFW_ACCUM_GREEN_BITS // Specifies the desired bit depth of the accumulation buffer. + AccumBlueBits Hint = C.GLFW_ACCUM_BLUE_BITS // Specifies the desired bit depth of the accumulation buffer. + AccumAlphaBits Hint = C.GLFW_ACCUM_ALPHA_BITS // Specifies the desired bit depth of the accumulation buffer. + AuxBuffers Hint = C.GLFW_AUX_BUFFERS // Specifies the desired number of auxiliary buffers. + Stereo Hint = C.GLFW_STEREO // Specifies whether to use stereoscopic rendering. Hard constraint. + Samples Hint = C.GLFW_SAMPLES // Specifies the desired number of samples to use for multisampling. Zero disables multisampling. + SRGBCapable Hint = C.GLFW_SRGB_CAPABLE // Specifies whether the framebuffer should be sRGB capable. + RefreshRate Hint = C.GLFW_REFRESH_RATE // Specifies the desired refresh rate for full screen windows. If set to zero, the highest available refresh rate will be used. This hint is ignored for windowed mode windows. + DoubleBuffer Hint = C.GLFW_DOUBLEBUFFER // Specifies whether the framebuffer should be double buffered. You nearly always want to use double buffering. This is a hard constraint. + CocoaGraphicsSwitching Hint = C.GLFW_COCOA_GRAPHICS_SWITCHING // Specifies whether to in Automatic Graphics Switching, i.e. to allow the system to choose the integrated GPU for the OpenGL context and move it between GPUs if necessary or whether to force it to always run on the discrete GPU. + CocoaRetinaFramebuffer Hint = C.GLFW_COCOA_RETINA_FRAMEBUFFER // Specifies whether to use full resolution framebuffers on Retina displays. +) + +// Naming related hints. (Use with glfw.WindowHintString) +const ( + CocoaFrameNAME Hint = C.GLFW_COCOA_FRAME_NAME // Specifies the UTF-8 encoded name to use for autosaving the window frame, or if empty disables frame autosaving for the window. + X11ClassName Hint = C.GLFW_X11_CLASS_NAME // Specifies the desired ASCII encoded class parts of the ICCCM WM_CLASS window property.nd instance parts of the ICCCM WM_CLASS window property. + X11InstanceName Hint = C.GLFW_X11_INSTANCE_NAME // Specifies the desired ASCII encoded instance parts of the ICCCM WM_CLASS window property.nd instance parts of the ICCCM WM_CLASS window property. +) + +// Values for the ClientAPI hint. +const ( + OpenGLAPI int = C.GLFW_OPENGL_API + OpenGLESAPI int = C.GLFW_OPENGL_ES_API + NoAPI int = C.GLFW_NO_API +) + +// Values for ContextCreationAPI hint. +const ( + NativeContextAPI int = C.GLFW_NATIVE_CONTEXT_API + EGLContextAPI int = C.GLFW_EGL_CONTEXT_API + OSMesaContextAPI int = C.GLFW_OSMESA_CONTEXT_API +) + +// Values for the ContextRobustness hint. +const ( + NoRobustness int = C.GLFW_NO_ROBUSTNESS + NoResetNotification int = C.GLFW_NO_RESET_NOTIFICATION + LoseContextOnReset int = C.GLFW_LOSE_CONTEXT_ON_RESET +) + +// Values for ContextReleaseBehavior hint. +const ( + AnyReleaseBehavior int = C.GLFW_ANY_RELEASE_BEHAVIOR + ReleaseBehaviorFlush int = C.GLFW_RELEASE_BEHAVIOR_FLUSH + ReleaseBehaviorNone int = C.GLFW_RELEASE_BEHAVIOR_NONE +) + +// Values for the OpenGLProfile hint. +const ( + OpenGLAnyProfile int = C.GLFW_OPENGL_ANY_PROFILE + OpenGLCoreProfile int = C.GLFW_OPENGL_CORE_PROFILE + OpenGLCompatProfile int = C.GLFW_OPENGL_COMPAT_PROFILE +) + +// Other values. +const ( + True int = 1 // GL_TRUE + False int = 0 // GL_FALSE + DontCare int = C.GLFW_DONT_CARE +) + +// Window represents a window. +type Window struct { + data *C.GLFWwindow + + // Window. + fPosHolder func(w *Window, xpos int, ypos int) + fSizeHolder func(w *Window, width int, height int) + fFramebufferSizeHolder func(w *Window, width int, height int) + fCloseHolder func(w *Window) + fMaximizeHolder func(w *Window, maximized bool) + fContentScaleHolder func(w *Window, x float32, y float32) + fRefreshHolder func(w *Window) + fFocusHolder func(w *Window, focused bool) + fIconifyHolder func(w *Window, iconified bool) + + // Input. + fMouseButtonHolder func(w *Window, button MouseButton, action Action, mod ModifierKey) + fCursorPosHolder func(w *Window, xpos float64, ypos float64) + fCursorEnterHolder func(w *Window, entered bool) + fScrollHolder func(w *Window, xoff float64, yoff float64) + fKeyHolder func(w *Window, key Key, scancode int, action Action, mods ModifierKey) + fCharHolder func(w *Window, char rune) + fCharModsHolder func(w *Window, char rune, mods ModifierKey) + fDropHolder func(w *Window, names []string) +} + +// Handle returns a *C.GLFWwindow reference (i.e. the GLFW window itself). +// This can be used for passing the GLFW window handle to external libraries +// like vulkan-go. +func (w *Window) Handle() unsafe.Pointer { + return unsafe.Pointer(w.data) +} + +// GoWindow creates a Window from a *C.GLFWwindow reference. +// Used when an external C library is calling your Go handlers. +func GoWindow(window unsafe.Pointer) *Window { + return &Window{data: (*C.GLFWwindow)(window)} +} + +//export goWindowPosCB +func goWindowPosCB(window unsafe.Pointer, xpos, ypos C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fPosHolder(w, int(xpos), int(ypos)) +} + +//export goWindowSizeCB +func goWindowSizeCB(window unsafe.Pointer, width, height C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fSizeHolder(w, int(width), int(height)) +} + +//export goFramebufferSizeCB +func goFramebufferSizeCB(window unsafe.Pointer, width, height C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fFramebufferSizeHolder(w, int(width), int(height)) +} + +//export goWindowCloseCB +func goWindowCloseCB(window unsafe.Pointer) { + w := windows.get((*C.GLFWwindow)(window)) + w.fCloseHolder(w) +} + +//export goWindowMaximizeCB +func goWindowMaximizeCB(window unsafe.Pointer, maximized C.int) { + w := windows.get((*C.GLFWwindow)(window)) + w.fMaximizeHolder(w, glfwbool(maximized)) +} + +//export goWindowRefreshCB +func goWindowRefreshCB(window unsafe.Pointer) { + w := windows.get((*C.GLFWwindow)(window)) + w.fRefreshHolder(w) +} + +//export goWindowFocusCB +func goWindowFocusCB(window unsafe.Pointer, focused C.int) { + w := windows.get((*C.GLFWwindow)(window)) + isFocused := glfwbool(focused) + w.fFocusHolder(w, isFocused) +} + +//export goWindowIconifyCB +func goWindowIconifyCB(window unsafe.Pointer, iconified C.int) { + isIconified := glfwbool(iconified) + w := windows.get((*C.GLFWwindow)(window)) + w.fIconifyHolder(w, isIconified) +} + +//export goWindowContentScaleCB +func goWindowContentScaleCB(window unsafe.Pointer, x C.float, y C.float) { + w := windows.get((*C.GLFWwindow)(window)) + w.fContentScaleHolder(w, float32(x), float32(y)) +} + +// DefaultWindowHints resets all window hints to their default values. +// +// This function may only be called from the main thread. +func DefaultWindowHints() { + C.glfwDefaultWindowHints() + panicError() +} + +// WindowHint sets hints for the next call to CreateWindow. The hints, +// once set, retain their values until changed by a call to WindowHint or +// DefaultWindowHints, or until the library is terminated with Terminate. +// +// This function may only be called from the main thread. +func WindowHint(target Hint, hint int) { + C.glfwWindowHint(C.int(target), C.int(hint)) + panicError() +} + +// WindowHintString sets hints for the next call to CreateWindow. The hints, +// once set, retain their values until changed by a call to this function or +// DefaultWindowHints, or until the library is terminated. +// +// Only string type hints can be set with this function. Integer value hints are +// set with WindowHint. +// +// This function does not check whether the specified hint values are valid. If +// you set hints to invalid values this will instead be reported by the next +// call to CreateWindow. +// +// Some hints are platform specific. These may be set on any platform but they +// will only affect their specific platform. Other platforms will ignore them. +// Setting these hints requires no platform specific headers or functions. +// +// This function must only be called from the main thread. +func WindowHintString(hint Hint, value string) { + str := C.CString(value) + defer C.free(unsafe.Pointer(str)) + C.glfwWindowHintString(C.int(hint), str) +} + +// CreateWindow creates a window and its associated context. Most of the options +// controlling how the window and its context should be created are specified +// through Hint. +// +// Successful creation does not change which context is current. Before you can +// use the newly created context, you need to make it current using +// MakeContextCurrent. +// +// Note that the created window and context may differ from what you requested, +// as not all parameters and hints are hard constraints. This includes the size +// of the window, especially for full screen windows. To retrieve the actual +// attributes of the created window and context, use queries like +// Window.GetAttrib and Window.GetSize. +// +// To create the window at a specific position, make it initially invisible using +// the Visible window hint, set its position and then show it. +// +// If a fullscreen window is active, the screensaver is prohibited from starting. +// +// Windows: If the executable has an icon resource named GLFW_ICON, it will be +// set as the icon for the window. If no such icon is present, the IDI_WINLOGO +// icon will be used instead. +// +// Mac OS X: The GLFW window has no icon, as it is not a document window, but the +// dock icon will be the same as the application bundle's icon. Also, the first +// time a window is opened the menu bar is populated with common commands like +// Hide, Quit and About. The (minimal) about dialog uses information from the +// application's bundle. For more information on bundles, see the Bundle +// Programming Guide provided by Apple. +// +// This function may only be called from the main thread. +func CreateWindow(width, height int, title string, monitor *Monitor, share *Window) (*Window, error) { + var ( + m *C.GLFWmonitor + s *C.GLFWwindow + ) + + t := C.CString(title) + defer C.free(unsafe.Pointer(t)) + + if monitor != nil { + m = monitor.data + } + + if share != nil { + s = share.data + } + + w := C.glfwCreateWindow(C.int(width), C.int(height), t, m, s) + if w == nil { + return nil, acceptError(APIUnavailable, VersionUnavailable) + } + + wnd := &Window{data: w} + windows.put(wnd) + return wnd, nil +} + +// Destroy destroys the specified window and its context. On calling this +// function, no further callbacks will be called for that window. +// +// This function may only be called from the main thread. +func (w *Window) Destroy() { + windows.remove(w.data) + C.glfwDestroyWindow(w.data) + panicError() +} + +// ShouldClose reports the value of the close flag of the specified window. +func (w *Window) ShouldClose() bool { + ret := glfwbool(C.glfwWindowShouldClose(w.data)) + panicError() + return ret +} + +// SetShouldClose sets the value of the close flag of the window. This can be +// used to override the user's attempt to close the window, or to signal that it +// should be closed. +func (w *Window) SetShouldClose(value bool) { + if !value { + C.glfwSetWindowShouldClose(w.data, C.int(False)) + } else { + C.glfwSetWindowShouldClose(w.data, C.int(True)) + } + panicError() +} + +// SetTitle sets the window title, encoded as UTF-8, of the window. +// +// This function may only be called from the main thread. +func (w *Window) SetTitle(title string) { + t := C.CString(title) + defer C.free(unsafe.Pointer(t)) + C.glfwSetWindowTitle(w.data, t) + panicError() +} + +// SetIcon sets the icon of the specified window. If passed an array of candidate images, +// those of or closest to the sizes desired by the system are selected. If no images are +// specified, the window reverts to its default icon. +// +// The image is ideally provided in the form of *image.NRGBA. +// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight +// bits per channel with the red channel first. They are arranged canonically +// as packed sequential rows, starting from the top-left corner. If the image +// type is not *image.NRGBA, it will be converted to it. +// +// The desired image sizes varies depending on platform and system settings. The selected +// images will be rescaled as needed. Good sizes include 16x16, 32x32 and 48x48. +func (w *Window) SetIcon(images []image.Image) { + count := len(images) + cimages := make([]C.GLFWimage, count) + freePixels := make([]func(), count) + + for i, img := range images { + cimages[i], freePixels[i] = imageToGLFW(img) + } + + var p *C.GLFWimage + if count > 0 { + p = &cimages[0] + } + C.glfwSetWindowIcon(w.data, C.int(count), p) + + for _, v := range freePixels { + v() + } + + panicError() +} + +// GetPos returns the position, in screen coordinates, of the upper-left +// corner of the client area of the window. +func (w *Window) GetPos() (x, y int) { + var xpos, ypos C.int + C.glfwGetWindowPos(w.data, &xpos, &ypos) + panicError() + return int(xpos), int(ypos) +} + +// SetPos sets the position, in screen coordinates, of the upper-left corner +// of the client area of the window. +// +// If it is a full screen window, this function does nothing. +// +// If you wish to set an initial window position you should create a hidden +// window (using Hint and Visible), set its position and then show it. +// +// It is very rarely a good idea to move an already visible window, as it will +// confuse and annoy the user. +// +// The window manager may put limits on what positions are allowed. +// +// This function may only be called from the main thread. +func (w *Window) SetPos(xpos, ypos int) { + C.glfwSetWindowPos(w.data, C.int(xpos), C.int(ypos)) + panicError() +} + +// GetSize returns the size, in screen coordinates, of the client area of the +// specified window. +func (w *Window) GetSize() (width, height int) { + var wi, h C.int + C.glfwGetWindowSize(w.data, &wi, &h) + panicError() + return int(wi), int(h) +} + +// SetSize sets the size, in screen coordinates, of the client area of the +// window. +// +// For full screen windows, this function selects and switches to the resolution +// closest to the specified size, without affecting the window's context. As the +// context is unaffected, the bit depths of the framebuffer remain unchanged. +// +// The window manager may put limits on what window sizes are allowed. +// +// This function may only be called from the main thread. +func (w *Window) SetSize(width, height int) { + C.glfwSetWindowSize(w.data, C.int(width), C.int(height)) + panicError() +} + +// SetSizeLimits sets the size limits of the client area of the specified window. +// If the window is full screen or not resizable, this function does nothing. +// +// The size limits are applied immediately and may cause the window to be resized. +func (w *Window) SetSizeLimits(minw, minh, maxw, maxh int) { + C.glfwSetWindowSizeLimits(w.data, C.int(minw), C.int(minh), C.int(maxw), C.int(maxh)) + panicError() +} + +// SetAspectRatio sets the required aspect ratio of the client area of the specified window. +// If the window is full screen or not resizable, this function does nothing. +// +// The aspect ratio is specified as a numerator and a denominator and both values must be greater +// than zero. For example, the common 16:9 aspect ratio is specified as 16 and 9, respectively. +// +// If the numerator and denominator is set to glfw.DontCare then the aspect ratio limit is disabled. +// +// The aspect ratio is applied immediately and may cause the window to be resized. +func (w *Window) SetAspectRatio(numer, denom int) { + C.glfwSetWindowAspectRatio(w.data, C.int(numer), C.int(denom)) + panicError() +} + +// GetFramebufferSize retrieves the size, in pixels, of the framebuffer of the +// specified window. +func (w *Window) GetFramebufferSize() (width, height int) { + var wi, h C.int + C.glfwGetFramebufferSize(w.data, &wi, &h) + panicError() + return int(wi), int(h) +} + +// GetFrameSize retrieves the size, in screen coordinates, of each edge of the frame +// of the specified window. This size includes the title bar, if the window has one. +// The size of the frame may vary depending on the window-related hints used to create it. +// +// Because this function retrieves the size of each window frame edge and not the offset +// along a particular coordinate axis, the retrieved values will always be zero or positive. +func (w *Window) GetFrameSize() (left, top, right, bottom int) { + var l, t, r, b C.int + C.glfwGetWindowFrameSize(w.data, &l, &t, &r, &b) + panicError() + return int(l), int(t), int(r), int(b) +} + +// GetContentScale function retrieves the content scale for the specified +// window. The content scale is the ratio between the current DPI and the +// platform's default DPI. If you scale all pixel dimensions by this scale then +// your content should appear at an appropriate size. This is especially +// important for text and any UI elements. +// +// This function may only be called from the main thread. +func (w *Window) GetContentScale() (float32, float32) { + var x, y C.float + C.glfwGetWindowContentScale(w.data, &x, &y) + return float32(x), float32(y) +} + +// GetOpacity function returns the opacity of the window, including any +// decorations. +// +// The opacity (or alpha) value is a positive finite number between zero and +// one, where zero is fully transparent and one is fully opaque. If the system +// does not support whole window transparency, this function always returns one. +// +// The initial opacity value for newly created windows is one. +// +// This function may only be called from the main thread. +func (w *Window) GetOpacity() float32 { + return float32(C.glfwGetWindowOpacity(w.data)) +} + +// SetOpacity function sets the opacity of the window, including any +// decorations. The opacity (or alpha) value is a positive finite number between +// zero and one, where zero is fully transparent and one is fully opaque. +// +// The initial opacity value for newly created windows is one. +// +// A window created with framebuffer transparency may not use whole window +// transparency. The results of doing this are undefined. +// +// This function may only be called from the main thread. +func (w *Window) SetOpacity(opacity float32) { + C.glfwSetWindowOpacity(w.data, C.float(opacity)) +} + +// RequestWindowAttention funciton requests user attention to the specified +// window. On platforms where this is not supported, attention is requested to +// the application as a whole. +// +// Once the user has given attention, usually by focusing the window or +// application, the system will end the request automatically. +// +// This function must only be called from the main thread. +func (w *Window) RequestAttention() { + C.glfwRequestWindowAttention(w.data) +} + +// Focus brings the specified window to front and sets input focus. +// The window should already be visible and not iconified. +// +// By default, both windowed and full screen mode windows are focused when initially created. +// Set the glfw.Focused to disable this behavior. +// +// Do not use this function to steal focus from other applications unless you are certain that +// is what the user wants. Focus stealing can be extremely disruptive. +func (w *Window) Focus() { + C.glfwFocusWindow(w.data) +} + +// Iconify iconifies/minimizes the window, if it was previously restored. If it +// is a full screen window, the original monitor resolution is restored until the +// window is restored. If the window is already iconified, this function does +// nothing. +// +// This function may only be called from the main thread. +func (w *Window) Iconify() { + C.glfwIconifyWindow(w.data) +} + +// Maximize maximizes the specified window if it was previously not maximized. +// If the window is already maximized, this function does nothing. +// +// If the specified window is a full screen window, this function does nothing. +func (w *Window) Maximize() { + C.glfwMaximizeWindow(w.data) +} + +// Restore restores the window, if it was previously iconified/minimized. If it +// is a full screen window, the resolution chosen for the window is restored on +// the selected monitor. If the window is already restored, this function does +// nothing. +// +// This function may only be called from the main thread. +func (w *Window) Restore() { + C.glfwRestoreWindow(w.data) +} + +// Show makes the window visible, if it was previously hidden. If the window is +// already visible or is in full screen mode, this function does nothing. +// +// This function may only be called from the main thread. +func (w *Window) Show() { + C.glfwShowWindow(w.data) + panicError() +} + +// Hide hides the window, if it was previously visible. If the window is already +// hidden or is in full screen mode, this function does nothing. +// +// This function may only be called from the main thread. +func (w *Window) Hide() { + C.glfwHideWindow(w.data) + panicError() +} + +// GetMonitor returns the handle of the monitor that the window is in +// fullscreen on. +// +// Returns nil if the window is in windowed mode. +func (w *Window) GetMonitor() *Monitor { + m := C.glfwGetWindowMonitor(w.data) + panicError() + if m == nil { + return nil + } + return &Monitor{m} +} + +// SetMonitor sets the monitor that the window uses for full screen mode or, +// if the monitor is NULL, makes it windowed mode. +// +// When setting a monitor, this function updates the width, height and refresh +// rate of the desired video mode and switches to the video mode closest to it. +// The window position is ignored when setting a monitor. +// +// When the monitor is NULL, the position, width and height are used to place +// the window client area. The refresh rate is ignored when no monitor is specified. +// If you only wish to update the resolution of a full screen window or the size of +// a windowed mode window, see window.SetSize. +// +// When a window transitions from full screen to windowed mode, this function +// restores any previous window settings such as whether it is decorated, floating, +// resizable, has size or aspect ratio limits, etc.. +func (w *Window) SetMonitor(monitor *Monitor, xpos, ypos, width, height, refreshRate int) { + var m *C.GLFWmonitor + if monitor == nil { + m = nil + } else { + m = monitor.data + } + C.glfwSetWindowMonitor(w.data, m, C.int(xpos), C.int(ypos), C.int(width), C.int(height), C.int(refreshRate)) + panicError() +} + +// GetAttrib returns an attribute of the window. There are many attributes, +// some related to the window and others to its context. +func (w *Window) GetAttrib(attrib Hint) int { + ret := int(C.glfwGetWindowAttrib(w.data, C.int(attrib))) + panicError() + return ret +} + +// SetAttrib function sets the value of an attribute of the specified window. +// +// The supported attributes are Decorated, Resizeable, Floating and AutoIconify. +// +// Some of these attributes are ignored for full screen windows. The new value +// will take effect if the window is later made windowed. +// +// Some of these attributes are ignored for windowed mode windows. The new value +// will take effect if the window is later made full screen. +// +// This function may only be called from the main thread. +func (w *Window) SetAttrib(attrib Hint, value int) { + C.glfwSetWindowAttrib(w.data, C.int(attrib), C.int(value)) +} + +// SetUserPointer sets the user-defined pointer of the window. The current value +// is retained until the window is destroyed. The initial value is nil. +func (w *Window) SetUserPointer(pointer unsafe.Pointer) { + C.glfwSetWindowUserPointer(w.data, pointer) + panicError() +} + +// GetUserPointer returns the current value of the user-defined pointer of the +// window. The initial value is nil. +func (w *Window) GetUserPointer() unsafe.Pointer { + ret := C.glfwGetWindowUserPointer(w.data) + panicError() + return ret +} + +// PosCallback is the window position callback. +type PosCallback func(w *Window, xpos int, ypos int) + +// SetPosCallback sets the position callback of the window, which is called +// when the window is moved. The callback is provided with the screen position +// of the upper-left corner of the client area of the window. +func (w *Window) SetPosCallback(cbfun PosCallback) (previous PosCallback) { + previous = w.fPosHolder + w.fPosHolder = cbfun + if cbfun == nil { + C.glfwSetWindowPosCallback(w.data, nil) + } else { + C.glfwSetWindowPosCallbackCB(w.data) + } + panicError() + return previous +} + +// SizeCallback is the window size callback. +type SizeCallback func(w *Window, width int, height int) + +// SetSizeCallback sets the size callback of the window, which is called when +// the window is resized. The callback is provided with the size, in screen +// coordinates, of the client area of the window. +func (w *Window) SetSizeCallback(cbfun SizeCallback) (previous SizeCallback) { + previous = w.fSizeHolder + w.fSizeHolder = cbfun + if cbfun == nil { + C.glfwSetWindowSizeCallback(w.data, nil) + } else { + C.glfwSetWindowSizeCallbackCB(w.data) + } + panicError() + return previous +} + +// FramebufferSizeCallback is the framebuffer size callback. +type FramebufferSizeCallback func(w *Window, width int, height int) + +// SetFramebufferSizeCallback sets the framebuffer resize callback of the specified +// window, which is called when the framebuffer of the specified window is resized. +func (w *Window) SetFramebufferSizeCallback(cbfun FramebufferSizeCallback) (previous FramebufferSizeCallback) { + previous = w.fFramebufferSizeHolder + w.fFramebufferSizeHolder = cbfun + if cbfun == nil { + C.glfwSetFramebufferSizeCallback(w.data, nil) + } else { + C.glfwSetFramebufferSizeCallbackCB(w.data) + } + panicError() + return previous +} + +// CloseCallback is the window close callback. +type CloseCallback func(w *Window) + +// SetCloseCallback sets the close callback of the window, which is called when +// the user attempts to close the window, for example by clicking the close +// widget in the title bar. +// +// The close flag is set before this callback is called, but you can modify it at +// any time with SetShouldClose. +// +// Mac OS X: Selecting Quit from the application menu will trigger the close +// callback for all windows. +func (w *Window) SetCloseCallback(cbfun CloseCallback) (previous CloseCallback) { + previous = w.fCloseHolder + w.fCloseHolder = cbfun + if cbfun == nil { + C.glfwSetWindowCloseCallback(w.data, nil) + } else { + C.glfwSetWindowCloseCallbackCB(w.data) + } + panicError() + return previous +} + +// MaximizeCallback is the function signature for window maximize callback +// functions. +type MaximizeCallback func(w *Window, maximized bool) + +// SetMaximizeCallback sets the maximization callback of the specified window, +// which is called when the window is maximized or restored. +// +// This function must only be called from the main thread. +func (w *Window) SetMaximizeCallback(cbfun MaximizeCallback) MaximizeCallback { + previous := w.fMaximizeHolder + w.fMaximizeHolder = cbfun + if cbfun == nil { + C.glfwSetWindowMaximizeCallback(w.data, nil) + } else { + C.glfwSetWindowMaximizeCallbackCB(w.data) + } + return previous +} + +// ContentScaleCallback is the function signature for window content scale +// callback functions. +type ContentScaleCallback func(w *Window, x float32, y float32) + +// SetContentScaleCallback function sets the window content scale callback of +// the specified window, which is called when the content scale of the specified +// window changes. +// +// This function must only be called from the main thread. +func (w *Window) SetContentScaleCallback(cbfun ContentScaleCallback) ContentScaleCallback { + previous := w.fContentScaleHolder + w.fContentScaleHolder = cbfun + if cbfun == nil { + C.glfwSetWindowContentScaleCallback(w.data, nil) + } else { + C.glfwSetWindowContentScaleCallbackCB(w.data) + } + return previous +} + +// RefreshCallback is the window refresh callback. +type RefreshCallback func(w *Window) + +// SetRefreshCallback sets the refresh callback of the window, which +// is called when the client area of the window needs to be redrawn, for example +// if the window has been exposed after having been covered by another window. +// +// On compositing window systems such as Aero, Compiz or Aqua, where the window +// contents are saved off-screen, this callback may be called only very +// infrequently or never at all. +func (w *Window) SetRefreshCallback(cbfun RefreshCallback) (previous RefreshCallback) { + previous = w.fRefreshHolder + w.fRefreshHolder = cbfun + if cbfun == nil { + C.glfwSetWindowRefreshCallback(w.data, nil) + } else { + C.glfwSetWindowRefreshCallbackCB(w.data) + } + panicError() + return previous +} + +// FocusCallback is the window focus callback. +type FocusCallback func(w *Window, focused bool) + +// SetFocusCallback sets the focus callback of the window, which is called when +// the window gains or loses focus. +// +// After the focus callback is called for a window that lost focus, synthetic key +// and mouse button release events will be generated for all such that had been +// pressed. For more information, see SetKeyCallback and SetMouseButtonCallback. +func (w *Window) SetFocusCallback(cbfun FocusCallback) (previous FocusCallback) { + previous = w.fFocusHolder + w.fFocusHolder = cbfun + if cbfun == nil { + C.glfwSetWindowFocusCallback(w.data, nil) + } else { + C.glfwSetWindowFocusCallbackCB(w.data) + } + panicError() + return previous +} + +// IconifyCallback is the window iconification callback. +type IconifyCallback func(w *Window, iconified bool) + +// SetIconifyCallback sets the iconification callback of the window, which is +// called when the window is iconified or restored. +func (w *Window) SetIconifyCallback(cbfun IconifyCallback) (previous IconifyCallback) { + previous = w.fIconifyHolder + w.fIconifyHolder = cbfun + if cbfun == nil { + C.glfwSetWindowIconifyCallback(w.data, nil) + } else { + C.glfwSetWindowIconifyCallbackCB(w.data) + } + panicError() + return previous +} + +// SetClipboardString sets the system clipboard to the specified UTF-8 encoded +// string. +// +// Ownership to the Window is no longer necessary, see +// glfw.SetClipboardString(string) +// +// This function may only be called from the main thread. +func (w *Window) SetClipboardString(str string) { + cp := C.CString(str) + defer C.free(unsafe.Pointer(cp)) + C.glfwSetClipboardString(w.data, cp) + panicError() +} + +// GetClipboardString returns the contents of the system clipboard, if it +// contains or is convertible to a UTF-8 encoded string. +// +// Ownership to the Window is no longer necessary, see +// glfw.GetClipboardString() +// +// This function may only be called from the main thread. +func (w *Window) GetClipboardString() string { + cs := C.glfwGetClipboardString(w.data) + if cs == nil { + acceptError(FormatUnavailable) + return "" + } + return C.GoString(cs) +} + +// PollEvents processes only those events that have already been received and +// then returns immediately. Processing events will cause the window and input +// callbacks associated with those events to be called. +// +// This function is not required for joystick input to work. +// +// This function may not be called from a callback. +// +// This function may only be called from the main thread. +func PollEvents() { + C.glfwPollEvents() + panicError() +} + +// WaitEvents puts the calling thread to sleep until at least one event has been +// received. Once one or more events have been recevied, it behaves as if +// PollEvents was called, i.e. the events are processed and the function then +// returns immediately. Processing events will cause the window and input +// callbacks associated with those events to be called. +// +// Since not all events are associated with callbacks, this function may return +// without a callback having been called even if you are monitoring all +// callbacks. +// +// This function may not be called from a callback. +// +// This function may only be called from the main thread. +func WaitEvents() { + C.glfwWaitEvents() + panicError() +} + +// WaitEventsTimeout puts the calling thread to sleep until at least one event is available in the +// event queue, or until the specified timeout is reached. If one or more events are available, +// it behaves exactly like PollEvents, i.e. the events in the queue are processed and the function +// then returns immediately. Processing events will cause the window and input callbacks associated +// with those events to be called. +// +// The timeout value must be a positive finite number. +// +// Since not all events are associated with callbacks, this function may return without a callback +// having been called even if you are monitoring all callbacks. +// +// On some platforms, a window move, resize or menu operation will cause event processing to block. +// This is due to how event processing is designed on those platforms. You can use the window +// refresh callback to redraw the contents of your window when necessary during such operations. +// +// On some platforms, certain callbacks may be called outside of a call to one of the event +// processing functions. +// +// If no windows exist, this function returns immediately. For synchronization of threads in +// applications that do not create windows, use native Go primitives. +// +// Event processing is not required for joystick input to work. +func WaitEventsTimeout(timeout float64) { + C.glfwWaitEventsTimeout(C.double(timeout)) + panicError() +} + +// PostEmptyEvent posts an empty event from the current thread to the main +// thread event queue, causing WaitEvents to return. +// +// If no windows exist, this function returns immediately. For synchronization of threads in +// applications that do not create windows, use native Go primitives. +// +// This function may be called from secondary threads. +func PostEmptyEvent() { + C.glfwPostEmptyEvent() + panicError() +}