Something went wrong. Try again.
A puzzle game of bent arrows sent off a board of dots, written in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! pfeilstorch on Android: a `NativeActivity`, drawn with Vulkan.//!//! The activity's callbacks arrive on the main thread, and the game runs on//! a thread of its own with a looper, as `android_native_app_glue` would//! arrange in C (see ADR 0003). Each callback hands the game's thread a//! message and waits until it has been acted on, so that a window or an//! input queue is never used after the callback saying it is gone has//! returned. What has to be asked of Java — the accent color, the insets,//! hiding the system bars — is asked on the main thread, where the//! activity's `JNIEnv` belongs.//!//! A frame is drawn only when something has changed, and at the display's//! pace while anything moves: the game asks the choreographer for a frame//! and draws when it comes.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const vk = @import("vk");const view = @import("view");
const ndk = @import("ndk.zig");const system = @import("system.zig");const Device = @import("../vulkan/Device.zig");const Renderer = @import("../vulkan/Renderer.zig");const Swapchain = @import("../vulkan/Swapchain.zig");const progress = @import("../progress.zig");
const log = std.log.scoped(.pfeilstorch);
/// What every Android device's swapchains can show.const format: vk.Format = .r8g8b8a8_unorm;
/// The looper's identifier for the input queue.const input_ident = 1;
/// What the main thread tells the game's thread.const Message = union(enum) { /// The window to draw in, or none, once it has gone. window: ?*ndk.ANativeWindow, /// The queue to read input from, or none. input: ?*ndk.AInputQueue, insets: system.Insets, accent: ?view.draw.Color, redraw, quit,};
const App = struct { gpa: Allocator, threaded: Io.Threaded, activity: *ndk.ANativeActivity, thread: std.Thread = undefined, mutex: Io.Mutex = .init, changed: Io.Condition = .init, /// Set by the game's thread once it can be woken. looper: ?*ndk.ALooper = null, inbox: std.ArrayList(Message) = .empty, sent: u64 = 0, done: u64 = 0,
fn io(app: *App) Io { return app.threaded.io(); }
/// Hands `message` to the game's thread, and waits until it has been /// acted on. fn send(app: *App, message: Message) void { const io_ = app.io(); app.mutex.lockUncancelable(io_); defer app.mutex.unlock(io_); app.inbox.append(app.gpa, message) catch { log.err("out of memory telling the game {t}", .{message}); return; }; app.sent += 1; const mine = app.sent; ndk.ALooper_wake(app.looper.?); while (app.done < mine) app.changed.waitUncancelable(io_, &app.mutex); }
fn sendInsets(app: *App) void { if (system.insets(app.activity)) |i| app.send(.{ .insets = i }); }};
fn appOf(activity: *ndk.ANativeActivity) *App { return @ptrCast(@alignCast(activity.instance.?));}
/// Called by `NativeActivity` once the library is loaded, on the main/// thread.pub fn onCreate(activity: *ndk.ANativeActivity) void { const gpa = std.heap.c_allocator; const a = gpa.create(App) catch { log.err("out of memory starting", .{}); ndk.ANativeActivity_finish(activity); return; }; a.* = .{ .gpa = gpa, .threaded = .init(gpa, .{}), .activity = activity }; activity.instance = a;
a.thread = std.Thread.spawn(.{}, run, .{a}) catch |err| { log.err("could not start the game: {t}", .{err}); gpa.destroy(a); activity.instance = null; ndk.ANativeActivity_finish(activity); return; }; const io = a.io(); a.mutex.lockUncancelable(io); while (a.looper == null) a.changed.waitUncancelable(io, &a.mutex); a.mutex.unlock(io);
// Only now, since every one of them talks to the game's thread. activity.callbacks.* = .{ .onDestroy = onDestroy, .onWindowFocusChanged = onWindowFocusChanged, .onNativeWindowCreated = onNativeWindowCreated, .onNativeWindowResized = onNativeWindowResized, .onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded, .onNativeWindowDestroyed = onNativeWindowDestroyed, .onInputQueueCreated = onInputQueueCreated, .onInputQueueDestroyed = onInputQueueDestroyed, .onContentRectChanged = onContentRectChanged, .onConfigurationChanged = onConfigurationChanged, };
system.hideBars(activity); a.send(.{ .accent = system.accent(activity) });}
fn onDestroy(activity: *ndk.ANativeActivity) callconv(.c) void { const a = appOf(activity); a.send(.quit); a.thread.join(); a.inbox.deinit(a.gpa); a.threaded.deinit(); a.gpa.destroy(a); activity.instance = null;}
fn onWindowFocusChanged(activity: *ndk.ANativeActivity, focused: c_int) callconv(.c) void { if (focused == 0) return; // Bars shown by a swipe stay up on Android 10 until they are hidden // again. system.hideBars(activity); appOf(activity).sendInsets();}
fn onNativeWindowCreated(activity: *ndk.ANativeActivity, window: *ndk.ANativeWindow) callconv(.c) void { const a = appOf(activity); a.sendInsets(); a.send(.{ .window = window });}
fn onNativeWindowResized(activity: *ndk.ANativeActivity, _: *ndk.ANativeWindow) callconv(.c) void { const a = appOf(activity); a.sendInsets(); a.send(.redraw);}
fn onNativeWindowRedrawNeeded(activity: *ndk.ANativeActivity, _: *ndk.ANativeWindow) callconv(.c) void { const a = appOf(activity); a.sendInsets(); a.send(.redraw);}
fn onNativeWindowDestroyed(activity: *ndk.ANativeActivity, _: *ndk.ANativeWindow) callconv(.c) void { appOf(activity).send(.{ .window = null });}
fn onInputQueueCreated(activity: *ndk.ANativeActivity, queue: *ndk.AInputQueue) callconv(.c) void { appOf(activity).send(.{ .input = queue });}
fn onInputQueueDestroyed(activity: *ndk.ANativeActivity, _: *ndk.AInputQueue) callconv(.c) void { appOf(activity).send(.{ .input = null });}
fn onContentRectChanged(activity: *ndk.ANativeActivity, _: *const ndk.ARect) callconv(.c) void { appOf(activity).sendInsets();}
fn onConfigurationChanged(activity: *ndk.ANativeActivity) callconv(.c) void { const a = appOf(activity); // A new wallpaper, and with it a new accent, comes as a change of // configuration. a.send(.{ .accent = system.accent(activity) }); a.sendInsets();}
/// The game's thread.fn run(a: *App) void { const io = a.io(); const looper = ndk.ALooper_prepare(ndk.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); a.mutex.lockUncancelable(io); a.looper = looper; a.changed.broadcast(io); a.mutex.unlock(io);
var game: ?Game = Game.init(a.gpa, io, a.activity, looper) catch |err| failed: { log.err("cannot play: {t}", .{err}); ndk.ANativeActivity_finish(a.activity); break :failed null; }; defer if (game) |*g| g.deinit();
var inbox: std.ArrayList(Message) = .empty; defer inbox.deinit(a.gpa); while (true) { const ident = ndk.ALooper_pollOnce(-1, null, null, null); if (ident == input_ident) if (game) |*g| g.readInput();
a.mutex.lockUncancelable(io); std.mem.swap(std.ArrayList(Message), &inbox, &a.inbox); const taken = a.sent; a.mutex.unlock(io);
var quit = false; for (inbox.items) |message| switch (message) { .quit => quit = true, // With no game, nothing reads the input queue and it is left // unattached; the activity is finishing anyway. else => if (game) |*g| g.handle(message), }; inbox.clearRetainingCapacity();
a.mutex.lockUncancelable(io); a.done = taken; a.changed.broadcast(io); a.mutex.unlock(io);
if (quit) break; if (game) |*g| g.frame() catch |err| { log.err("could not draw: {t}", .{err}); ndk.ANativeActivity_finish(a.activity); g.deinit(); game = null; }; }}
const Game = struct { gpa: Allocator, io: Io, activity: *ndk.ANativeActivity, looper: *ndk.ALooper, choreographer: *ndk.AChoreographer, device: *Device, renderer: Renderer, swapchain: ?Swapchain = null, window: ?*ndk.ANativeWindow = null, input: ?*ndk.AInputQueue = null, store: progress.Store, play: view.Play, theme: view.draw.Theme = .{}, insets: system.Insets = .{}, list: view.draw.List = .empty, /// Something has changed since the last frame. dirty: bool = true, /// A frame has been asked of the choreographer and has not yet come. asked: bool = false, /// The display is ready for a frame. due: bool = false,
fn init(gpa: Allocator, io: Io, activity: *ndk.ANativeActivity, looper: *ndk.ALooper) !Game { const choreographer = ndk.AChoreographer_getInstance() orelse return error.NoChoreographer; const device = Device.init(gpa, .{}) catch |err| { log.err("no Vulkan device to draw with: {t}", .{err}); return err; }; errdefer device.deinit(); var renderer = try Renderer.init(device, format); errdefer renderer.deinit(); const store = progress.Store.at(std.mem.span(activity.internal_data_path)); return .{ .gpa = gpa, .io = io, .activity = activity, .looper = looper, .choreographer = choreographer, .device = device, .renderer = renderer, .store = store, .play = try view.Play.init(gpa, store.load(io) orelse 1), }; }
fn deinit(g: *Game) void { if (g.input) |q| ndk.AInputQueue_detachLooper(q); if (g.swapchain) |*s| s.deinit(); g.list.deinit(g.gpa); g.play.deinit(); g.renderer.deinit(); g.device.deinit(); g.* = undefined; }
fn handle(g: *Game, message: Message) void { switch (message) { .window => |window| { if (g.swapchain) |*s| s.deinit(); g.swapchain = null; g.window = window; if (window) |w| g.swapchain = g.makeSwapchain(w) catch |err| none: { log.err("cannot draw in the window: {t}", .{err}); break :none null; }; g.dirty = true; }, .input => |queue| { if (g.input) |q| ndk.AInputQueue_detachLooper(q); g.input = queue; if (queue) |q| ndk.AInputQueue_attachLooper(q, g.looper, input_ident, null, null); }, .insets => |i| { if (!std.meta.eql(i, g.insets)) g.dirty = true; g.insets = i; }, .accent => |color| { g.theme.accent = color orelse view.draw.Theme.default_accent; g.dirty = true; }, .redraw => g.dirty = true, .quit => unreachable, } }
fn makeSwapchain(g: *Game, window: *ndk.ANativeWindow) !Swapchain { const surface = try g.device.instance.createAndroidSurfaceKHR(&.{ .window = window }, null); return Swapchain.init(g.device, surface, format); }
fn readInput(g: *Game) void { const queue = g.input orelse return; var event: ?*ndk.AInputEvent = null; while (ndk.AInputQueue_getEvent(queue, &event) >= 0) { const e = event orelse continue; if (ndk.AInputQueue_preDispatchEvent(queue, e) != 0) continue; const handled = g.inputEvent(e); ndk.AInputQueue_finishEvent(queue, e, @intFromBool(handled)); } }
fn inputEvent(g: *Game, e: *ndk.AInputEvent) bool { switch (ndk.AInputEvent_getType(e)) { ndk.AINPUT_EVENT_TYPE_MOTION => { const action = ndk.AMotionEvent_getAction(e); // A tap is a finger, or a mouse button, let go: where it // was let go. const index: usize = switch (action & ndk.AMOTION_EVENT_ACTION_MASK) { ndk.AMOTION_EVENT_ACTION_UP => 0, ndk.AMOTION_EVENT_ACTION_POINTER_UP => @intCast((action & ndk.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> ndk.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT), else => return true, }; const window = g.window orelse return true; const point: view.draw.Point = .{ ndk.AMotionEvent_getX(e, index), ndk.AMotionEvent_getY(e, index) }; g.play.tap(g.layout(window), point, clock(g.io)); g.dirty = true; return true; }, ndk.AINPUT_EVENT_TYPE_KEY => { const code = ndk.AKeyEvent_getKeyCode(e); const down = ndk.AKeyEvent_getAction(e) == ndk.AKEY_EVENT_ACTION_DOWN and ndk.AKeyEvent_getRepeatCount(e) == 0; switch (code) { // Back is not among them: the system handles it, and // sends the game to the background. ndk.AKEYCODE_ESCAPE, ndk.AKEYCODE_Q => { if (down) ndk.ANativeActivity_finish(g.activity); return true; }, ndk.AKEYCODE_R => { if (down) { g.play.restart(); g.dirty = true; } return true; }, // Volume and the rest are the system's. else => return false, } }, else => return false, } }
/// The board's layout in `window`, inside its insets. fn layout(g: *const Game, window: *ndk.ANativeWindow) view.Layout { const w: f32 = @floatFromInt(ndk.ANativeWindow_getWidth(window)); const h: f32 = @floatFromInt(ndk.ANativeWindow_getHeight(window)); const i = g.insets; const left: f32 = @floatFromInt(i.left); const top: f32 = @floatFromInt(i.top); return g.play.layoutIn( .{ left, top }, @max(1, w - left - @as(f32, @floatFromInt(i.right))), @max(1, h - top - @as(f32, @floatFromInt(i.bottom))), ); }
/// Draws a frame if one is wanted and the display is ready for it, and /// asks for the next if anything is still moving. fn frame(g: *Game) !void { const now = clock(g.io); if (try g.play.update(now)) |reached| { g.store.save(g.io, reached) catch |err| log.warn("could not save the level reached: {t}", .{err}); g.dirty = true; } const window = g.window orelse return; const swapchain = if (g.swapchain) |*s| s else return; if (!g.dirty and !g.play.animating(now)) return;
if (g.due) { g.due = false; g.dirty = false; const w: u32 = @intCast(@max(1, ndk.ANativeWindow_getWidth(window))); const h: u32 = @intCast(@max(1, ndk.ANativeWindow_getHeight(window))); g.list.clearRetainingCapacity(); try g.play.render(g.layout(window), g.theme, now, &g.list); try g.renderer.draw(w, h, g.theme.background, g.list.items, swapchain.target()); if (!g.play.animating(now)) return; } if (!g.asked) { g.asked = true; ndk.AChoreographer_postFrameCallback64(g.choreographer, onFrame, g); } }
fn onFrame(_: i64, data: ?*anyopaque) callconv(.c) void { const g: *Game = @ptrCast(@alignCast(data.?)); g.asked = false; g.due = true; }};
fn clock(io: Io) i64 { return @intCast(Io.Clock.awake.now(io).nanoseconds);}