Code
The source code for Computer Graphics Turbo Demos lives here.
Installation
The project uses a specific set of CircuitPython libraries, compiled .mpy files, the main code.py file, and a number of supporting .py and asset files.
We can do this in one go. In the example code block below, click the Download Project Bundle button to download the zip file. Extract the contents of the zip file, open the CG_TurboDemos_Code/ directory, and then open the directory that matches the version of CircuitPython you're using. Copy the contents of that directory to your CIRCUITPY drive.
# SPDX-FileCopyrightText: 2026 John Park with Claude Opus 5.5 for Adafruit Industries # # SPDX-License-Identifier: MIT """Boot into the demo menu (menu.py). To run one demo directly while developing, set DEMO to its module instead: voxel_demo, cornell_demo, metaballs_demo or meshes_demo. Keep this file tiny: demos allocate their SRAM framebuffers first thing, and anything imported before them uses up SRAM. """ DEMO = "menu" __import__(DEMO)
Kiosk Mode
If you'd like the Fruit Jam to boot into a single demo instead of the menu as soon as you turn it on, you can simply change the DEMO variable in the code.py file and save it.
Change DEMO = "menu" to any of these:
DEMO = "voxel_demo"DEMO = "cornell_demo"DEMO = "metaballs_demo"DEMO = "meshes_demo"
How It Works
Each demo has three layers:
- CircuitPython for setup and the frame loop
- Compiled Turbo/Viper (.mpy) to pass data to the code
- Inline assembler (
asm_thumb) for the per-pixel work
@micropython.asm_thumb
def add(r0, r1):
add(r0, r0, r1) # r0 = r0 + r1; r0 is the return value
The .py files in CG_Turbo_Demos_Code/ run from source on the board. They handle setup, buttons, the camera/animation, and the frame loop.
The Turbo modules live in turbo_source/. tools/build.py compiles them with mpy-cross -march=armv7emsp. For modules that contain asm_thumb functions, it then runs Liz Clark's tools/asm_to_viper.py. Stock CircuitPython loads Viper machine code but has no inline assembler, so that tool relabels each asm function as Viper.
A relabelled asm function can't take normal arguments, so every kernel is called the same way:
- Python fills an int32 "args block" in SRAM with sizes, addresses and per-frame values.
- A short Viper function turns offsets into absolute addresses and passes the block's address to the asm.
- The asm finds that address at
[r3], untags it withasr(r7, r7, 1), and reads everything else at fixed offsets fromr7.
Every kernel comes in a pair. A readable Viper render() is the reference and runs on the board and on the desktop (with stand-in decorators in tools/host/). The asm version is written by a generator script, tools/gen_*_asm.py, and must produce identical pixels: edit the generator, never its output.
display.py is shared by all four demos. It creates the picodvi framebuffer (320x240 RGB565, pixel-doubled to 640x480) before anything else, so the back buffer gets fast internal SRAM. It also sets aside a scratch area of SRAM for each demo's hot data and warns if anything lands in slower PSRAM. flip() waits for vblank, then copies the back buffer to the screen faster than the display scans it out, so nothing tears.
Voxel Space Demo Code
VoxelSpace is a Comanche-style terrain fly-over built from a grayscale height map and color texture map.
- How it draws For each screen column it marches out from the camera and draws a vertical span for each terrain sample it hits.
- Terrain data 16-bit samples (height plus a color index) with two smaller copies for distant terrain, stored in PSRAM.
- Code The whole frame is one asm call, written by gen_voxel_asm.py.
- Buttons The view modes, height scaling and fog all work by changing the input data, so the asm never changes.
The whole 320x200 frame is one asm call, which takes 24-31 ms in flight and holds a locked 30 fps; the Viper reference takes 117-130 ms.
CircuitPython
voxel_demo.py creates the Display, with 8 KB of scratch, before importing anything else, then builds a VoxelSpace. Each frame, flight.step() moves the camera along a winding path and eases its height toward the terrain ahead. Then space.render(screen.back) draws the frame and screen.flip() shows it.
voxelspace.py does all the setup:
- Terrain: loads 672 KB into PSRAM. Each texel is a u16, height in the high byte and palette index in the low byte, with two smaller mip levels for distant terrain.
- Distance table: each step holds
z,scale / z, a fog amount and a mip level, built in integer 16.16 math so the board and the desktop make the same table. - Each frame:
view()writes the camera position, heading vectors and horizon into the args block, and redraws the sky gradient only when the horizon moves. - Buttons: none of them touch the kernel. The view mode swaps in another copy of the terrain plus a gray palette, height scaling changes a shift value, and fog-off writes zeros into the table's fog column.
Turbo .mpy and asm
voxel.py holds render(), the Viper reference. For each distance step, near to far, it walks a row of 320 sample points across the map. It projects each sample's height to a screen row and, if that is above anything already drawn in that column, fills the span down to the previous top. A per-column "y buffer" tracks how far up each column has been drawn, and whatever is left at the top gets the sky.
render_fast() is a short Viper shim. It converts the block's offsets into absolute addresses in slots 0-31, because asm ldr offsets only reach 124 bytes, then calls voxel_asm.frame_asm() once. tools/gen_voxel_asm.py writes the inner loop out once per mip level, so its shifts are constants, each with and without the fog blend. Constants sit in r8-r12, leaving about 25 instructions per sample.
Cornell Box Demo Code
Cornell box is a progressive path tracer at 240x240 that takes 0.73 s per pass.
- Paths Each path has up to 3 bounces. At every matte surface it also samples the ceiling light directly.
- Accumulation Results add up in a float32 buffer in PSRAM.
- Accuracy The asm uses the FPU and matches the numpy reference exactly. Scene constants are stored as float32 bit patterns so the board can't round them differently.
- Boxes mode It swaps the spheres for rotated boxes, which nearly doubles the pass time.
One asm call traces one sample for each pixel of a 240-pixel row on the RP2350's FPU, and a full pass over all 240 rows takes 0.73 s.
CircuitPython
cornell_demo.py uses Display(back=False): the tracer draws straight into the framebuffer, one row at a time. The outer loop runs one pass, adding one sample per pixel. It checks the buttons between rows, so a press restarts within one row instead of after a whole pass.
cornell.py keeps a 113-word parameter block in SRAM scratch and a 690 KB float32 accumulation buffer in PSRAM:
- Each row:
trace_row()writes the row's accumulation address, output address and pixel index into the block, then calls the asm. - Scene: cornell_scene.py is generated by tools/cornell_scene.py, with every float stored as its bit pattern, so the board never parses a decimal and maybe rounds it differently from the desktop.
- Buttons: wall color and spheres/boxes overwrite a few words in the block, then clear the accumulation buffer with
mem.zero(). That Viper loop takes 98 ms; Python slice assignment took 10 s.
Turbo .mpy and asm
This demo has no Viper kernel. The reference is tools/cornell_ref.py, a NumPy float32 tracer that does the same operations in the same order, so the board's pixels and sums match it bit for bit. cornell_asm.trace_row() comes from tools/gen_cornell_asm.py and is about 1,300 lines, nearly all FPU instructions (vadd, vmul, vdiv, vsqrt, vcmp).
For each pixel, the asm:
- Seeds an xorshift32 random generator from the pixel index and pass number, and shoots a ray through a jittered point in the box's open front.
- Finds where the ray leaves the box, then tests the two spheres. In boxes mode it does a slab test against each rotated box instead, at 6 divides each.
- Reflects off the mirror sphere. On matte surfaces it samples a random point on the ceiling light, shadowed by the objects, then bounces in a cosine-weighted direction, for up to 3 interactions.
- Adds the color into the accumulation buffer, scales by exposure / samples, clamps, takes a square root as a cheap gamma, and packs RGB565 to the screen.
The random generator and other shared steps are bl subroutines. Long jumps use bl too, because Thumb's short branches reach only about 2 KB. The kernel saves s16-s31 into the block, because the caller expects them preserved.
Metaballs Demo Code
Metaballs demo shows six to ten 2D balls at 320x200 and 30 fps, all in integer math.
- The field Each ball adds Wyvill's falloff and its gradient over its own bounding area.
- Inside the blobs The surface height is
sqrt(field − threshold), and its slope looks up a 64x64 shading table, which makes the blobs look round. - Outside The field value picks a color from a glow palette with contour bands.
An all-integer field kernel draws six balls in 20 ms (the Viper reference takes 117 ms), and the demo holds 30 fps with up to 10 balls.
CircuitPython
metaballs_demo.py follows the VoxelSpace pattern, with 14 KB of scratch. Each frame, blobs.positions(t) gives each ball's (x, y, radius) on its Lissajous path. metafield.set_balls() converts them to 1/16-pixel fixed point and precomputes r² and (1 << 28) / r² per ball, so the kernel never divides. Then it renders and flips.
metafield.py loads metaballs.bin into PSRAM: six hue sets of 9 KB, each a 256-color glow palette, a 64x64 lit-surface table and a slope-scale table. The current set is copied into SRAM next to the args, so changing the hue is one 9 KB copy. Turning the glow off overwrites the glow palette with its first color. The double-click on button 1 is plain Python with a 0.35 s timer.
Turbo .mpy and asm
metaballs.render(), the Viper reference, works one row at a time:
- Clears three per-row sums: the field and its x and y gradients.
- For each ball whose circle crosses the row, adds Wyvill's falloff
(1 - d²/R²)²and its gradient across the ball's horizontal extent. - Inside a blob (field above the threshold), scales the gradient by a table value and uses it to index the 64x64 shading table, which gives the glossy 3D look.
- Outside, uses the field value to index the glow palette, contour bands included.
render_fast() fills the address slots and calls metaballs_asm.frame_asm() once per frame. The generated asm from tools/gen_metaballs_asm.py stores the three row sums interleaved per pixel, so one pointer reaches all three, and clears them while shading so the next row starts clean.
3D Models Demo Code
3D models demo animates the Utah teapot and the Stanford bunny meshes at 30 fps, with multiple shader options.
- Transform Vertices are rotated and projected on the FPU.
- Sorting Back faces are culled, then the rest are bucket-sorted far to near and painted in that order (the painter's algorithm).
- Filling Triangles are filled using edge functions.
- Lighting Lambert, Phong and Blinn are 64x64 tables looked up by the interpolated normal. This works because the light is directional and the view is nearly orthographic.
- Texture Texture mode interpolates two values per 32-bit register so the inner loop fits in the available registers.
Three asm kernels run each frame (transform, sort, draw) and render the teapot or bunny in 14-31 ms; the Viper sort and draw alone took 49-83 ms.
CircuitPython
meshes_demo.py uses a narrower 240x200 back buffer to free SRAM, plus 46 KB of scratch. Each frame it computes a rotation matrix (spin around y, a fixed tilt about x), renders and flips. The flip uses mem_asm.copy_rows_asm, because the narrow buffer goes in the middle of each 320-pixel screen row.
meshview.py loads the models (vertices, normals, face normals, triangle indices, quad edge masks and teapot UVs) and the 512x512 texture into PSRAM. It divides the SRAM scratch into four parts, each rounded up to 4 bytes so the next starts word-aligned:
- geo: the transformed vertices, the drawing order and the face normals.
- args: the parameter block for the sort and draw kernels.
- Lighting table: the current 64x64 table, copied in when the model or shader changes.
- Transform block: the floats for the transform.
Turbo .mpy and asm
- Transform:
mesh_asm.transform_asm, FPU asm called straight from Python, rotates and projects every vertex. It writes 1/16-pixel screen x and y, an integer depth and the normal's x and y as u16s into geo, plus packed face normals for Lambert mode. - Sort:
mesh.sortdrops back faces (negative signed area on screen) and bucket-sorts the rest into 256 depth buckets, far to near. - Draw:
mesh.drawclears the buffer and paints each triangle by mode:- Wireframes: Bresenham lines, using the edge mask in quad mode.
- Filled modes: edge-function fills with normals interpolated per pixel. The normal's x and y index the lighting table, which works because the light is directional and the view nearly orthographic.
- Texture: s, t and the normal are interpolated in wrapping 32-bit math, two values packed per register.
mesh.sort and mesh.draw are the Viper references. render_fast() fills a 32-word block and calls sort_asm and draw_asm, both generated by tools/gen_mesh_draw.py. The asm steps the edge functions instead of multiplying per pixel. In texture mode it computes each row's run of pixels directly with three sdivs, and the paint loop uses all 8 low registers plus r8-r12 and lr.
Every mode holds 30 fps except the 512x512 texture, which drops a frame now and then. All model/mode frames match tools/mesh_ref.py bit for bit.
Menu Code
Menu: Each demo starts as a fresh run of its own file, using supervisor.set_next_code_file and then a reload. That way every demo can put its buffers in fast internal memory first.
Page last edited October 29, 2026