---
title: "Rust + raylib handheld performance reference (Mali-G31 / Panfrost)"
summary: "Measured 60 FPS hardware budgets, raylib API traps, Panfrost sync and FBO rules, 3D optimization techniques, OS I/O spike fixes, and profiling triage for Gizlet OS handhelds (R36S / R36MAX2)."
category: agents
tags: ["raylib","rust","performance","mali-g31","agents"]
language: en
published: 2026-12-06
updated: 2026-12-06
url: https://gizlet.io/blog/agent-raylib-performance
---

This reference answers how to hit and keep locked 60 FPS (≤ 16.67 ms/frame) in Rust + raylib (and `gizlet/rayui`) 2D and 3D apps on Gizlet OS RK3326 handhelds (R36S 640×480 and R36MAX2 1024×768).

# 1. Hardware envelope and dual-pipeline budgets

Both R36S and R36MAX2 run Rockchip RK3326 (4× Cortex-A35 @ 1.5 GHz), Mali-G31 MP2 GPU with the Panfrost OpenGL ES 3.0 driver, low-bandwidth DDR3, and direct KMS/DRM output (no compositor) via Gizlet OS Runtime 1.

- **2D dynamic `rlgl` vertex cliff:** **≤ 3,500 vertices/frame** (slope ≈ 4.5 µs/vertex; crossing ~3,700 vertices drops below 16.67 ms). Cutting total vertices and sync flushes beats cutting texture switches—on Mali-G31, 77 draw calls with 2,552 vertices holds 60.0 FPS while 34 draw calls with 10,692 vertices drops to 21.6 FPS.
- **3D static indexed VBO budget:** **≤ 22,000 triangles and ≤ 35 draw calls/frame** rendered into a **448×336** (4:3, 16-px aligned) opaque offscreen FBO (~0.4–0.5 ms per 1,000 tris; ~0.12–0.15 ms CPU per draw call).
- **KMS render batch:** Always configure `rlLoadRenderBatch(24, 4096)` on KMS. Raylib's default 1-buffer batch stalls 30–86 ms on every mid-frame flush.
- **No MSAA:** Never enable `FLAG_MSAA_4X_HINT` on KMS (excessive bandwidth or context creation failure); use 2× SDF textures/shaders for antialiasing.

# 2. 2D geometry, overdraw and font baking traps

- **`DrawRectangleRounded` and multi-layer shadows (130–1,500 v/card → 8–60 v):** Expands corner triangle strips; 5-layer shadows reach ~1,500 v per card, and `RL_TRIANGLES` breaks `RL_QUADS` batching. Fix: prebake a 2× SDF `RoundedMask` (8 v) for fixed-size cards, or build a **128×128 RGBA8 4-quadrant `ShapeAtlas`** (64 KB: antialiased disc with 2×2 white center, 9-slice hollow 8-quad Gaussian shadow = 32 v, small radial glow, 5-point SDF star = 4 v) so all UI primitives share one `RL_QUADS` batch.
- **Modal occlusion culling & two-pass soft keyboards:** Drawing 45 keys alternating background/glyph triggers ~90 texture switches, and drawing obscured cards plus a full-screen scrim behind an opaque modal wastes ~540k pixels of overdraw. Draw all key backgrounds in pass 1, then glyphs grouped by font size in pass 2 (90 → 3 draws); skip fully occluded items behind settled opaque modals and draw the scrim as 4 border strips around the modal cutout.
- **`DrawLineEx`, `DrawSplineLinear` and round caps (6 v/seg, 294 v with caps):** `DrawLineEx` uses `RL_TRIANGLES` and adding `DrawCircleV` caps adds 2×144 v. Emit miter-clamped (`cos.max(0.4)`) 4-vertex `RL_QUADS` using the `ShapeAtlas` white texel, adding 4 v `ShapeAtlas` disc caps only when `thick >= 2.0 && thick_px >= 3.5`.
- **`DrawRing`, `DrawCircleV` and large radial glows:** `DrawCircleV` hard-codes 36 segments = 144 v/circle. Use a single-batch SDF ring shader (4 v/ring via `dFdx`/`dFdy`, skipping `r < 1.5`) for hollow rings, `ShapeAtlas` quads (4 v) for circles and glows with `r <= 200 px`, and an **untextured 16-segment `RL_QUADS` vertex-colored fan (64 v, zero texture fetches)** for large background glows (`r > 200 px`), because large textured quads saturate Mali-G31's bilinear texture bandwidth.
- **`DrawRectangleRoundedLinesEx` `segments < 4` trap (`rshapes.c:1194`):** Passing `segments < 4` triggers automatic subdivision (`SMOOTH_CIRCLE_ERROR_RATE = 0.5`), exploding large corners to 12–20+ segments (400+ v/box). Always clamp `segments >= 4` (e.g. `((r_px * 0.25).ceil() as i32).clamp(4, 5)`).
- **Dot matrices, QR codes, icons and dense curves:** Prebake QR codes (`TEXTURE_FILTER_POINT`) and tiled dot backgrounds (power-of-two + `TEXTURE_WRAP_REPEAT`) to a single 4 v texture; simplify static dense curves once at load time with closed Ramer-Douglas-Peucker (tolerance 0.20–0.25 px, cutting 50%–95% of vertices).
- **Font atlas rebuild spikes (50–380 ms) and outlined text:** Changing font size during animations re-rasterizes the atlas every frame; encountering any unseeded CJK/Phosphor codepoint clears and rebuilds all font sizes. Call `seed_text()` with all known CJK and Phosphor codepoints at startup, animate score popups via `rlPushMatrix`/`rlScalef` instead of changing font size, quantize DPI to 0.1 steps (`1.6` at 1024×768 instead of rounding to `2.0`, saving 36% VRAM), and prebake heavy static/outlined titles and compact HUD strips (e.g. 640×56, never full-screen 1024×768 FBOs) converting premultiplied FBO alpha to straight alpha (CPU un-premultiply + 1 px bleed) to avoid dark fringes without extra blend flushes.

# 3. Panfrost sync stalls and offscreen FBO discipline

- **Golden rule: calling `glBufferSubData` on a VBO the GPU may still be reading causes a synchronous CPU stall (20–86 ms).**
- **2D dynamic batches:** Use `rlLoadRenderBatch(24, 4096)` on KMS, deduplicate consecutive identical `BeginScissorMode` regions (20–30 flushes → 1), and reuse cached layout when `!changed`.
- **3D repeated props:** Never CPU-batch with per-frame `UpdateMeshBuffer` (adds 6–9 ms CPU on Cortex-A35 plus Panfrost sync). Keep static Mesh VBOs immutable and batch via uniform arrays (e.g. 32 transform/color slots) + `gl_InstanceID` + `rlDrawVertexArrayElementsInstanced`.
- **CPU skeletal skinning VBOs:** Under Runtime 1's 8-buffer GBM queue (2–3 frames in flight), double buffering (`[Mesh; 2]`) still hits sync stalls. Use a **4-slot ring buffer (`[Mesh; 4]`)**, deduplicate unindexed GLB vertices at load time, and reuse pose scratch buffers.
- **Offscreen FBO rule: complete ALL `BeginTextureMode()` passes BEFORE `BeginDrawing()`.** Switching to an offscreen FBO mid-frame (for 3D, bloom, carousel cards, or mini-planets) forces the Panfrost tile-based renderer to flush and reload the partial main framebuffer to DDR (`N` mid-frame FBOs = `N + 1` passes).
- **Main pass & FBO best practices:** Always call `ClearBackground()` on the main pass (avoids DDR tile reload on TBR); blit the 448×336 3D FBO to 1024×768 with `rlDisableColorBlend()`; reuse a frozen FBO on static pause/result overlays (0 draws, 0 tris); cap spinning mini-3D thumbnail FBOs at 1× resolution (`<= 224 px`) staggered at 15 Hz (at most 1 redrawn per frame).

# 4. 3D mesh, skinning and shader optimization

- **Bypass `DrawMesh()`:** `ffi::DrawMesh` recomputes `MatrixInvert`, binds 12 material slots, and calls `glUseProgram(0)` / `glBindVertexArray(0)` every draw (6–8 ms CPU for 40–75 draws). Wrap direct `rlgl` calls in a lightweight scope that caches bound shader, VAO and texture slot 0, updating only the model matrix and changed uniforms.
- **Per-vertex lighting + FP16 fragment shaders:** Move two-tone cel lighting, sky fill, bounded point lights and rim lighting to the vertex shader so fragments do only texture lookup × color. Use `precision mediump float;` in GLES fragment shaders for 2× Mali-G31 FP16 ALU throughput (keep `highp` in vertex shaders and UVs; guard WebGL 1 with `#ifdef GL_FRAGMENT_PRECISION_HIGH`). **FP16 overflow trap (max 65,504):** never pass distant sentinel positions like `(0, 1000, 0)` into `length()` for disabled lights (`1000^2` overflows to Inf/NaN); short-circuit with `if (lampCol.r > 0.0)`.
- **Geometry & draw-call reduction:** Run feature-preserving shortest-edge collapse at load time on handhelds (preserving UV seams, vertex colors, bone groups, boundaries and winding; `min_nrm_dot = 0.80`, `max_edge = 5.5%` cuts character tris 55–62%); group distant spherical/terrain patches into coarse SuperGroups; reduce foliage density while widening blades 1.25×; add a 1-bone skinning fast path, skip skinning for distant NPCs, and stagger off-focus updates at 30 Hz.

# 5. Gizlet OS, I/O spikes and GLES 3.0 lifecycle

- **Multi-backend shader headers:** Select by `rlGetVersion()`—desktop GL 3.3 (`#version 330`), Runtime 1 GLES 3.0 (`#version 300 es` + `precision highp float;`), WebGL 1 (`#version 100`, non-instanced fallback).
- **Deferred GPU init & clean shutdown:** Create all GPU atlases/FBOs/shaders only after `IsWindowReady()` so headless `cargo test` passes. On exit, follow strict order to prevent `SIGABRT`: `drop(app)` → unload custom textures/FBOs → `rlSetRenderBatchActive(null)` → `rlUnloadRenderBatch(batch)` → `CloseWindow()`. Only unload custom shaders when `id != 0 && id != rlGetShaderIdDefault()`.
- **evdev 2 s hotplug spike (35–60 ms):** Cache `/dev/input` mtime and ignored nodes (built into `gizlet/device-input` > v1.4.1).
- **`power_supply` / `thermal` sysfs I2C stalls (30–40 ms):** Move battery/temperature/perf reads to a background thread with initial preload and `Condvar` shutdown.
- **ALSA `InitAudioDevice` (~85 ms) / `CloseAudioDevice` (~10 ms):** Run audio init/play/idle-close on a dedicated background thread on native targets (check `IsAudioDeviceReady()` first).
- **`rayui` / `device-input` responsibility split:** `gizlet/rayui` > v0.4.0 includes `ShapeAtlas`, 24-buffer KMS batch, scissor dedup, layout reuse, pre-frame Carousel FBO caching, modal occlusion + two-pass keyboard, async battery, background audio, and `RAYUI_PROFILE=1`. Applications must still pre-seed CJK/Phosphor glyphs via `seed_text()`, keep animated font sizes fixed, and respect vertex budgets.
- **Never run handheld binaries bare:** Runtime 1 bundles Mesa/Panfrost/GBM/raylib in SquashFS; bare execution fails with `Failed to create GBM device`. Always invoke `/data/device/runtime/1/bin/gizlet-run <path-to-binary> </dev/null` (pass the executable path, not a directory; always redirect `</dev/null` over SSH so raylib's DRM backend does not read keyboard bytes from stdin; never enable `PAN_MESA_DEBUG=trace` on device).

# 6. Profiling triage and benchmark reference (R36MAX2, 5 apps / 64 scenes)

Measure steady-state `work` (`ctrl` / `lay` / `draw`), `frame avg` (including `EndDrawing()`), and `worst` on hardware:

- **Light CPU / heavy frame (`work < 10 ms`, `frame > 17 ms`):** GPU vertex, triangle or fill-rate bound. Check 2D vertices (> ~3,700), large alpha overdraw, modal overdraw, or 3D > 22k tris / missing 448×336 FBO.
- **Heavy CPU (`work ≈ frame`, 20–120 ms):** Panfrost sync stall or per-frame recomputation. Check 24-buffer batch, scissor dedup, `UpdateMeshBuffer`, mid-frame `BeginTextureMode`, or `DrawMesh`.
- **60 FPS average with 35–245 ms `worst` spikes:** Check 2 s/5 s `ctrl` spikes (evdev / sysfs), 85 ms first-input / 8 s `lay` spikes (audio), or 35–245 ms page-switch spikes (unseeded font rebuild / lazy FBO bake).
- **Acceptance gate:** Visual screenshot comparison at 1024×768 with handheld LOD enabled first (zero cracks, dark halos or misalignment), then steady-state on R36MAX2 at `avg <= 16.8 ms`, `worst <= 18 ms`, zero periodic spikes.

Verified results on R36MAX2 (1024×768, 1 ns hrtimer kernel + 8-buffer Runtime 1):

- **fInk (10 2D vector scenes):** 16.0–41.1 FPS → **60.0 FPS** across all 10 scenes (up to 3.74×; QR `share` 62.3 → 16.68 ms, 44-key `name` 59.8 → 16.67 ms).
- **Lean Workshop (12 2D scenes):** 11.3–35.7 FPS → **60.0 FPS** across all 12 scenes (`worst <= 17.40 ms`; `journey` 88.3 → 16.66 ms, `map` 62× `DrawCircleV` 51.6 → 16.67 ms).
- **rayui gallery (14 UI scenes):** 8.1–18.3 FPS → **60.0 FPS** across all 14 scenes (`worst <= 17.14 ms`; `dialog` 123.1 → 16.66 ms, 7.39×; 3D `shelf-turn` 75.9 → 16.66 ms).
- **Overeaten (16 3D+2D scenes):** 20.6–43.2 FPS → **58.1–60.0 FPS** across all 16 scenes (`room-4` 67k → 22k tris, 59 → 28 draws, 48.6 → 16.8 ms, 2.90×).
- **The Little Prince (12 3D+storybook scenes):** 9.6–43.0 FPS → **58.8–60.0 FPS** across all 12 scenes (`starmap` 104.0 → 16.7 ms, 6.25×; `title` 98 → 17 draws, 41.0 → 16.7 ms).

## Source files

- [gizlet/skill — performance.md](https://github.com/gizlet/skill/blob/main/skills/gizlet-dev/references/performance.md)
- [gizlet/rayui](https://github.com/gizlet/rayui) · [gizlet/device-input](https://github.com/gizlet/device-input) · [gizlet/os](https://github.com/gizlet/os)
- [gizlet/overeaten](https://github.com/gizlet/overeaten) · [li3g/little-prince](https://github.com/li3g/little-prince)
