Rust + raylib handheld performance reference (Mali-G31 / Panfrost)
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).
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
rlglvertex 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_HINTon KMS (excessive bandwidth or context creation failure); use 2× SDF textures/shaders for antialiasing.
2. 2D geometry, overdraw and font baking traps
DrawRectangleRoundedand multi-layer shadows (130–1,500 v/card → 8–60 v): Expands corner triangle strips; 5-layer shadows reach ~1,500 v per card, andRL_TRIANGLESbreaksRL_QUADSbatching. Fix: prebake a 2× SDFRoundedMask(8 v) for fixed-size cards, or build a 128×128 RGBA8 4-quadrantShapeAtlas(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 oneRL_QUADSbatch.- 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,DrawSplineLinearand round caps (6 v/seg, 294 v with caps):DrawLineExusesRL_TRIANGLESand addingDrawCircleVcaps adds 2×144 v. Emit miter-clamped (cos.max(0.4)) 4-vertexRL_QUADSusing theShapeAtlaswhite texel, adding 4 vShapeAtlasdisc caps only whenthick >= 2.0 && thick_px >= 3.5.DrawRing,DrawCircleVand large radial glows:DrawCircleVhard-codes 36 segments = 144 v/circle. Use a single-batch SDF ring shader (4 v/ring viadFdx/dFdy, skippingr < 1.5) for hollow rings,ShapeAtlasquads (4 v) for circles and glows withr <= 200 px, and an untextured 16-segmentRL_QUADSvertex-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.DrawRectangleRoundedLinesExsegments < 4trap (rshapes.c:1194): Passingsegments < 4triggers automatic subdivision (SMOOTH_CIRCLE_ERROR_RATE = 0.5), exploding large corners to 12–20+ segments (400+ v/box). Always clampsegments >= 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 viarlPushMatrix/rlScalefinstead of changing font size, quantize DPI to 0.1 steps (1.6at 1024×768 instead of rounding to2.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
glBufferSubDataon 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 identicalBeginScissorModeregions (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 BEFOREBeginDrawing(). 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 (Nmid-frame FBOs =N + 1passes). - 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 withrlDisableColorBlend(); 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::DrawMeshrecomputesMatrixInvert, binds 12 material slots, and callsglUseProgram(0)/glBindVertexArray(0)every draw (6–8 ms CPU for 40–75 draws). Wrap directrlglcalls 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 (keephighpin 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)intolength()for disabled lights (1000^2overflows to Inf/NaN); short-circuit withif (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 headlesscargo testpasses. On exit, follow strict order to preventSIGABRT:drop(app)→ unload custom textures/FBOs →rlSetRenderBatchActive(null)→rlUnloadRenderBatch(batch)→CloseWindow(). Only unload custom shaders whenid != 0 && id != rlGetShaderIdDefault(). - evdev 2 s hotplug spike (35–60 ms): Cache
/dev/inputmtime and ignored nodes (built intogizlet/device-input> v1.4.1). power_supply/thermalsysfs I2C stalls (30–40 ms): Move battery/temperature/perf reads to a background thread with initial preload andCondvarshutdown.- ALSA
InitAudioDevice(~85 ms) /CloseAudioDevice(~10 ms): Run audio init/play/idle-close on a dedicated background thread on native targets (checkIsAudioDeviceReady()first). rayui/device-inputresponsibility split:gizlet/rayui> v0.4.0 includesShapeAtlas, 24-buffer KMS batch, scissor dedup, layout reuse, pre-frame Carousel FBO caching, modal occlusion + two-pass keyboard, async battery, background audio, andRAYUI_PROFILE=1. Applications must still pre-seed CJK/Phosphor glyphs viaseed_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/nullover SSH so raylib's DRM backend does not read keyboard bytes from stdin; never enablePAN_MESA_DEBUG=traceon 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-frameBeginTextureMode, orDrawMesh. - 60 FPS average with 35–245 ms
worstspikes: Check 2 s/5 sctrlspikes (evdev / sysfs), 85 ms first-input / 8 slayspikes (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
share62.3 → 16.68 ms, 44-keyname59.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;journey88.3 → 16.66 ms,map62×DrawCircleV51.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;dialog123.1 → 16.66 ms, 7.39×; 3Dshelf-turn75.9 → 16.66 ms). - Overeaten (16 3D+2D scenes): 20.6–43.2 FPS → 58.1–60.0 FPS across all 16 scenes (
room-467k → 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 (
starmap104.0 → 16.7 ms, 6.25×;title98 → 17 draws, 41.0 → 16.7 ms).