kart: GLES fallback renderer + armv7 ABI
- Commit
961e0325b86c879151568b1a8e2764f5b940231b- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-18 17:19 UTC (1 month ago)
- Parents
4c5e811
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 3e0122032a..40e4c991e7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1745,6 +1745,18 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]]+name = "glow"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd348e04c43b32574f2de31c8bb397d96c9fcfa1371bd4ca6d8bdc464ab121b1"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]+ [[package]] name = "group" version = "0.13.0"@@ -2438,7 +2450,9 @@ version = "0.1.0" dependencies = [ "ash", "glam",+ "glow", "jni",+ "khronos-egl", "serde", "serde_json", ]@@ -2506,6 +2520,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading",+]+ [[package]] name = "kurbo" version = "0.13.1"@@ -4553,6 +4577,15 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]+ [[package]] name = "smallvec" version = "1.16.3"
games/kart/build.gradle.kts
diff --git a/games/kart/build.gradle.kts b/games/kart/build.gradle.ktsindex 9c4a8de0ac..e1d798e2a7 100644--- a/games/kart/build.gradle.kts+++ b/games/kart/build.gradle.kts@@ -15,6 +15,13 @@ android { } } +// ONN 4K box (32-bit armeabi-v7a userspace, Mali-G31, no Vulkan): the GLES+// fallback in src/main/rust/gles renders 3D there. Same arrangement as+// :cast:tv + :library:e2ee-p2p (the only armv7 precedent in the tree).+nativeAbis {+ armv7 = true+}+ androidComponents { onVariants { variant -> variant.sources.jniLibs?.addStaticSourceDirectory(@@ -28,7 +35,10 @@ androidComponents { // KartNative.isAvailable gates every call, so devices without the .so run the // placeholder race. Listing images are hand-captured (Layoutlib can't render // the Vulkan surface); see the plan's verification notes.-rustNativeLib("kart_engine", "kart")+// armeabi-v7a as well as arm64: the ONN box runs this app directly on 32-bit+// Google TV hardware. Only kart_engine opts in (:library:e2ee-p2p precedent) —+// no other native module changes.+rustNativeLib("kart_engine", "kart", extraAbis = listOf(ABI_ARMV7)) dependencies { implementation(project(":sdk:games"))
games/kart/src/main/rust/Cargo.toml
diff --git a/games/kart/src/main/rust/Cargo.toml b/games/kart/src/main/rust/Cargo.tomlindex e14d75d9e3..6d89baa8a6 100644--- a/games/kart/src/main/rust/Cargo.toml+++ b/games/kart/src/main/rust/Cargo.toml@@ -15,3 +15,11 @@ ash = { workspace = true, default-features = false, features = ["loaded"] } glam = { workspace = true, features = ["serde"] } serde = { workspace = true, features = ["derive"] } serde_json.workspace = true+# GLES fallback for Vulkan-less devices (ONN 4K box, Mali-G31, armeabi-v7a):+# glow 0.13 loads GL symbols via eglGetProcAddress; khronos-egl 6 (the plan's+# "0.1" pin was never published) provides the EGL display/surface/context+# wrappers. `dynamic` (dlopen at runtime) — NOT `static`: that feature probes+# pkg-config for egl at build time, which fails for Android cross-compiles and+# on hosts without system EGL (e.g. Windows dev machines).+glow = "0.13"+khronos-egl = { version = "6", features = ["dynamic"] }
games/kart/src/main/rust/shaders/kart_gles.frag
diff --git a/games/kart/src/main/rust/shaders/kart_gles.frag b/games/kart/src/main/rust/shaders/kart_gles.fragnew file mode 100644index 0000000000..7068e92907--- /dev/null+++ b/games/kart/src/main/rust/shaders/kart_gles.frag@@ -0,0 +1,27 @@+#version 300 es+// Flat shading plus distance fog (GLES 3.0 port of kart.frag): one fixed sun+// direction, no shadow maps. Karts read as solid boxes against the track; the+// fog melts the far side of the oval into the sky clear color so the pop-in+// line never shows. Same `ndl` lighting + `exp` fog 0.0045 to+// SKY(0.45, 0.68, 0.94) as the Vulkan twin.+precision mediump float;++in vec3 vColor;+in vec3 vWorld;++out vec4 outColor;++uniform mat4 uViewProj;+uniform vec3 uSunDir;+uniform vec3 uCamPos;++const vec3 SKY = vec3(0.45, 0.68, 0.94);++void main() {+ vec3 up = vec3(0.0, 1.0, 0.0);+ float ndl = 0.72 + 0.28 * clamp(dot(up, normalize(uSunDir)), 0.0, 1.0);+ vec3 col = vColor * ndl;+ float dist = length(vWorld - uCamPos);+ float fog = 1.0 - exp(-dist * 0.0045);+ outColor = vec4(mix(col, SKY, clamp(fog, 0.0, 1.0)), 1.0);+}
games/kart/src/main/rust/shaders/kart_gles.vert
diff --git a/games/kart/src/main/rust/shaders/kart_gles.vert b/games/kart/src/main/rust/shaders/kart_gles.vertnew file mode 100644index 0000000000..9a5f7ba3a9--- /dev/null+++ b/games/kart/src/main/rust/shaders/kart_gles.vert@@ -0,0 +1,20 @@+#version 300 es+// Unlit vertex-color kart shader (GLES 3.0 port of kart.vert): the mesh+// carries the art (asphalt gray, grass green, per-kart box colors), so no+// textures and no samplers. The Vulkan `clip.y` flip is removed — OpenGL NDC+// Y already points up — so winding stays as authored (cull off either way).+layout(location = 0) in vec3 inPos;+layout(location = 1) in vec3 inColor;++out vec3 vColor;+out vec3 vWorld;++uniform mat4 uViewProj;+uniform vec3 uSunDir;+uniform vec3 uCamPos;++void main() {+ vColor = inColor;+ vWorld = inPos;+ gl_Position = uViewProj * vec4(inPos, 1.0);+}
games/kart/src/main/rust/src/engine.rs
diff --git a/games/kart/src/main/rust/src/engine.rs b/games/kart/src/main/rust/src/engine.rsindex 68dea96cef..89e7c4b69d 100644--- a/games/kart/src/main/rust/src/engine.rs+++ b/games/kart/src/main/rust/src/engine.rs@@ -6,9 +6,11 @@ //! chase camera, draw. Everything fallible returns `Option`/`Result` — the //! JNI boundary logs and keeps the placeholder running rather than crashing. +use crate::gles::renderer::GlesRenderer; use crate::mesh::{self, KartVertex}; use crate::physics::DriveInput; use crate::race::Race;+use crate::renderer::Renderer; use crate::vulkan::context::{ANativeWindow, VulkanContext}; use crate::vulkan::renderer::KartRenderer; use std::sync::{Mutex, OnceLock};@@ -22,7 +24,7 @@ pub struct EngineState { /// The live race (created by `start_race`). pub race: Option<Race>, /// The renderer (created by `create_renderer`).- pub renderer: Option<KartRenderer>,+ pub renderer: Option<Renderer>, /// Static track vertex count (from the last `upload_track`). pub track_count: usize, /// Pending human inputs by seat, written by the JNI setters and consumed@@ -153,8 +155,10 @@ fn escape(s: &str) -> String { s.replace('\\', "\\\\").replace('"', "\\\"") } -/// Create the renderer for a live window. Fails cleanly (None) — the Kotlin-/// side keeps the placeholder when this returns false.+/// Create the renderer for a live window. Tries Vulkan first, then GLES;+/// fails cleanly (None) — the Kotlin side keeps the placeholder when this+/// returns false. The winning backend is logged to logcat (`kart_engine` tag)+/// so device triage can see which path engaged. /// /// # Safety /// `window` must be a live `ANativeWindow` adopted from the JNI surface (the@@ -164,15 +168,25 @@ pub unsafe fn create_renderer(window: *mut ANativeWindow, width: i32, height: i3 state.window_ptr = Some(window); state.width = width.max(1) as u32; state.height = height.max(1) as u32;- let ctx = match unsafe { VulkanContext::new(window, width, height) } {- Ok(c) => c,- Err(_) => return false,- };- let renderer = match unsafe {- KartRenderer::new(ctx, state.width, state.height)- } {- Ok(r) => r,- Err(_) => return false,+ let mut renderer = match try_vulkan(window, width, height, state.width, state.height) {+ Ok(r) => {+ log_backend("Vulkan");+ r+ }+ Err(vulkan_err) => match unsafe {+ GlesRenderer::new(window, state.width, state.height)+ } {+ Ok(r) => {+ log_backend(&format!("GLES (Vulkan init failed: {vulkan_err})"));+ Renderer::Gles(r)+ }+ Err(gles_err) => {+ log_backend(&format!(+ "no renderer (Vulkan: {vulkan_err}; GLES: {gles_err})"+ ));+ return false;+ }+ }, }; // A race may already be live (surface recreated on rotation): upload. if state.race.is_some() {@@ -187,8 +201,59 @@ pub unsafe fn create_renderer(window: *mut ANativeWindow, width: i32, height: i3 .unwrap_or(false) } -/// Resize: recreate the swapchain at the new size. If recreation fails the-/// renderer is dropped and the next frame re-creates it (placeholder covers).+/// Try the Vulkan path, returning the error string on failure (for the+/// logcat fallback line). Ownership of `window` stays with the engine either+/// way — the caller releases it when creation fails overall.+///+/// # Safety+/// Same contract as [`create_renderer`].+unsafe fn try_vulkan(+ window: *mut ANativeWindow,+ width: i32,+ height: i32,+ state_width: u32,+ state_height: u32,+) -> Result<Renderer, String> {+ let ctx = match unsafe { VulkanContext::new(window, width, height) } {+ Ok(c) => c,+ Err(e) => return Err(format!("context: {e}")),+ };+ match unsafe { KartRenderer::new(ctx, state_width, state_height) } {+ Ok(r) => Ok(Renderer::Vulkan(r)),+ Err(e) => Err(format!("renderer: {e}")),+ }+}++/// One logcat line naming the winning backend (the `kart_engine` tag the+/// plan's triage filters on). `__android_log_print` on device; `eprintln` on+/// host builds and tests so the selection stays visible off-device.+fn log_backend(msg: &str) {+ #[cfg(target_os = "android")]+ unsafe {+ use std::ffi::CString;+ use std::os::raw::{c_char, c_int};+ extern "C" {+ fn __android_log_print(prio: c_int, tag: *const c_char, fmt: *const c_char, ...) -> c_int;+ }+ // ANDROID_LOG_INFO = 4.+ if let (Ok(tag), Ok(line), Ok(fmt)) = (+ CString::new("kart_engine"),+ CString::new(format!("backend: {msg}")),+ CString::new("%s"),+ ) {+ __android_log_print(4, tag.as_ptr(), fmt.as_ptr(), line.as_ptr());+ }+ }+ #[cfg(not(target_os = "android"))]+ {+ eprintln!("kart_engine backend: {msg}");+ }+}++/// Resize: Vulkan recreates the swapchain at the new size; GLES re-creates+/// the EGL surface on the same context (GL objects survive, no re-upload).+/// If recreation fails the renderer is dropped and the next frame re-creates+/// it (placeholder covers). pub fn resize_renderer(width: i32, height: i32) { with_engine(|state| { state.width = width.max(1) as u32;@@ -201,6 +266,20 @@ pub fn resize_renderer(width: i32, height: i32) { return; } };+ match &mut r {+ Renderer::Gles(g) => {+ match unsafe { g.resize(window, state.width, state.height) } {+ Ok(()) => {+ state.renderer = Some(r);+ }+ Err(_) => {+ unsafe { r.destroy() };+ }+ }+ return;+ }+ Renderer::Vulkan(_) => {}+ } let ctx = match unsafe { VulkanContext::new(window, width, height) } { Ok(c) => c, Err(_) => {@@ -210,6 +289,7 @@ pub fn resize_renderer(width: i32, height: i32) { }; match unsafe { KartRenderer::new(ctx, state.width, state.height) } { Ok(fresh) => {+ let mut fresh = Renderer::Vulkan(fresh); let mesh = mesh::build_track_mesh(); state.track_count = mesh.len(); unsafe { fresh.upload_track(&mesh) };@@ -247,8 +327,8 @@ pub fn destroy_engine() { if let Some(mut state) = guard.take() { if let Some(mut r) = state.renderer.take() { unsafe { r.destroy() };- // The context owns instance/device; release them too.- r.ctx.destroy();+ // The context owns instance/device; release them too (GLES: no-op).+ r.destroy_context(); } if let Some(win) = state.window_ptr.take() { unsafe { crate::vulkan::context::ANativeWindow_release(win) };@@ -306,9 +386,9 @@ pub fn tick_and_render() { let view_proj = view_proj_for( cam_pos, look,- renderer.width,- renderer.height,- renderer.swap.pre_rotation(),+ renderer.width(),+ renderer.height(),+ renderer.pre_rotation(), ); let track_count = s.track_count; let _ = unsafe { renderer.draw(view_proj, cam_pos, track_count, &dynamic) };
games/kart/src/main/rust/src/gles/buffers.rs
diff --git a/games/kart/src/main/rust/src/gles/buffers.rs b/games/kart/src/main/rust/src/gles/buffers.rsnew file mode 100644index 0000000000..6e482f542f--- /dev/null+++ b/games/kart/src/main/rust/src/gles/buffers.rs@@ -0,0 +1,130 @@+//! VAO/VBO pairs: the static track upload plus the per-frame dynamic mesh.+//!+//! Mirrors `vulkan/buffers.rs` through GL instead of `ash`: `pos@0 (3f) ++//! color@1 (3f)`, stride 24 (the [`crate::mesh::KartVertex`] layout),+//! `STATIC_DRAW` storage sized to the caps, `DrawArrays(TRIANGLES)`.+//! `upload_track` re-sizes the store once per race; `upload_dynamic` re-sizes+//! every frame from the race transforms. No mesh budget increase (the sweep is+//! already modest for the 2 GB box).++use crate::gles::renderer::{DYNAMIC_VERT_CAP, TRACK_VERT_CAP};+use crate::mesh::KartVertex;+use glow::HasContext as _;+use std::mem;++/// One VAO + VBO pair: vertex layout bound once, store re-sized per upload.+pub struct MeshBuffer {+ /// Vertex array (layout recorded at creation).+ vao: glow::VertexArray,+ /// Vertex buffer (store re-sized on every upload).+ vbo: glow::Buffer,+ /// Vertices in the last upload (the draw count).+ pub count: usize,+}++impl MeshBuffer {+ /// Create VAO+VBO and record the `pos@0`/`color@1` layout (stride 24).+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn new(gl: &glow::Context) -> Result<Self, String> {+ let vao = unsafe { gl.create_vertex_array() }+ .map_err(|e| format!("glGenVertexArrays: {e}"))?;+ let vbo = unsafe { gl.create_buffer() }.map_err(|e| format!("glGenBuffers: {e}"))?;+ unsafe {+ gl.bind_vertex_array(Some(vao));+ gl.bind_buffer(glow::ARRAY_BUFFER, Some(vbo));+ // pos@0 (3f, offset 0) + color@1 (3f, offset 12), stride 24.+ gl.enable_vertex_attrib_array(0);+ gl.vertex_attrib_pointer_f32(0, 3, glow::FLOAT, false, 24, 0);+ gl.enable_vertex_attrib_array(1);+ gl.vertex_attrib_pointer_f32(1, 3, glow::FLOAT, false, 24, 12);+ gl.bind_buffer(glow::ARRAY_BUFFER, None);+ gl.bind_vertex_array(None);+ }+ Ok(Self { vao, vbo, count: 0 })+ }++ /// Re-size the store and upload `mesh` (capped by the caller).+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn upload(&mut self, gl: &glow::Context, mesh: &[KartVertex]) {+ unsafe {+ gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.vbo));+ gl.buffer_data_u8_slice(+ glow::ARRAY_BUFFER,+ bytes_of(mesh),+ glow::STATIC_DRAW,+ );+ gl.bind_buffer(glow::ARRAY_BUFFER, None);+ }+ self.count = mesh.len();+ }++ /// Draw the last upload as `TRIANGLES`.+ ///+ /// # Safety+ /// EGL context must be current; the program must be in use.+ pub unsafe fn draw(&self, gl: &glow::Context) {+ if self.count == 0 {+ return;+ }+ unsafe {+ gl.bind_vertex_array(Some(self.vao));+ gl.draw_arrays(glow::TRIANGLES, 0, self.count as i32);+ gl.bind_vertex_array(None);+ }+ }++ /// Free VAO + VBO.+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn destroy(&mut self, gl: &glow::Context) {+ unsafe {+ gl.delete_buffer(self.vbo);+ gl.delete_vertex_array(self.vao);+ }+ self.count = 0;+ }+}++/// Byte view of a vertex slice (stride-24 `KartVertex`, `repr(C)`).+fn bytes_of(mesh: &[KartVertex]) -> &[u8] {+ if mesh.is_empty() {+ return &[];+ }+ unsafe {+ std::slice::from_raw_parts(+ mesh.as_ptr() as *const u8,+ mesh.len() * mem::size_of::<KartVertex>(),+ )+ }+}++/// Upload the static track mesh (once per race; capped at `TRACK_VERT_CAP`).+///+/// # Safety+/// EGL context must be current on this thread.+pub unsafe fn upload_track_mesh(+ gl: &glow::Context,+ buf: &mut MeshBuffer,+ mesh: &[KartVertex],+) {+ let n = mesh.len().min(TRACK_VERT_CAP);+ unsafe { buf.upload(gl, &mesh[..n]) };+}++/// Upload the per-frame dynamic mesh (capped at `DYNAMIC_VERT_CAP`).+///+/// # Safety+/// EGL context must be current on this thread.+pub unsafe fn upload_dynamic_mesh(+ gl: &glow::Context,+ buf: &mut MeshBuffer,+ mesh: &[KartVertex],+) {+ let n = mesh.len().min(DYNAMIC_VERT_CAP);+ unsafe { buf.upload(gl, &mesh[..n]) };+}
games/kart/src/main/rust/src/gles/egl.rs
diff --git a/games/kart/src/main/rust/src/gles/egl.rs b/games/kart/src/main/rust/src/gles/egl.rsnew file mode 100644index 0000000000..472498c420--- /dev/null+++ b/games/kart/src/main/rust/src/gles/egl.rs@@ -0,0 +1,203 @@+//! EGL display, surface, and context: the RAII foundation glow draws through.+//!+//! Lifecycle: `get_display(DEFAULT_DISPLAY)` → `initialize` → `choose_config`+//! (RGBA8888 + depth 24 + ES3 renderable + window surface) →+//! `create_window_surface` on the engine-owned `ANativeWindow` →+//! `create_context` (client version 3) → `make_current` + `swap_interval(1)`.+//! ES 3.0 only (no 3.1 compute) for the Mali-G31. [`Egl::resize`] re-creates+//! the surface on the same display/config/context; [`Egl::teardown`] (also run+//! from `Drop`) unbinds, destroys surface/context, then terminates the+//! display. Never touches the `ANativeWindow` lifetime: the engine owns+//! acquire/release, exactly as on the Vulkan path.+//!+//! `khronos-egl` is used through its `dynamic` backend (`dlopen("libEGL.so")`+//! at runtime): the `static` backend links EGL at compile time via pkg-config,+//! which fails for Android cross-compiles and on hosts without system EGL.++use khronos_egl as egl;+use std::os::raw::c_void;++/// EGL API instance: dynamically loaded `libEGL.so` (EGL 1.4 entry points —+/// everything kart needs is 1.0-era core).+type Api = egl::DynamicInstance<egl::EGL1_4>;++/// Config attributes: 8-bit RGBA, 24-bit depth, ES3-renderable window surface.+const CONFIG_ATTRIBS: &[egl::Int] = &[+ egl::RED_SIZE,+ 8,+ egl::GREEN_SIZE,+ 8,+ egl::BLUE_SIZE,+ 8,+ egl::ALPHA_SIZE,+ 8,+ egl::DEPTH_SIZE,+ 24,+ egl::RENDERABLE_TYPE,+ egl::OPENGL_ES3_BIT,+ egl::SURFACE_TYPE,+ egl::WINDOW_BIT,+ egl::NONE,+];++/// Context attributes: OpenGL ES client version 3.+const CONTEXT_ATTRIBS: &[egl::Int] = &[egl::CONTEXT_CLIENT_VERSION, 3, egl::NONE];++/// RAII EGL state. Tear down explicitly with [`Self::teardown`] (called from+/// the renderer's `destroy` on the render thread); `Drop` re-runs it+/// idempotently in case destroy was skipped.+pub struct Egl {+ /// Dynamically loaded EGL entry points.+ api: Api,+ /// The default display (terminated on teardown).+ display: egl::Display,+ /// Chosen ES3 window config.+ config: egl::Config,+ /// Window surface (recreated on resize).+ surface: Option<egl::Surface>,+ /// ES 3.0 context.+ context: Option<egl::Context>,+ /// False once [`Self::teardown`] ran (idempotence guard for `Drop`).+ terminated: bool,+}++impl Egl {+ /// Bring up display → config → surface → context → current on `window`.+ ///+ /// # Safety+ /// `window` must be a live `ANativeWindow`; ownership stays with the+ /// caller (the engine releases it, as on the Vulkan path).+ pub unsafe fn new(+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<Self, String> {+ let api =+ unsafe { Api::load_required() }.map_err(|e| format!("load libEGL: {e:?}"))?;+ let display = unsafe { api.get_display(egl::DEFAULT_DISPLAY) }+ .ok_or_else(|| "eglGetDisplay failed".to_string())?;+ api.initialize(display)+ .map_err(|e| format!("eglInitialize: {e:?}"))?;+ let mut configs = Vec::with_capacity(1);+ api.choose_config(display, CONFIG_ATTRIBS, &mut configs)+ .map_err(|e| format!("eglChooseConfig: {e:?}"))?;+ let config = configs+ .first()+ .copied()+ .ok_or_else(|| "no ES3 window EGL config".to_string())?;+ let mut egl = Self {+ api,+ display,+ config,+ surface: None,+ context: None,+ terminated: false,+ };+ unsafe { egl.create_surface(window)? };+ let context = egl+ .api+ .create_context(display, config, None, CONTEXT_ATTRIBS)+ .map_err(|e| format!("eglCreateContext (ES3): {e:?}"))?;+ egl.context = Some(context);+ egl.make_current()?;+ egl.api+ .swap_interval(display, 1)+ .map_err(|e| format!("eglSwapInterval: {e:?}"))?;+ Ok(egl)+ }++ /// Re-create the window surface on the same display/config/context+ /// (rotation/resize). GL objects survive — no re-upload needed.+ ///+ /// # Safety+ /// `window` must be the live adopted `ANativeWindow`; render thread only.+ pub unsafe fn resize(+ &mut self,+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<(), String> {+ if let Some(surface) = self.surface.take() {+ let _ = self.unbind();+ let _ = self.api.destroy_surface(self.display, surface);+ }+ unsafe { self.create_surface(window)? };+ self.make_current()?;+ self.api+ .swap_interval(self.display, 1)+ .map_err(|e| format!("eglSwapInterval: {e:?}"))?;+ Ok(())+ }++ /// Present the current back buffer. No fences — this is the present.+ pub fn swap_buffers(&self) -> Result<(), String> {+ match self.surface {+ Some(surface) => self+ .api+ .swap_buffers(self.display, surface)+ .map_err(|e| format!("eglSwapBuffers: {e:?}")),+ None => Err("eglSwapBuffers: no surface".into()),+ }+ }++ /// Resolve a GL entry point for the glow loader (null when absent — glow+ /// treats a null loader result as a missing function).+ pub fn proc_address(&self, name: &str) -> *const c_void {+ self.api+ .get_proc_address(name)+ .map(|f| f as *const c_void)+ .unwrap_or(std::ptr::null())+ }++ /// Unbind, destroy surface/context, terminate the display. Idempotent.+ pub fn teardown(&mut self) {+ if self.terminated {+ return;+ }+ self.terminated = true;+ if self.surface.is_some() || self.context.is_some() {+ let _ = self.unbind();+ }+ if let Some(surface) = self.surface.take() {+ let _ = self.api.destroy_surface(self.display, surface);+ }+ if let Some(context) = self.context.take() {+ let _ = self.api.destroy_context(self.display, context);+ }+ let _ = self.api.terminate(self.display);+ }++ /// Create the window surface on the adopted window.+ unsafe fn create_surface(+ &mut self,+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<(), String> {+ let surface = unsafe {+ self.api.create_window_surface(+ self.display,+ self.config,+ window as egl::NativeWindowType,+ None,+ )+ }+ .map_err(|e| format!("eglCreateWindowSurface: {e:?}"))?;+ self.surface = Some(surface);+ Ok(())+ }++ /// Bind surface + context to this thread.+ fn make_current(&self) -> Result<(), String> {+ self.api+ .make_current(self.display, self.surface, self.surface, self.context)+ .map_err(|e| format!("eglMakeCurrent: {e:?}"))+ }++ /// Unbind everything from this thread.+ fn unbind(&self) -> Result<(), String> {+ self.api+ .make_current(self.display, None, None, None)+ .map_err(|e| format!("eglMakeCurrent (unbind): {e:?}"))+ }+}++impl Drop for Egl {+ fn drop(&mut self) {+ self.teardown();+ }+}
games/kart/src/main/rust/src/gles/mod.rs
diff --git a/games/kart/src/main/rust/src/gles/mod.rs b/games/kart/src/main/rust/src/gles/mod.rsnew file mode 100644index 0000000000..7300bdfb23--- /dev/null+++ b/games/kart/src/main/rust/src/gles/mod.rs@@ -0,0 +1,12 @@+//! GLES 3.0 fallback renderer for Vulkan-less devices (ONN 4K box, Mali-G31).+//!+//! Same layering as [`crate::vulkan`]: `egl` owns the display/surface/context,+//! `shaders` compiles the GLSL ES program, `buffers` uploads the+//! [`crate::mesh`] builders verbatim, `renderer` draws + presents. Runtime+//! selection lives in [`crate::engine`]: try Vulkan, fall back to GLES, fail+//! only if both fail.++pub mod buffers;+pub mod egl;+pub mod renderer;+pub mod shaders;
games/kart/src/main/rust/src/gles/renderer.rs
diff --git a/games/kart/src/main/rust/src/gles/renderer.rs b/games/kart/src/main/rust/src/gles/renderer.rsnew file mode 100644index 0000000000..7840e6dfcf--- /dev/null+++ b/games/kart/src/main/rust/src/gles/renderer.rs@@ -0,0 +1,220 @@+//! Frame renderer: EGL surface, glow program, VAO/VBO uploads, draw + present.+//!+//! The GLES twin of [`crate::vulkan::renderer::KartRenderer`]: `new` brings+//! up EGL, loads glow from `eglGetProcAddress`, compiles/links the program,+//! creates the track + dynamic [`MeshBuffer`]s and uploads the static mesh+//! skeleton, sets viewport + `clear_color(SKY)` + depth `LESS` + cull off;+//! `draw` clears, sets the three uniforms 1:1 for+//! `KartUbo{view_proj,sun_dir,cam_pos}`, draws both meshes, then+//! `swap_buffers` (no fences — the swap is the present). `resize` re-creates+//! the EGL surface on the same context (GL objects survive); `destroy` frees+//! GL objects then tears down EGL. The track mesh uploads once per race via+//! [`Self::upload_track`], exactly like Vulkan.++use crate::gles::buffers::{self, MeshBuffer};+use crate::gles::egl::Egl;+use crate::gles::shaders::{self, U_CAM_POS, U_SUN_DIR, U_VIEW_PROJ};+use crate::mesh::KartVertex;+use glow::HasContext as _;++/// Static track mesh budget: the oval sweep is ~30k verts; 64k leaves margin.+pub const TRACK_VERT_CAP: usize = 65_536;+/// Dynamic mesh budget per frame: 8 karts (~160 verts each) + boxes + shells.+pub const DYNAMIC_VERT_CAP: usize = 8_192;++/// Sky clear color, shared with the Vulkan clear value and `kart_gles.frag`.+pub const SKY: [f32; 3] = [0.45, 0.68, 0.94];++/// Fixed sun direction (normalized on upload — mirrors the Vulkan UBO fill).+const SUN_DIR: [f32; 3] = [0.35, -1.0, 0.45];++/// Everything needed to draw one GLES frame.+pub struct GlesRenderer {+ /// EGL display/surface/context (RAII; owns the presentation surface).+ egl: Egl,+ /// glow context (function pointers loaded via `eglGetProcAddress`).+ gl: glow::Context,+ /// Linked `kart_gles` program.+ program: glow::Program,+ /// `uViewProj` uniform location.+ u_view_proj: glow::UniformLocation,+ /// `uSunDir` uniform location.+ u_sun_dir: glow::UniformLocation,+ /// `uCamPos` uniform location.+ u_cam_pos: glow::UniformLocation,+ /// Static track VAO/VBO (re-uploaded per race).+ track: MeshBuffer,+ /// Per-frame dynamic VAO/VBO (karts, shells, boxes).+ dynamic: MeshBuffer,+ /// Current surface width.+ pub width: u32,+ /// Current surface height.+ pub height: u32,+}++impl GlesRenderer {+ /// Create from a live window at `width` x `height`. Fails cleanly (the+ /// caller logs and keeps the placeholder) rather than panicking.+ ///+ /// # Safety+ /// `window` must be a live `ANativeWindow` adopted from the JNI surface+ /// (the caller acquired it via `ANativeWindow_acquire`); ownership moves+ /// to the engine, exactly as on the Vulkan path.+ pub unsafe fn new(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: u32,+ height: u32,+ ) -> Result<Self, String> {+ let egl = unsafe { Egl::new(window)? };+ let gl = unsafe {+ glow::Context::from_loader_function(|name| egl.proc_address(name) as *const _)+ };+ let program = unsafe { shaders::compile_program(&gl)? };+ let (u_view_proj, u_sun_dir, u_cam_pos) = unsafe {+ let view = gl+ .get_uniform_location(program, U_VIEW_PROJ)+ .ok_or_else(|| format!("missing uniform {U_VIEW_PROJ}"))?;+ let sun = gl+ .get_uniform_location(program, U_SUN_DIR)+ .ok_or_else(|| format!("missing uniform {U_SUN_DIR}"))?;+ let cam = gl+ .get_uniform_location(program, U_CAM_POS)+ .ok_or_else(|| format!("missing uniform {U_CAM_POS}"))?;+ (view, sun, cam)+ };+ let track = unsafe { MeshBuffer::new(&gl)? };+ let dynamic = unsafe { MeshBuffer::new(&gl)? };+ let renderer = Self {+ egl,+ gl,+ program,+ u_view_proj,+ u_sun_dir,+ u_cam_pos,+ track,+ dynamic,+ width: width.max(1),+ height: height.max(1),+ };+ unsafe { renderer.apply_state() };+ Ok(renderer)+ }++ /// Upload the static track mesh (once per race; capped at the budget).+ ///+ /// # Safety+ /// Must be called on the render thread with the EGL context current.+ pub unsafe fn upload_track(&mut self, mesh: &[KartVertex]) {+ unsafe { buffers::upload_track_mesh(&self.gl, &mut self.track, mesh) };+ }++ /// Draw one frame: clear, set the three uniforms, draw static + dynamic,+ /// `eglSwapBuffers`.+ /// `track_count` is informational (the count lives in the track VBO, as on+ /// Vulkan where it is passed per frame alongside the buffer).+ ///+ /// # Safety+ /// Must be called on the render thread with the EGL context current.+ pub unsafe fn draw(+ &mut self,+ view_proj: [[f32; 4]; 4],+ cam_pos: [f32; 3],+ track_count: usize,+ dynamic: &[KartVertex],+ ) -> Result<(), String> {+ let _ = track_count;+ unsafe { buffers::upload_dynamic_mesh(&self.gl, &mut self.dynamic, dynamic) };+ let flat = flatten(&view_proj);+ let sun = normalize(SUN_DIR);+ unsafe {+ self.gl+ .clear_color(SKY[0], SKY[1], SKY[2], 1.0);+ self.gl.clear(glow::COLOR_BUFFER_BIT | glow::DEPTH_BUFFER_BIT);+ self.gl.use_program(Some(self.program));+ self.gl+ .uniform_matrix_4_f32_slice(Some(&self.u_view_proj), false, &flat);+ self.gl+ .uniform_3_f32(Some(&self.u_sun_dir), sun[0], sun[1], sun[2]);+ self.gl+ .uniform_3_f32(Some(&self.u_cam_pos), cam_pos[0], cam_pos[1], cam_pos[2]);+ }+ unsafe {+ self.track.draw(&self.gl);+ self.dynamic.draw(&self.gl);+ self.gl.use_program(None);+ }+ self.egl.swap_buffers()+ }++ /// Re-create the EGL surface at the new size on the same context (GL+ /// objects survive, so no re-upload). On failure the caller drops the+ /// renderer and the placeholder covers, as on Vulkan.+ ///+ /// # Safety+ /// `window` must be the live adopted `ANativeWindow`; render thread only.+ pub unsafe fn resize(+ &mut self,+ window: *mut crate::vulkan::context::ANativeWindow,+ width: u32,+ height: u32,+ ) -> Result<(), String> {+ self.width = width.max(1);+ self.height = height.max(1);+ unsafe { self.egl.resize(window)? };+ unsafe { self.apply_state() };+ Ok(())+ }++ /// Surface pre-rotation: GLES has no swapchain `currentTransform`, so the+ /// identity (no aspect swap, no Z rotation) — the box is landscape-native.+ pub fn pre_rotation(&self) -> (bool, f32) {+ (false, 0.0)+ }++ /// Free program + VAO/VBOs, then tear down EGL. The engine releases the+ /// window itself.+ ///+ /// # Safety+ /// Must be called on the render thread that owns the EGL context.+ pub unsafe fn destroy(&mut self) {+ unsafe {+ self.gl.use_program(None);+ self.dynamic.destroy(&self.gl);+ self.track.destroy(&self.gl);+ self.gl.delete_program(self.program);+ }+ self.egl.teardown();+ }++ /// Viewport + fixed GL state: depth test `LESS` (matches the Vulkan+ /// pipeline), cull off (matches `CULL_NONE` — winding is as authored+ /// since the GLES shaders carry no Y flip).+ unsafe fn apply_state(&self) {+ unsafe {+ self.gl+ .viewport(0, 0, self.width as i32, self.height as i32);+ self.gl.enable(glow::DEPTH_TEST);+ self.gl.depth_func(glow::LESS);+ self.gl.disable(glow::CULL_FACE);+ }+ }+}++/// Column-major flatten for `uniform_matrix_4_f32_slice(transpose=false)`:+/// the `[[f32; 4]; 4]` from [`crate::engine::view_proj_for`] is already+/// `to_cols_array_2d`, so concatenation preserves column order.+fn flatten(m: &[[f32; 4]; 4]) -> [f32; 16] {+ let mut out = [0.0f32; 16];+ for (col, column) in m.iter().enumerate() {+ for (row, v) in column.iter().enumerate() {+ out[col * 4 + row] = *v;+ }+ }+ out+}++/// Normalize the fixed sun direction (mirrors the Vulkan UBO fill).+fn normalize(v: [f32; 3]) -> [f32; 3] {+ let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);+ [v[0] / len, v[1] / len, v[2] / len]+}
games/kart/src/main/rust/src/gles/shaders.rs
diff --git a/games/kart/src/main/rust/src/gles/shaders.rs b/games/kart/src/main/rust/src/gles/shaders.rsnew file mode 100644index 0000000000..d232083300--- /dev/null+++ b/games/kart/src/main/rust/src/gles/shaders.rs@@ -0,0 +1,88 @@+//! GLSL ES program: compile + link the `kart_gles` shader twins.+//!+//! The Vulkan SPIR-V pair gains GLSL ES 3.0 sources (built untouched by+//! `build.rs`, which only knows `kart.vert`/`kart.frag`); the UBO becomes+//! three uniforms (`uViewProj` / `uSunDir` / `uCamPos`). Every failure+//! surfaces the driver info log so logcat names the bad line, not just+//! "link failed".++use glow::HasContext as _;++/// Vertex shader: `#version 300 es`, Vulkan `clip.y` flip removed.+pub const VERT_SRC: &str = include_str!("../../shaders/kart_gles.vert");+/// Fragment shader: `#version 300 es`, same `ndl` + `exp` fog `0.0045`.+pub const FRAG_SRC: &str = include_str!("../../shaders/kart_gles.frag");++/// View-projection uniform (mirrors the Vulkan UBO's `viewProj`).+pub const U_VIEW_PROJ: &str = "uViewProj";+/// Fixed sun direction (mirrors the Vulkan UBO's `sunDir`).+pub const U_SUN_DIR: &str = "uSunDir";+/// Chase-cam position, the fog origin (mirrors the Vulkan UBO's `camPos`).+pub const U_CAM_POS: &str = "uCamPos";++/// Compile `VERT_SRC` + `FRAG_SRC`, link, return the program. On any failure+/// the returned string carries the shader/program info log from the driver.+pub unsafe fn compile_program(gl: &glow::Context) -> Result<glow::Program, String> {+ let vert = unsafe { compile_stage(gl, glow::VERTEX_SHADER, "kart_gles.vert", VERT_SRC)? };+ let frag = unsafe { compile_stage(gl, glow::FRAGMENT_SHADER, "kart_gles.frag", FRAG_SRC)? };+ let program = unsafe { gl.create_program() }.map_err(|e| format!("glCreateProgram: {e}"))?;+ unsafe {+ gl.attach_shader(program, vert);+ gl.attach_shader(program, frag);+ gl.link_program(program);+ gl.delete_shader(vert);+ gl.delete_shader(frag);+ }+ if !unsafe { gl.get_program_link_status(program) } {+ let log = unsafe { gl.get_program_info_log(program) };+ unsafe { gl.delete_program(program) };+ return Err(format!("glLinkProgram kart_gles: {log}"));+ }+ Ok(program)+}++/// Compile one shader stage; the error carries the driver's info log.+unsafe fn compile_stage(+ gl: &glow::Context,+ stage: u32,+ name: &str,+ src: &str,+) -> Result<glow::Shader, String> {+ let shader = unsafe { gl.create_shader(stage) }+ .map_err(|e| format!("glCreateShader {name}: {e}"))?;+ unsafe {+ gl.shader_source(shader, src);+ gl.compile_shader(shader);+ }+ if !unsafe { gl.get_shader_compile_status(shader) } {+ let log = unsafe { gl.get_shader_info_log(shader) };+ unsafe { gl.delete_shader(shader) };+ return Err(format!("glCompileShader {name}: {log}"));+ }+ Ok(shader)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn gles_shaders_are_300_es_with_matching_uniforms() {+ for src in [VERT_SRC, FRAG_SRC] {+ assert!(+ src.trim_start().starts_with("#version 300 es"),+ "missing ES 3.0 preamble"+ );+ }+ assert!(+ !VERT_SRC.contains("clip.y = -clip.y"),+ "Vulkan Y flip must not ship on GLES"+ );+ for uniform in [U_VIEW_PROJ, U_SUN_DIR, U_CAM_POS] {+ assert!(VERT_SRC.contains(uniform), "vert missing {uniform}");+ }+ for uniform in [U_SUN_DIR, U_CAM_POS] {+ assert!(FRAG_SRC.contains(uniform), "frag missing {uniform}");+ }+ }+}
games/kart/src/main/rust/src/lib.rs
diff --git a/games/kart/src/main/rust/src/lib.rs b/games/kart/src/main/rust/src/lib.rsindex 1183f9e185..fbc3b23843 100644--- a/games/kart/src/main/rust/src/lib.rs+++ b/games/kart/src/main/rust/src/lib.rs@@ -6,10 +6,12 @@ //! native methods receive `EnvUnowned` and adapt via `with_env`. pub mod engine;+pub mod gles; pub mod items; pub mod mesh; pub mod physics; pub mod race;+pub mod renderer; pub mod track; pub mod vulkan;
games/kart/src/main/rust/src/renderer.rs
diff --git a/games/kart/src/main/rust/src/renderer.rs b/games/kart/src/main/rust/src/renderer.rsnew file mode 100644index 0000000000..4798a90fa8--- /dev/null+++ b/games/kart/src/main/rust/src/renderer.rs@@ -0,0 +1,95 @@+//! Renderer seam: which GPU backend drew the frame.+//!+//! Vulkan wins where drivers exist (64-bit phones); GLES covers Vulkan-less+//! boxes (ONN 4K, Mali-G31). Split out of `engine.rs` along module lines so+//! neither file trips the 500-line Rust gate. `engine.rs` owns the race, the+//! lifecycle, and the tick; this module owns the backend dispatch.++use crate::gles::renderer::GlesRenderer;+use crate::mesh::KartVertex;+use crate::vulkan::renderer::KartRenderer;++/// Which GPU backend drew the frame. `create_renderer` tries Vulkan first,+/// falls back to GLES, and fails only when both fail.+pub enum Renderer {+ /// Vulkan path (`ash` loaded): instance + swapchain + pipeline.+ Vulkan(KartRenderer),+ /// GLES 3.0 path (`glow` + `khronos-egl`): EGL surface + GL program.+ Gles(GlesRenderer),+}++impl Renderer {+ /// Current surface width (either backend).+ pub fn width(&self) -> u32 {+ match self {+ Self::Vulkan(r) => r.width,+ Self::Gles(r) => r.width,+ }+ }++ /// Current surface height (either backend).+ pub fn height(&self) -> u32 {+ match self {+ Self::Vulkan(r) => r.height,+ Self::Gles(r) => r.height,+ }+ }++ /// Surface pre-rotation for [`crate::engine::view_proj_for`]: the+ /// swapchain's `currentTransform` on Vulkan, identity on GLES+ /// (landscape-native box).+ pub fn pre_rotation(&self) -> (bool, f32) {+ match self {+ Self::Vulkan(r) => r.swap.pre_rotation(),+ Self::Gles(r) => r.pre_rotation(),+ }+ }++ /// Upload the static track mesh (once per race; capped per backend).+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn upload_track(&mut self, mesh: &[KartVertex]) {+ match self {+ Self::Vulkan(r) => unsafe { r.upload_track(mesh) },+ Self::Gles(r) => unsafe { r.upload_track(mesh) },+ }+ }++ /// Draw one frame. `track_count` is the vertex count from the last+ /// [`Self::upload_track`].+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn draw(+ &mut self,+ view_proj: [[f32; 4]; 4],+ cam_pos: [f32; 3],+ track_count: usize,+ dynamic: &[KartVertex],+ ) -> Result<(), String> {+ match self {+ Self::Vulkan(r) => unsafe { r.draw(view_proj, cam_pos, track_count, dynamic) },+ Self::Gles(r) => unsafe { r.draw(view_proj, cam_pos, track_count, dynamic) },+ }+ }++ /// Free everything except the window (the engine releases that itself).+ ///+ /// # Safety+ /// Must be called on the render thread that owns the backend's context.+ pub unsafe fn destroy(&mut self) {+ match self {+ Self::Vulkan(r) => unsafe { r.destroy() },+ Self::Gles(r) => unsafe { r.destroy() },+ }+ }++ /// Tear down the Vulkan instance + device. No-op on GLES (the EGL+ /// display/context teardown already happened in [`Self::destroy`]).+ pub fn destroy_context(&mut self) {+ if let Self::Vulkan(r) = self {+ r.ctx.destroy();+ }+ }+}