native: switch to setWaitEvent()

This commit is contained in:
David Vanderson 2022-06-08 16:19:26 -04:00 committed by Stephen Gutekanst
parent 15c71f5135
commit 9354c178eb
2 changed files with 46 additions and 0 deletions

View file

@ -53,10 +53,28 @@ pub fn setOptions(engine: *Engine, options: structs.Options) !void {
engine.options = options;
}
// Signals mach to stop the update loop.
pub fn setShouldClose(engine: *Engine, value: bool) void {
engine.internal.setShouldClose(value);
}
// Signals mach to wait for an event with timeout before calling update()
// again. Mach resets to null, so call during each update() if needed.
//
// timeout is in seconds (null disables waiting)
// - pass std.math.floatMax(f64) to wait with no timeout
//
// update() can be called earlier than timeout if an event happens (key press,
// mouse motion, etc.)
//
// update() can be called a bit later than timeout due to timer precision and
// process scheduling.
//
// Calling this multiple times means the last call's value is used.
pub fn setWaitEvent(engine: *Engine, timeout: ?f64) void {
engine.internal.setWaitEvent(timeout);
}
// Returns the framebuffer size, in subpixel units.
//
// e.g. returns 1280x960 on macOS for a window that is 640x480
@ -71,6 +89,10 @@ pub fn getWindowSize(engine: *Engine) structs.Size {
return engine.internal.getWindowSize();
}
pub fn hasEvent(engine: *Engine) !bool {
return engine.internal.hasEvent();
}
pub fn pollEvent(engine: *Engine) ?structs.Event {
return engine.internal.pollEvent();
}

View file

@ -17,6 +17,7 @@ pub const Platform = struct {
last_window_size: structs.Size,
last_framebuffer_size: structs.Size,
waitEventTimeout: ?f64 = null,
native_instance: gpu.NativeInstance,
@ -305,6 +306,15 @@ pub const Platform = struct {
return platform.last_window_size;
}
pub fn hasEvent(platform: *Platform) !bool {
try glfw.pollEvents();
return platform.events.first != null;
}
pub fn setWaitEvent(platform: *Platform, timeout: ?f64) void {
platform.waitEventTimeout = timeout;
}
pub fn pollEvent(platform: *Platform) ?structs.Event {
if (platform.events.popFirst()) |n| {
defer platform.allocator.destroy(n);
@ -512,5 +522,19 @@ pub fn main() !void {
}
try app.update(&engine);
if (engine.internal.waitEventTimeout) |timeout| {
// wait for an event
if (timeout == std.math.floatMax(f64)) {
// no timeout
try glfw.waitEvents();
}
else {
// with a timeout
try glfw.waitEventsTimeout(timeout);
}
engine.internal.waitEventTimeout = null;
}
}
}