From c5c5a241a9cc11546018daaab973dbbd69b9b668 Mon Sep 17 00:00:00 2001 From: zenith391 <39484230+zenith391@users.noreply.github.com> Date: Fri, 30 Dec 2022 18:29:53 +0100 Subject: [PATCH] update ZigAndroidTemplate --- android/.gitignore | 1 + android/LICENCE | 7 + android/README.md | 9 +- android/Sdk.zig | 105 ++-- android/build.zig | 13 +- android/build/auto-detect.zig | 11 +- android/devshell.nix | 37 ++ android/examples/egl/logo.stl | Bin 0 -> 4684 bytes android/examples/egl/main.zig | 904 +++++++++++++++++++++++++++++ android/examples/icon.png | Bin 0 -> 4812 bytes android/examples/textview/main.zig | 178 ++++++ android/flake.lock | 221 +++++++ android/flake.nix | 46 ++ android/src/jni.zig | 1 + build_capy.zig | 1 - 15 files changed, 1485 insertions(+), 49 deletions(-) create mode 100644 android/LICENCE create mode 100644 android/devshell.nix create mode 100644 android/examples/egl/logo.stl create mode 100644 android/examples/egl/main.zig create mode 100644 android/examples/icon.png create mode 100644 android/examples/textview/main.zig create mode 100644 android/flake.lock create mode 100644 android/flake.nix diff --git a/android/.gitignore b/android/.gitignore index c6f6a0ab..a769cf7e 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -1,6 +1,7 @@ zig-cache *.apk *.keystore +.vscode .build_config zig-out *.apk.idsig diff --git a/android/LICENCE b/android/LICENCE new file mode 100644 index 00000000..fe2f6f59 --- /dev/null +++ b/android/LICENCE @@ -0,0 +1,7 @@ +Copyright (c) 2020 Felix "xq" Queißner + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/android/README.md b/android/README.md index 7873863b..82e23cd5 100644 --- a/android/README.md +++ b/android/README.md @@ -47,8 +47,13 @@ There are convenience options with `zig build push` (installs the app on a conne Install the [`sdkmanager`](https://developer.android.com/studio/command-line/sdkmanager) and invoke the following command line: ``` -sdkmanager --install "platforms;android-21" # Min version: Android 5 -sdkmanager --install "build-tools;33.0.0" +# Android Platforms for your target Android version +# Min version: Android 5 +sdkmanager --install "platforms;android-21" +# you can install other versions as well +# remember to set it like `zig build -Dandroid=android99` + +sdkmanager --install "build-tools;33.0.1" sdkmanager --install "ndk;25.1.8937393" zig build keystore install run ``` diff --git a/android/Sdk.zig b/android/Sdk.zig index eb654497..998db6b1 100644 --- a/android/Sdk.zig +++ b/android/Sdk.zig @@ -45,6 +45,13 @@ folders: UserConfig, versions: ToolchainVersions, +launch_using: ADBLaunchMethod = .monkey, + +pub const ADBLaunchMethod = enum { + monkey, + am, +}; + /// Initializes the android SDK. /// It requires some input on which versions of the tool chains should be used pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions) *Sdk { @@ -55,7 +62,13 @@ pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions const zipalign = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "zipalign" ++ exe }) catch unreachable; const aapt = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "aapt" ++ exe }) catch unreachable; - const adb = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "platform-tools", "adb" ++ exe }) catch unreachable; + const adb = blk1: { + const adb_sdk = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "platform-tools", "adb" ++ exe }) catch unreachable; + if (!auto_detect.fileExists(adb_sdk)) { + break :blk1 auto_detect.findProgramPath(b.allocator, "adb") orelse @panic("No adb found"); + } + break :blk1 adb_sdk; + }; const apksigner = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "apksigner" ++ exe }) catch unreachable; const keytool = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.java_home, "bin", "keytool" ++ exe }) catch unreachable; @@ -96,7 +109,7 @@ pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions } pub const ToolchainVersions = struct { - build_tools_version: []const u8 = "33.0.0", + build_tools_version: []const u8 = "33.0.1", ndk_version: []const u8 = "25.1.8937393", }; @@ -194,8 +207,6 @@ pub const AppConfig = struct { }, libraries: []const []const u8 = &app_libs, - - packages: []const std.build.Pkg = &.{}, }; /// One of the legal targets android can be built for. @@ -448,9 +459,6 @@ pub fn createApp( \\ , .{perm}) catch unreachable; } - writer.print( - \\ - , .{ @enumToInt(app_config.target_version) }) catch unreachable; if (app_config.fullscreen) { writer.writeAll( @@ -748,9 +756,6 @@ pub fn compileAppLibrary( for (app_config.libraries) |lib| { exe.linkSystemLibraryName(lib); } - for (app_config.packages) |package| { - exe.addPackage(package); - } exe.setBuildMode(mode); @@ -924,14 +929,25 @@ pub fn installApp(sdk: Sdk, apk_file: std.build.FileSource) *Step { } pub fn startApp(sdk: Sdk, package_name: []const u8) *Step { - const step = sdk.b.addSystemCommand(&[_][]const u8{ - sdk.system_tools.adb, - "shell", - "am", - "start", - "-n", - sdk.b.fmt("{s}/android.app.NativeActivity", .{package_name}), - }); + const command: []const []const u8 = switch (sdk.launch_using) { + .am => &.{ + sdk.system_tools.adb, + "shell", + "am", + "start", + "-n", + sdk.b.fmt("{s}/android.app.NativeActivity", .{package_name}), + }, + .monkey => &.{ + sdk.system_tools.adb, + "shell", + "monkey", + "-p", + package_name, + "1", + }, + }; + const step = sdk.b.addSystemCommand(command); return &step.step; } @@ -946,28 +962,33 @@ pub const KeyConfig = struct { /// A build step that initializes a new key store from the given configuration. /// `android_config.key_store` must be non-`null` as it is used to initialize the key store. pub fn initKeystore(sdk: Sdk, key_store: KeyStore, key_config: KeyConfig) *Step { - const step = sdk.b.addSystemCommand(&[_][]const u8{ - sdk.system_tools.keytool, - "-genkey", - "-v", - "-keystore", - key_store.file, - "-alias", - key_store.alias, - "-keyalg", - @tagName(key_config.key_algorithm), - "-keysize", - sdk.b.fmt("{d}", .{key_config.key_size}), - "-validity", - sdk.b.fmt("{d}", .{key_config.validity}), - "-storepass", - key_store.password, - "-keypass", - key_store.password, - "-dname", - key_config.distinguished_name, - }); - return &step.step; + if (auto_detect.fileExists(key_store.file)) { + std.log.warn("keystore already exists: {s}", .{key_store.file}); + return sdk.b.step("init_keystore_noop", "Do nothing, since key exists"); + } else { + const step = sdk.b.addSystemCommand(&[_][]const u8{ + sdk.system_tools.keytool, + "-genkey", + "-v", + "-keystore", + key_store.file, + "-alias", + key_store.alias, + "-keyalg", + @tagName(key_config.key_algorithm), + "-keysize", + sdk.b.fmt("{d}", .{key_config.key_size}), + "-validity", + sdk.b.fmt("{d}", .{key_config.validity}), + "-storepass", + key_store.password, + "-keypass", + key_store.password, + "-dname", + key_config.distinguished_name, + }); + return &step.step; + } } const Builder = std.build.Builder; @@ -1008,9 +1029,7 @@ const zig_targets = struct { }; }; -const app_libs = [_][]const u8{ - "GLESv2", "EGL", "android", "log", "aaudio" -}; +const app_libs = [_][]const u8{ "GLESv2", "EGL", "android", "log", "aaudio" }; const BuildOptionStep = struct { const Self = @This(); diff --git a/android/build.zig b/android/build.zig index a613ebb5..39724df6 100644 --- a/android/build.zig +++ b/android/build.zig @@ -49,7 +49,7 @@ pub fn build(b: *std.build.Builder) !void { // This is a set of resources. It should at least contain a "mipmap/icon.png" resource that // will provide the application icon. .resources = &[_]Sdk.Resource{ - .{ .path = "mipmap/icon.png", .content = .{ .path = "example/icon.png" } }, + .{ .path = "mipmap/icon.png", .content = .{ .path = "examples/icon.png" } }, }, .aaudio = aaudio, @@ -66,9 +66,18 @@ pub fn build(b: *std.build.Builder) !void { .libraries = libraries.items, }; + // Replace by your app's main file. + // Here this is some code to choose the example to run + const ExampleType = enum { egl, textview }; + const example = b.option(ExampleType, "example", "Which example to run") orelse .egl; + const src = switch (example) { + .egl => "examples/egl/main.zig", + .textview => "examples/textview/main.zig", + }; + const app = sdk.createApp( "app-template.apk", - "example/main.zig", + src, config, mode, .{ diff --git a/android/build/auto-detect.zig b/android/build/auto-detect.zig index 97f1a4fa..caaba020 100644 --- a/android/build/auto-detect.zig +++ b/android/build/auto-detect.zig @@ -378,7 +378,7 @@ pub fn findUserConfig(b: *Builder, versions: Sdk.ToolchainVersions) !UserConfig return config; } -fn findProgramPath(allocator: std.mem.Allocator, program: []const u8) ?[]const u8 { +pub fn findProgramPath(allocator: std.mem.Allocator, program: []const u8) ?[]const u8 { const args: []const []const u8 = if (builtin.os.tag == .windows) &[_][]const u8{ "where", program } else @@ -493,3 +493,12 @@ fn findProblemWithJdk(b: *Builder, path: []const u8) ?[]const u8 { fn pathConcat(b: *Builder, left: []const u8, right: []const u8) []const u8 { return std.fs.path.join(b.allocator, &[_][]const u8{ left, right }) catch unreachable; } + +pub fn fileExists(path: []const u8) bool { + std.fs.cwd().access(path, .{}) catch |err| { + if (err == error.FileNotFound) return false; + std.log.debug("Cannot access {s}, {s}", .{ path, @errorName(err) }); + return false; + }; + return true; +} diff --git a/android/devshell.nix b/android/devshell.nix new file mode 100644 index 00000000..8ab64bee --- /dev/null +++ b/android/devshell.nix @@ -0,0 +1,37 @@ +{ pkgs }: + +with pkgs; + +# Configure your development environment. +# +# Documentation: https://github.com/numtide/devshell +devshell.mkShell { + name = "android-project"; + motd = '' + Entered the Android app development environment. + ''; + env = [ + { + name = "ANDROID_HOME"; + value = "${android-sdk}/share/android-sdk"; + } + { + name = "ANDROID_SDK_ROOT"; + value = "${android-sdk}/share/android-sdk"; + } + { + name = "ANDROID_NDK_ROOT"; + value = "${android-sdk}/share/android-sdk/ndk"; + } + { + name = "JAVA_HOME"; + value = jdk11.home; + } + ]; + packages = [ + android-sdk + gradle + jdk11 + zig + ]; +} diff --git a/android/examples/egl/logo.stl b/android/examples/egl/logo.stl new file mode 100644 index 0000000000000000000000000000000000000000..851ab482b634a0d1aa6037d50a304954be866076 GIT binary patch literal 4684 zcmbVQU2IfU5FQ9kEJ2APL{0cvA|{B1cDI1L+r2lDbXy+?MhrH9Qf+JcBQ2~DFiMvO zgDKGP05OPw4}=#`pu7BSH+yc=DvC%{XbpnUkVacWD4+pRpzF*%cb2(rfy8~9+;hH} z`DVVEd)va*%jzO4D#|Cl6RBG|>7{ooYRfAkIo|31yy>~{KYoi5lN<0R0M=RrAH8Ix zIkn)R`m%9UsAxioaXSB?I@~xa#m~tG_$(c@>iWxqgy{fw7 zJH*f9XakhJf6mw1R^+2N(r?2j`;FYr0)@9ya~w3;0H>3s!CmR7`TDu!A$h_GiXr0x zY^n`g0p&3%t6}Fa8NCWUJWlCS1Ayt8y zlMPVtd>oXzqvRL5R*~jgTj@KGGAwnN4GSC(HsnhP*{K*UF8UQlA~KT9Y>@D~XVt z0QNnzE!G#&S;x6 z!x?;gh#8bUki7xO33&a~J&N(hyiwL8!@sb%L9}a$YW`QxHb2+%fqU0{ZCH7d5O4l{ zT$Oa|&Dr(padmQ?-f;X}>uUbWM}22-?_zZ=>3969nCdIlTbt3OG1SzN(j@L(d&9{S zMo>TaxmHOsHE*NPcp^puRjHa)j{9>BdjC@b| z+O2$mb_Z&VasoK(>|KsdzNBByP-}PFrY$k7mAw<02c3}38smy!hNyP>bvb)i-s0ZS z6uA+h`fMLocTfy@OJ8v_*GtOR%n-*WvaPp zBd0Yh)ww#$4ArL%KRyR&zZo_+j&n9#%VeWu<$g5-Pqx%`+UJf zf7F_F<7jYVMZW60q7m(#9^>$y{c1KMb_!1b-=&@iTA^-Z-%Y1ar!$EqbuZLU?#*vEj!{j zFn8i%+vEu#HZebmJj@e+*gTBUeHwv06!I{z3dAGh2_SLx@fPG^{d~#hk;#hvQViq~ zLLPQJfM*wVsN(CD=BfGL`(+QXZkc%Qe$*}MFlJw`v|d<$G9elM^YTo!bix6YzkR ze)wgvBW(7r^H|l{T}i11sS??LfEk|r;4!Rju zM-=&3S1H~lQm^h9q^$8Z`nz48$SIQi0G9ux^19dRuO)el*%EU%;-iw?u^E^ZeP78F z$w?|7p!ZIqd31yR(w9oa81{xEm7u2#KY-ijcHh=}6O}oUoMdc0QLo%%p4o{qo;wC% z&c(d;49c#_Zp!J>F~0Kazt!Xk^B{%0=VL&O%>Ix)m&yk?{_WP>_iFV2GGq+t*R7J_ iH$L@lcCzBGkw&G$-7zRDjv;T!Dhx&pwXb9*Zp441sG-*Y literal 0 HcmV?d00001 diff --git a/android/examples/egl/main.zig b/android/examples/egl/main.zig new file mode 100644 index 00000000..c2f2ded9 --- /dev/null +++ b/android/examples/egl/main.zig @@ -0,0 +1,904 @@ +const std = @import("std"); + +const android = @import("android"); + +const audio = android.audio; +pub const panic = android.panic; +pub const log = android.log; + +const EGLContext = android.egl.EGLContext; +const JNI = android.JNI; +const c = android.egl.c; + +const app_log = std.log.scoped(.app); + +comptime { + _ = android.ANativeActivity_createFunc; +} + +/// Entry point for our application. +/// This struct provides the interface to the android support package. +pub const AndroidApp = struct { + const Self = @This(); + + const TouchPoint = struct { + /// if null, then fade out + index: ?i32, + intensity: f32, + x: f32, + y: f32, + age: i64, + }; + + allocator: std.mem.Allocator, + activity: *android.ANativeActivity, + + thread: ?std.Thread = null, + running: bool = true, + + egl_lock: std.Thread.Mutex = .{}, + egl: ?EGLContext = null, + egl_init: bool = true, + + input_lock: std.Thread.Mutex = .{}, + input: ?*android.AInputQueue = null, + + config: ?*android.AConfiguration = null, + + touch_points: [16]?TouchPoint = [1]?TouchPoint{null} ** 16, + screen_width: f32 = undefined, + screen_height: f32 = undefined, + + // audio_engine: audio.AudioEngine = .{}, + simple_synth: SimpleSynth = undefined, + + /// This is the entry point which initializes a application + /// that has stored its previous state. + /// `stored_state` is that state, the memory is only valid for this function. + pub fn init(allocator: std.mem.Allocator, activity: *android.ANativeActivity, stored_state: ?[]const u8) !Self { + _ = stored_state; + + return Self{ + .allocator = allocator, + .activity = activity, + }; + } + + /// This function is called when the application is successfully initialized. + /// It should create a background thread that processes the events and runs until + /// the application gets destroyed. + pub fn start(self: *Self) !void { + self.thread = try std.Thread.spawn(.{}, mainLoop, .{self}); + } + + /// Uninitialize the application. + /// Don't forget to stop your background thread here! + pub fn deinit(self: *Self) void { + @atomicStore(bool, &self.running, false, .SeqCst); + if (self.thread) |thread| { + thread.join(); + self.thread = null; + } + if (self.config) |config| { + android.AConfiguration_delete(config); + } + self.* = undefined; + } + + pub fn onNativeWindowCreated(self: *Self, window: *android.ANativeWindow) void { + self.egl_lock.lock(); + defer self.egl_lock.unlock(); + + if (self.egl) |*old| { + old.deinit(); + } + + self.screen_width = @intToFloat(f32, android.ANativeWindow_getWidth(window)); + self.screen_height = @intToFloat(f32, android.ANativeWindow_getHeight(window)); + + self.egl = EGLContext.init(window, .gles2) catch |err| blk: { + app_log.err("Failed to initialize EGL for window: {}\n", .{err}); + break :blk null; + }; + self.egl_init = true; + } + + pub fn onNativeWindowDestroyed(self: *Self, window: *android.ANativeWindow) void { + _ = window; + self.egl_lock.lock(); + defer self.egl_lock.unlock(); + + if (self.egl) |*old| { + old.deinit(); + } + self.egl = null; + } + + pub fn onInputQueueCreated(self: *Self, input: *android.AInputQueue) void { + self.input_lock.lock(); + defer self.input_lock.unlock(); + + self.input = input; + } + + pub fn onInputQueueDestroyed(self: *Self, input: *android.AInputQueue) void { + _ = input; + + self.input_lock.lock(); + defer self.input_lock.unlock(); + + self.input = null; + } + + fn printConfig(config: *android.AConfiguration) void { + var lang: [2]u8 = undefined; + var country: [2]u8 = undefined; + + android.AConfiguration_getLanguage(config, &lang); + android.AConfiguration_getCountry(config, &country); + + app_log.debug( + \\App Configuration: + \\ MCC: {} + \\ MNC: {} + \\ Language: {s} + \\ Country: {s} + \\ Orientation: {} + \\ Touchscreen: {} + \\ Density: {} + \\ Keyboard: {} + \\ Navigation: {} + \\ KeysHidden: {} + \\ NavHidden: {} + \\ SdkVersion: {} + \\ ScreenSize: {} + \\ ScreenLong: {} + \\ UiModeType: {} + \\ UiModeNight: {} + \\ + , .{ + android.AConfiguration_getMcc(config), + android.AConfiguration_getMnc(config), + &lang, + &country, + android.AConfiguration_getOrientation(config), + android.AConfiguration_getTouchscreen(config), + android.AConfiguration_getDensity(config), + android.AConfiguration_getKeyboard(config), + android.AConfiguration_getNavigation(config), + android.AConfiguration_getKeysHidden(config), + android.AConfiguration_getNavHidden(config), + android.AConfiguration_getSdkVersion(config), + android.AConfiguration_getScreenSize(config), + android.AConfiguration_getScreenLong(config), + android.AConfiguration_getUiModeType(config), + android.AConfiguration_getUiModeNight(config), + }); + } + + fn processKeyEvent(self: *Self, event: *android.AInputEvent) !bool { + const event_type = @intToEnum(android.AKeyEventActionType, android.AKeyEvent_getAction(event)); + std.log.scoped(.input).debug( + \\Key Press Event: {} + \\ Flags: {} + \\ KeyCode: {} + \\ ScanCode: {} + \\ MetaState: {} + \\ RepeatCount: {} + \\ DownTime: {} + \\ EventTime: {} + \\ + , .{ + event_type, + android.AKeyEvent_getFlags(event), + android.AKeyEvent_getKeyCode(event), + android.AKeyEvent_getScanCode(event), + android.AKeyEvent_getMetaState(event), + android.AKeyEvent_getRepeatCount(event), + android.AKeyEvent_getDownTime(event), + android.AKeyEvent_getEventTime(event), + }); + + if (event_type == .AKEY_EVENT_ACTION_DOWN) { + var jni = JNI.init(self.activity); + defer jni.deinit(); + + var codepoint = jni.AndroidGetUnicodeChar( + android.AKeyEvent_getKeyCode(event), + android.AKeyEvent_getMetaState(event), + ); + var buf: [8]u8 = undefined; + + var len = std.unicode.utf8Encode(codepoint, &buf) catch 0; + var key_text = buf[0..len]; + + std.log.scoped(.input).info("Pressed key: '{s}' U+{X}", .{ key_text, codepoint }); + } + + return false; + } + + fn insertPoint(self: *Self, point: TouchPoint) void { + std.debug.assert(point.index != null); + var oldest: *TouchPoint = undefined; + + if (point.index) |index| { + self.simple_synth.oscillators[@intCast(usize, index)].setWaveOn(true); + } + + for (self.touch_points) |*opt, i| { + if (opt.*) |*pt| { + if (pt.index != null and pt.index.? == point.index.?) { + pt.* = point; + return; + } + + if (i == 0) { + oldest = pt; + } else { + if (pt.age < oldest.age) { + oldest = pt; + } + } + } else { + opt.* = point; + return; + } + } + oldest.* = point; + } + + fn processMotionEvent(self: *Self, event: *android.AInputEvent) !bool { + const event_type = @intToEnum(android.AMotionEventActionType, android.AMotionEvent_getAction(event)); + + { + var jni = JNI.init(self.activity); + defer jni.deinit(); + + // Show/Hide keyboard + // _ = jni.AndroidDisplayKeyboard(true); + + // this allows you to send the app in the background + // const success = jni.AndroidSendToBack(true); + // _ = success; + // std.log.scoped(.input).debug("SendToBack() = {}\n", .{success}); + + // This is a demo on how to request permissions: + if (event_type == .AMOTION_EVENT_ACTION_UP) { + if (!JNI.AndroidHasPermissions(&jni, "android.permission.RECORD_AUDIO")) { + JNI.AndroidRequestAppPermissions(&jni, "android.permission.RECORD_AUDIO"); + } + } + } + + std.log.scoped(.input).debug( + \\Motion Event {} + \\ Flags: {} + \\ MetaState: {} + \\ ButtonState: {} + \\ EdgeFlags: {} + \\ DownTime: {} + \\ EventTime: {} + \\ XOffset: {} + \\ YOffset: {} + \\ XPrecision: {} + \\ YPrecision: {} + \\ PointerCount: {} + \\ + , .{ + event_type, + android.AMotionEvent_getFlags(event), + android.AMotionEvent_getMetaState(event), + android.AMotionEvent_getButtonState(event), + android.AMotionEvent_getEdgeFlags(event), + android.AMotionEvent_getDownTime(event), + android.AMotionEvent_getEventTime(event), + android.AMotionEvent_getXOffset(event), + android.AMotionEvent_getYOffset(event), + android.AMotionEvent_getXPrecision(event), + android.AMotionEvent_getYPrecision(event), + android.AMotionEvent_getPointerCount(event), + }); + + var i: usize = 0; + var cnt = android.AMotionEvent_getPointerCount(event); + while (i < cnt) : (i += 1) { + std.log.scoped(.input).debug( + \\Pointer {}: + \\ PointerId: {} + \\ ToolType: {} + \\ RawX: {d} + \\ RawY: {d} + \\ X: {d} + \\ Y: {d} + \\ Pressure: {} + \\ Size: {} + \\ TouchMajor: {} + \\ TouchMinor: {} + \\ ToolMajor: {} + \\ ToolMinor: {} + \\ Orientation: {} + \\ + , .{ + i, + android.AMotionEvent_getPointerId(event, i), + android.AMotionEvent_getToolType(event, i), + android.AMotionEvent_getRawX(event, i), + android.AMotionEvent_getRawY(event, i), + android.AMotionEvent_getX(event, i), + android.AMotionEvent_getY(event, i), + android.AMotionEvent_getPressure(event, i), + android.AMotionEvent_getSize(event, i), + android.AMotionEvent_getTouchMajor(event, i), + android.AMotionEvent_getTouchMinor(event, i), + android.AMotionEvent_getToolMajor(event, i), + android.AMotionEvent_getToolMinor(event, i), + android.AMotionEvent_getOrientation(event, i), + }); + + self.insertPoint(TouchPoint{ + .x = android.AMotionEvent_getX(event, i), + .y = android.AMotionEvent_getY(event, i), + .index = android.AMotionEvent_getPointerId(event, i), + .age = android.AMotionEvent_getEventTime(event), + .intensity = 1.0, + }); + } + + return false; + } + + fn mainLoop(self: *Self) !void { + // This code somehow crashes yet. Needs more investigations + var jni = JNI.init(self.activity); + defer jni.deinit(); + + // Must be called from main thread… + _ = jni.AndroidMakeFullscreen(); + + var loop: usize = 0; + app_log.info("mainLoop() started\n", .{}); + + self.config = blk: { + var cfg = android.AConfiguration_new() orelse return error.OutOfMemory; + android.AConfiguration_fromAssetManager(cfg, self.activity.assetManager); + break :blk cfg; + }; + + if (self.config) |cfg| { + printConfig(cfg); + } + + // Audio + self.simple_synth = SimpleSynth.init(); + + try audio.init(); + + var output_stream = try audio.getOutputStream(self.allocator, .{ + .sample_format = .Int16, + .callback = SimpleSynth.audioCallback, + .user_data = &self.simple_synth, + }); + defer { + output_stream.stop(); + output_stream.deinit(); + } + + try output_stream.start(); + + // Graphics + const GLuint = c.GLuint; + + var touch_program: GLuint = undefined; + var shaded_program: GLuint = undefined; + + var uPos: c.GLint = undefined; + var uAspect: c.GLint = undefined; + var uIntensity: c.GLint = undefined; + + var vPosition: c.GLuint = undefined; + + var uTransform: c.GLint = undefined; + + var mesh_vPosition: c.GLuint = undefined; + var mesh_vNormal: c.GLuint = undefined; + + var touch_buffer: c.GLuint = undefined; + var mesh_buffer: c.GLuint = undefined; + + const vVertices = [_]c.GLfloat{ + 0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0, + }; + + while (@atomicLoad(bool, &self.running, .SeqCst)) { + + // Input process + { + // we lock the handle of our input so we don't have a race condition + self.input_lock.lock(); + defer self.input_lock.unlock(); + if (self.input) |input| { + var event: ?*android.AInputEvent = undefined; + while (android.AInputQueue_getEvent(input, &event) >= 0) { + std.debug.assert(event != null); + if (android.AInputQueue_preDispatchEvent(input, event) != 0) { + continue; + } + + const event_type = @intToEnum(android.AInputEventType, android.AInputEvent_getType(event)); + const handled = switch (event_type) { + .AINPUT_EVENT_TYPE_KEY => try self.processKeyEvent(event.?), + .AINPUT_EVENT_TYPE_MOTION => try self.processMotionEvent(event.?), + else => blk: { + std.log.scoped(.input).debug("Unhandled input event type ({})\n", .{event_type}); + break :blk false; + }, + }; + + // if (app.onInputEvent != NULL) + // handled = app.onInputEvent(app, event); + android.AInputQueue_finishEvent(input, event, if (handled) @as(c_int, 1) else @as(c_int, 0)); + } + } + } + + // Render process + { + // same for the EGL context + self.egl_lock.lock(); + defer self.egl_lock.unlock(); + if (self.egl) |egl| { + try egl.makeCurrent(); + + if (self.egl_init) { + enableDebug(); + app_log.info( + \\GL Vendor: {s} + \\GL Renderer: {s} + \\GL Version: {s} + \\GL Extensions: {s} + \\ + , .{ + std.mem.span(c.glGetString(c.GL_VENDOR)), + std.mem.span(c.glGetString(c.GL_RENDERER)), + std.mem.span(c.glGetString(c.GL_VERSION)), + std.mem.span(c.glGetString(c.GL_EXTENSIONS)), + }); + + touch_program = c.glCreateProgram(); + { + var ps = c.glCreateShader(c.GL_VERTEX_SHADER); + var fs = c.glCreateShader(c.GL_FRAGMENT_SHADER); + + var ps_code = + \\attribute vec2 vPosition; + \\varying vec2 uv; + \\void main() { + \\ uv = vPosition; + \\ gl_Position = vec4(2.0 * uv - 1.0, 0.0, 1.0); + \\} + \\ + ; + var fs_code = + \\varying highp vec2 uv; + \\uniform highp vec2 uPos; + \\uniform highp float uAspect; + \\uniform highp float uIntensity; + \\void main() { + \\ highp vec2 rel = uv - uPos; + \\ rel.x *= uAspect; + \\ gl_FragColor = vec4(vec3(pow(uIntensity * clamp(1.0 - 10.0 * length(rel), 0.0, 1.0), 2.2)), 1.0); + \\} + \\ + ; + + c.glShaderSource(ps, 1, @ptrCast([*c]const [*c]const u8, &ps_code), null); + c.glShaderSource(fs, 1, @ptrCast([*c]const [*c]const u8, &fs_code), null); + + c.glCompileShader(ps); + c.glCompileShader(fs); + + glCheckError(ps); + glCheckError(fs); + + c.glAttachShader(touch_program, ps); + c.glAttachShader(touch_program, fs); + + glShaderInfoLog(ps); + glShaderInfoLog(fs); + + c.glBindAttribLocation(touch_program, 0, "vPosition"); + c.glLinkProgram(touch_program); + + glCheckError(touch_program); + + c.glDetachShader(touch_program, ps); + c.glDetachShader(touch_program, fs); + + glProgramInfoLog(touch_program); + } + + // Get uniform locations + uPos = c.glGetUniformLocation(touch_program, "uPos"); + uAspect = c.glGetUniformLocation(touch_program, "uAspect"); + uIntensity = c.glGetUniformLocation(touch_program, "uIntensity"); + + // Get attrib locations + const vPosition_res = c.glGetAttribLocation(touch_program, "vPosition"); + app_log.info("vPosition: {}", .{vPosition_res}); + vPosition = @intCast(c.GLuint, vPosition_res); + + // Bind the vertices to the buffer + c.glGenBuffers(1, &touch_buffer); + c.glBindBuffer(c.GL_ARRAY_BUFFER, touch_buffer); + c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(isize, vVertices[0..].len * @sizeOf(c.GLfloat)), vVertices[0..], c.GL_STATIC_DRAW); + + shaded_program = c.glCreateProgram(); + { + var ps = c.glCreateShader(c.GL_VERTEX_SHADER); + var fs = c.glCreateShader(c.GL_FRAGMENT_SHADER); + + var ps_code = + \\#version 100 + \\attribute vec3 vPosition; + \\attribute vec3 vNormal; + \\uniform mat4 uTransform; + \\varying vec3 normal; + \\void main() { + \\ normal = mat3(uTransform) * vNormal; + \\ gl_Position = uTransform * vec4(vPosition, 1.0); + \\} + \\ + ; + var fs_code = + \\#version 100 + \\varying highp vec3 normal; + \\void main() { + \\ highp vec3 base_color = vec3(0.968,0.643,0.113); // #F7A41D + \\ highp vec3 ldir = normalize(vec3(0.3, 0.4, 2.0)); + \\ highp float l = 0.3 + 0.8 * clamp(-dot(normal, ldir), 0.0, 1.0); + \\ gl_FragColor = vec4(l * base_color,1); + \\} + \\ + ; + + c.glShaderSource(ps, 1, @ptrCast([*c]const [*c]const u8, &ps_code), null); + c.glShaderSource(fs, 1, @ptrCast([*c]const [*c]const u8, &fs_code), null); + + c.glCompileShader(ps); + c.glCompileShader(fs); + + glShaderInfoLog(ps); + glShaderInfoLog(fs); + + c.glAttachShader(shaded_program, ps); + c.glAttachShader(shaded_program, fs); + + c.glBindAttribLocation(shaded_program, 0, "vPosition"); + c.glBindAttribLocation(shaded_program, 1, "vNormal"); + c.glLinkProgram(shaded_program); + + c.glDetachShader(shaded_program, ps); + c.glDetachShader(shaded_program, fs); + + glProgramInfoLog(shaded_program); + } + + uTransform = c.glGetUniformLocation(shaded_program, "uTransform"); + + // Get attrib locations + const mesh_vPosition_res = c.glGetAttribLocation(shaded_program, "vPosition"); + app_log.info("mesh_vPosition: {}", .{mesh_vPosition_res}); + mesh_vPosition = @intCast(c.GLuint, mesh_vPosition_res); + const mesh_vNormal_res = c.glGetAttribLocation(shaded_program, "vNormal"); + app_log.info("mesh_vNormal: {}", .{mesh_vNormal_res}); + mesh_vNormal = @intCast(c.GLuint, mesh_vNormal_res); + + // Bind the vertices to the buffer + c.glGenBuffers(1, &mesh_buffer); + c.glBindBuffer(c.GL_ARRAY_BUFFER, mesh_buffer); + c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(isize, mesh.len * @sizeOf(MeshVertex)), &mesh, c.GL_STATIC_DRAW); + + self.egl_init = false; + } + + const t = @intToFloat(f32, loop) / 100.0; + + // Clear the screen + c.glClearColor( + 0.5 + 0.5 * @sin(t + 0.0), + 0.5 + 0.5 * @sin(t + 1.0), + 0.5 + 0.5 * @sin(t + 2.0), + 1.0, + ); + c.glClear(c.GL_COLOR_BUFFER_BIT); + + // -- Start touch display code + c.glUseProgram(touch_program); + + c.glBindBuffer(c.GL_ARRAY_BUFFER, touch_buffer); + + c.glEnableVertexAttribArray(vPosition); + c.glVertexAttribPointer(vPosition, 2, c.GL_FLOAT, c.GL_FALSE, 0, @intToPtr(?*anyopaque, 0)); + + // c.glDisableVertexAttribArray(1); + + c.glDisable(c.GL_DEPTH_TEST); + c.glEnable(c.GL_BLEND); + c.glBlendFunc(c.GL_ONE, c.GL_ONE); + c.glBlendEquation(c.GL_FUNC_ADD); + + for (self.touch_points) |*pt| { + if (pt.*) |*point| { + c.glUniform1f(uAspect, self.screen_width / self.screen_height); + c.glUniform2f(uPos, point.x / self.screen_width, 1.0 - point.y / self.screen_height); + c.glUniform1f(uIntensity, point.intensity); + c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 4); + + point.intensity -= 0.05; + if (point.intensity <= 0.0) { + if (point.index) |index| { + self.simple_synth.oscillators[@intCast(usize, index)].setWaveOn(false); + } + pt.* = null; + } + } + } + glDrainErrors(); + + // -- Start 3d zig logo code + c.glBindBuffer(c.GL_ARRAY_BUFFER, mesh_buffer); + c.glEnableVertexAttribArray(mesh_vPosition); + c.glVertexAttribPointer(mesh_vPosition, 3, c.GL_FLOAT, c.GL_FALSE, @sizeOf(MeshVertex), @intToPtr(?*anyopaque, @offsetOf(MeshVertex, "pos"))); + + c.glEnableVertexAttribArray(mesh_vNormal); + c.glVertexAttribPointer(mesh_vNormal, 3, c.GL_FLOAT, c.GL_FALSE, @sizeOf(MeshVertex), @intToPtr(?*anyopaque, @offsetOf(MeshVertex, "normal"))); + + c.glUseProgram(shaded_program); + + c.glClearDepthf(1.0); + c.glClear(c.GL_DEPTH_BUFFER_BIT); + + c.glDisable(c.GL_BLEND); + c.glEnable(c.GL_DEPTH_TEST); + + var matrix = [4][4]f32{ + [4]f32{ 1, 0, 0, 0 }, + [4]f32{ 0, 1, 0, 0 }, + [4]f32{ 0, 0, 1, 0 }, + [4]f32{ 0, 0, 0, 1 }, + }; + + matrix[1][1] = self.screen_width / self.screen_height; + + matrix[0][0] = @sin(t); + matrix[2][0] = @cos(t); + matrix[0][2] = @cos(t); + matrix[2][2] = -@sin(t); + + c.glUniformMatrix4fv(uTransform, 1, c.GL_FALSE, @ptrCast([*]const f32, &matrix)); + + c.glDrawArrays(c.GL_TRIANGLES, 0, mesh.len); + + glDrainErrors(); + + try egl.swapBuffers(); + } + } + loop += 1; + + std.time.sleep(10 * std.time.ns_per_ms); + } + app_log.info("mainLoop() finished\n", .{}); + } +}; + +const MeshVertex = extern struct { + pos: Vector4, + normal: Vector4, +}; + +const Vector4 = extern struct { + x: f32, + y: f32, + z: f32, + w: f32 = 1.0, + + fn readFromSlice(slice: []const u8) Vector4 { + return Vector4{ + .x = @bitCast(f32, std.mem.readIntLittle(u32, slice[0..4])), + .y = @bitCast(f32, std.mem.readIntLittle(u32, slice[4..8])), + .z = @bitCast(f32, std.mem.readIntLittle(u32, slice[8..12])), + .w = 1.0, + }; + } +}; + +const mesh = blk: { + const stl_data = @embedFile("logo.stl"); + + const count = std.mem.readIntLittle(u32, stl_data[80..][0..4]); + + var slice: []const u8 = stl_data[84..]; + + var array: [3 * count]MeshVertex = undefined; + var index: usize = 0; + + @setEvalBranchQuota(10_000); + + while (index < count) : (index += 1) { + const normal = Vector4.readFromSlice(slice[0..]); + const v1 = Vector4.readFromSlice(slice[12..]); + const v2 = Vector4.readFromSlice(slice[24..]); + const v3 = Vector4.readFromSlice(slice[36..]); + const attrib_count = std.mem.readIntLittle(u16, slice[48..50]); + + array[3 * index + 0] = MeshVertex{ + .pos = v1, + .normal = normal, + }; + array[3 * index + 1] = MeshVertex{ + .pos = v2, + .normal = normal, + }; + array[3 * index + 2] = MeshVertex{ + .pos = v3, + .normal = normal, + }; + + slice = slice[50 + attrib_count ..]; + } + + break :blk array; +}; + +pub fn glProgramInfoLog(program: c.GLuint) void { + var buffer: [4096]u8 = undefined; + var size: c.GLsizei = undefined; + c.glGetProgramInfoLog(program, 4096, &size, &buffer); + if (size == 0) return; + app_log.info("{s}", .{buffer[0..@intCast(usize, size)]}); +} + +pub fn glShaderInfoLog(shader: c.GLuint) void { + var buffer: [4096]u8 = undefined; + var size: c.GLsizei = undefined; + c.glGetShaderInfoLog(shader, 4096, &size, &buffer); + if (size == 0) return; + app_log.info("{s}", .{buffer[0..@intCast(usize, size)]}); +} + +pub fn glCheckError(res: i64) void { + switch (res) { + c.GL_INVALID_ENUM => app_log.err("GL error code {}: Invalid enum", .{res}), + c.GL_INVALID_VALUE => app_log.err("GL error code {}: Invalid value", .{res}), + c.GL_INVALID_OPERATION => app_log.err("GL error code {}: Invalid operation", .{res}), + // c.GL_STACK_OVERFLOW => app_log.err("GL error code {}: Stack overflow", .{res}), + // c.GL_STACK_UNDERFLOW => app_log.err("GL error code {}: Stack underflow", .{res}), + c.GL_OUT_OF_MEMORY => app_log.err("GL error code {}: Out of memory", .{res}), + // c.GL_TABLE_TOO_LARGE => app_log.err("GL error code {}: Table too large", .{res}), + c.GL_NO_ERROR => {}, + else => {}, + } +} + +pub fn glDrainErrors() void { + var res = c.glGetError(); + while (res != c.GL_NO_ERROR) : (res = c.glGetError()) { + glCheckError(res); + } +} + +pub fn enableDebug() void { + const extensions = std.mem.span(c.glGetString(c.GL_EXTENSIONS)); + if (std.mem.indexOf(u8, extensions, "GL_KHR_debug") != null) { + c.glEnable(c.GL_DEBUG_OUTPUT_KHR); + c.glEnable(c.GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR); + + const glDebugMessageControl = @ptrCast(c.PFNGLDEBUGMESSAGECONTROLKHRPROC, c.eglGetProcAddress("glDebugMessageControl")).?; + glDebugMessageControl(c.GL_DONT_CARE, c.GL_DONT_CARE, c.GL_DEBUG_SEVERITY_NOTIFICATION_KHR, 0, null, c.GL_TRUE); + + const glDebugMessageCallback = @ptrCast(c.PFNGLDEBUGMESSAGECALLBACKKHRPROC, c.eglGetProcAddress("glDebugMessageCallback")).?; + glDebugMessageCallback(debugMessageCallback, null); + } else { + app_log.err("Debug is not supported.", .{}); + } +} + +pub fn debugMessageCallback( + source: c.GLenum, + logtype: c.GLenum, + id: c.GLuint, + severity: c.GLenum, + length: c.GLsizei, + message_c: ?[*]const c.GLchar, + user_param: ?*const anyopaque, +) callconv(.C) void { + _ = user_param; + const message = message: { + if (message_c) |message_ptr| { + break :message if (length > 0) message_ptr[0..@intCast(usize, length)] else ""; + } else { + break :message ""; + } + }; + const logtype_str = switch (logtype) { + c.GL_DEBUG_TYPE_ERROR_KHR => "Error", + c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR => "Deprecated Behavior", + c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR => "Undefined Behavior", + c.GL_DEBUG_TYPE_PORTABILITY_KHR => "Portability", + c.GL_DEBUG_TYPE_PERFORMANCE_KHR => "Performance", + c.GL_DEBUG_TYPE_OTHER_KHR => "Other", + c.GL_DEBUG_TYPE_MARKER_KHR => "Marker", + else => "Unknown/invalid type", + }; + app_log.err("source = {}, type = {s}, id = {}, severity = {}, message = {s}", .{ source, logtype_str, id, severity, message }); +} + +const Oscillator = struct { + isWaveOn: bool = false, + phase: f64 = 0.0, + phaseIncrement: f64 = 0, + frequency: f64 = 440, + amplitude: f64 = 0.1, + + fn setWaveOn(self: *@This(), isWaveOn: bool) void { + @atomicStore(bool, &self.isWaveOn, isWaveOn, .SeqCst); + } + + fn setSampleRate(self: *@This(), sample_rate: i32) void { + self.phaseIncrement = (std.math.tau * self.frequency) / @intToFloat(f64, sample_rate); + } + + fn renderf32(self: *@This(), audio_data: []f32) void { + if (!@atomicLoad(bool, &self.isWaveOn, .SeqCst)) self.phase = 0; + + for (audio_data) |*frame| { + if (@atomicLoad(bool, &self.isWaveOn, .SeqCst)) { + frame.* += @floatCast(f32, std.math.sin(self.phase) * self.amplitude); + self.phase += self.phaseIncrement; + if (self.phase > std.math.tau) self.phase -= std.math.tau; + } + } + } + + fn renderi16(self: *@This(), audio_data: []i16) void { + if (!@atomicLoad(bool, &self.isWaveOn, .SeqCst)) self.phase = 0; + + for (audio_data) |*frame| { + if (@atomicLoad(bool, &self.isWaveOn, .SeqCst)) { + frame.* +|= @floatToInt(i16, @floatCast(f32, std.math.sin(self.phase) * self.amplitude) * std.math.maxInt(i16)); + self.phase += self.phaseIncrement; + if (self.phase > std.math.tau) self.phase -= std.math.tau; + } + } + } +}; + +const SimpleSynth = struct { + oscillators: [10]Oscillator = [1]Oscillator{.{}} ** 10, + + fn init() SimpleSynth { + var synth = SimpleSynth{}; + for (synth.oscillators) |*osc, index| { + osc.* = Oscillator{ + .frequency = audio.midiToFreq(49 + index * 3), + .amplitude = audio.dBToAmplitude(-@intToFloat(f64, index) - 15), + }; + } + return synth; + } + + fn audioCallback(stream: audio.StreamLayout, user_data: *anyopaque) void { + var synth = @ptrCast(*SimpleSynth, @alignCast(@alignOf(SimpleSynth), user_data)); + std.debug.assert(stream.buffer == .Int16); + + for (synth.oscillators) |*osc| { + osc.setSampleRate(@intCast(i32, stream.sample_rate)); + osc.renderi16(stream.buffer.Int16); + } + } +}; diff --git a/android/examples/icon.png b/android/examples/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..7ea4bd87ea6b463338901e4dc0c9c496bdd46541 GIT binary patch literal 4812 zcmV;-5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OEMEyU6007_uc6KId7l4sH(Zxg1_?`}MfN>74 z0Z0(iOu`_CfQuXqPMZMOfcd*kBvlS>0)p5TRsmPKfX_P2XswDj-fz+G-4zPe2E5*L zE>_Zu($c#L_&8+LFpiD?Fak8wT>Da`ddsv@%aQghFv~q0A>8Q87PES) z|7$zc4lc8gzIPvRxSiF|(6+7B{QJ8#`lhe{XOS5o1FAvj&0Dv}Y@(pWO@6S+!2YHLsy0N-PXvbHU$mMJj&}%|s?5S9Fyqpt9c@1!k`~ywmpuyL zLNGpd<9=E&X`tn%$uCDXK6b7>XF-KpZ*u-L`T)m8KtNGu*kl^=&UQ^}iSo@C_$*}( zE3>OAQDf9x|K{%6YmamP&z{)kpLv=~Jm>PY@y7fA!ruqzhb4k%V;l18-h}e12BztI8P;W>kV4d(nq%{^d zwbz1LQ&^+tPGEmt+ex=S`c-n5YVgXtK8nAWFsUpU3N5a#s~gD~+mX80L>STdr0Uw* z57zB7LZ&GH0smj{`Ful56y-pP&wFRU>w9qFk4_B^E%q-snKk{2@-x3jc?f_Q@F", "(Landroid/content/Context;)V" }); + const textView = jni.invokeJni(.NewObject, .{ TextView, textViewInit, self.activity.clazz }); + + // .. and set its text to "Hello from Zig!" + const setText = jni.invokeJni(.GetMethodID, .{ TextView, "setText", "(Ljava/lang/CharSequence;)V" }); + jni.invokeJni(.CallVoidMethod, .{ textView, setText, jni.newString("Hello from Zig!") }); + + // And then we use it as our content view! + std.log.err("Attempt to call NativeActivity.setContentView()", .{}); + const activityClass = jni.findClass("android/app/NativeActivity"); + const setContentView = jni.invokeJni(.GetMethodID, .{ activityClass, "setContentView", "(Landroid/view/View;)V" }); + jni.invokeJni(.CallVoidMethod, .{ + self.activity.clazz, + setContentView, + textView, + }); + } + + fn mainLoop(self: *AndroidApp) !void { + self.mainJni = JNI.init(self.activity); + defer self.mainJni.deinit(); + + try self.runOnUiThread(setAppContentView, .{ self }); + while (self.running) { + std.time.sleep(1 * std.time.ns_per_s); + } + } +}; diff --git a/android/flake.lock b/android/flake.lock new file mode 100644 index 00000000..c7589b6f --- /dev/null +++ b/android/flake.lock @@ -0,0 +1,221 @@ +{ + "nodes": { + "android": { + "inputs": { + "devshell": "devshell", + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + }, + "locked": { + "lastModified": 1671654171, + "narHash": "sha256-oWJLYZip4KRe0cv859DRnjokb6C4so7cc50ucQoFNac=", + "owner": "tadfisher", + "repo": "android-nixpkgs", + "rev": "068776b833f7cbd4e1796a71ba306296ecda1629", + "type": "github" + }, + "original": { + "owner": "tadfisher", + "repo": "android-nixpkgs", + "type": "github" + } + }, + "devshell": { + "inputs": { + "flake-utils": [ + "android", + "nixpkgs" + ], + "nixpkgs": [ + "android", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1671489820, + "narHash": "sha256-qoei5HDJ8psd1YUPD7DhbHdhLIT9L2nadscp4Qk37uk=", + "owner": "numtide", + "repo": "devshell", + "rev": "5aa3a8039c68b4bf869327446590f4cdf90bb634", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "devshell", + "type": "github" + } + }, + "devshell_2": { + "inputs": { + "flake-utils": "flake-utils_2", + "nixpkgs": "nixpkgs_2" + }, + "locked": { + "lastModified": 1671489820, + "narHash": "sha256-qoei5HDJ8psd1YUPD7DhbHdhLIT9L2nadscp4Qk37uk=", + "owner": "numtide", + "repo": "devshell", + "rev": "5aa3a8039c68b4bf869327446590f4cdf90bb634", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "devshell", + "type": "github" + } + }, + "flake-utils": { + "locked": { + "lastModified": 1667395993, + "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_2": { + "locked": { + "lastModified": 1642700792, + "narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "846b2ae0fc4cc943637d3d1def4454213e203cba", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_3": { + "locked": { + "lastModified": 1667395993, + "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_4": { + "locked": { + "lastModified": 1659877975, + "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1671359686, + "narHash": "sha256-3MpC6yZo+Xn9cPordGz2/ii6IJpP2n8LE8e/ebUXLrs=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "04f574a1c0fde90b51bf68198e2297ca4e7cccf4", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1643381941, + "narHash": "sha256-pHTwvnN4tTsEKkWlXQ8JMY423epos8wUOhthpwJjtpc=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "5efc8ca954272c4376ac929f4c5ffefcc20551d5", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_3": { + "locked": { + "lastModified": 1671653751, + "narHash": "sha256-YjhztZ2zana/WXhWKUzOdIrsoCd+edtum42X4U4ml4A=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6653a5a9320034a952fb39e310f1ff122bd0f12a", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_4": { + "locked": { + "lastModified": 1661151577, + "narHash": "sha256-++S0TuJtuz9IpqP8rKktWyHZKpgdyrzDFUXVY07MTRI=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "54060e816971276da05970a983487a25810c38a7", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "android": "android", + "devshell": "devshell_2", + "flake-utils": "flake-utils_3", + "nixpkgs": "nixpkgs_3", + "zig": "zig" + } + }, + "zig": { + "inputs": { + "flake-utils": "flake-utils_4", + "nixpkgs": "nixpkgs_4" + }, + "locked": { + "lastModified": 1671624479, + "narHash": "sha256-cwQzVb+1X7aDCXExVwCzoAx9NYU4XYr0EQyOqigIw/g=", + "owner": "mitchellh", + "repo": "zig-overlay", + "rev": "dd83b3c67d8d8cc198cec4cefb5d0fac83dcd917", + "type": "github" + }, + "original": { + "owner": "mitchellh", + "repo": "zig-overlay", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/android/flake.nix b/android/flake.nix new file mode 100644 index 00000000..beac2e56 --- /dev/null +++ b/android/flake.nix @@ -0,0 +1,46 @@ +{ + description = "My Android project"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs"; + devshell.url = "github:numtide/devshell"; + flake-utils.url = "github:numtide/flake-utils"; + android.url = "github:tadfisher/android-nixpkgs"; + zig.url = "github:mitchellh/zig-overlay"; + }; + + outputs = { self, nixpkgs, devshell, flake-utils, android, zig }: + { + overlay = final: prev: { + inherit (self.packages.${final.system}) android-sdk zig; + }; + } + // + flake-utils.lib.eachSystem [ "x86_64-linux" ] (system: + let + pkgs = import nixpkgs { + inherit system; + config.allowUnfree = true; + overlays = [ + devshell.overlay + self.overlay + ]; + }; + in + { + packages = { + zig = zig.packages.${system}.master; + android-sdk = android.sdk.${system} (sdkPkgs: with sdkPkgs; [ + # Useful packages for building and testing. + build-tools-33-0-1 + cmdline-tools-latest + platform-tools + platforms-android-21 + ndk-25-1-8937393 + ]); + }; + + devShell = import ./devshell.nix { inherit pkgs; }; + } + ); +} diff --git a/android/src/jni.zig b/android/src/jni.zig index 1f864fcb..161386a0 100644 --- a/android/src/jni.zig +++ b/android/src/jni.zig @@ -15,6 +15,7 @@ pub const JNI = struct { return fromJniEnv(activity, env); } + /// Get the JNIEnv associated with the current thread. pub fn get(activity: *android.ANativeActivity) Self { var env: *android.JNIEnv = undefined; _ = activity.vm.*.GetEnv(activity.vm, @ptrCast(*?*anyopaque, &env), android.JNI_VERSION_1_6); diff --git a/build_capy.zig b/build_capy.zig index 0f67031f..d3c80e23 100644 --- a/build_capy.zig +++ b/build_capy.zig @@ -127,7 +127,6 @@ pub fn install(step: *std.build.LibExeObjStep, options: CapyBuildOptions) !void }, // This is a list of native android apis to link against. .libraries = libraries.items, - .packages = &.{ }, //.fullscreen = true, };