Introduction
The GBA cycle-level optimization article and the
one on faking point lights on the DS GPU share a
premise: these CPUs have no floating-point unit, and every vertex costs
something somewhere. The GBA pays in rasterizer cycles. The DS has a hardware
3D engine, so it pays elsewhere, in a part of the frame I had not looked at.
Note
framer-engine is a personal side project. The source code will be
made publicly available once the engine reaches a sufficient level of
maturity.
The framer-engine spinning_shapes example puts a cube, a sphere and
a cone on screen, each rotating, and a button toggles between drawing them
solid and drawing them as wireframes. On the DS it ran at 60 FPS in solid
and about 20 in wireframe. Wireframe should be cheaper: fewer pixels filled,
no lighting. The bug report was that a debug view ran three times slower than
the real thing. A second question followed: how do you measure a frame on a
platform you can only run in an emulator?
How wireframe gets drawn on a GPU that has no lines
The DS 3D engine draws triangles and quads, and nothing else:
libnds' glBegin() takes only triangles and quads (and their strips), with
no line primitive. The hardware has a wireframe polygon mode, selected by a
polygon alpha of zero, but it outlines a polygon's own edges. The engine's
meshes keep a separate list of the edges to draw, and for a sphere that list
leaves out the diagonals that split each patch into two triangles; the
hardware mode would draw them. (I reasoned this out and never tried the mode.)
So wireframe here is a thin, flat, unlit quad along every edge.
The quad has to be widened perpendicular to the edge, in a direction that
makes sense for a convex mesh centered on its origin. The code takes the
direction from the origin to the middle of the edge and removes the part along
the edge:
/* per edge, every frame */
float edge_len = sqrtf(edge[0]*edge[0] + edge[1]*edge[1] + edge[2]*edge[2]);
float mid_len = sqrtf(mid[0]*mid[0] + mid[1]*mid[1] + mid[2]*mid[2]);
dir[k] = edge[k] / edge_len; /* k = 0..2 */
radial[k] = mid[k] / mid_len;
dot = radial[0]*dir[0] + radial[1]*dir[1] + radial[2]*dir[2];
width[k] = radial[k] - dot * dir[k]; /* perpendicular to the edge */
width_len = sqrtf(width[0]*width[0] + width[1]*width[1] + width[2]*width[2]);
width[k] = width[k] / width_len * half_width;
/* then four vertices: a -/+ width, b +/- width, as 4.12 fixed point */
On a PC this is unremarkable. On the DS's ARM9 it is three square roots, nine
divides, roughly fifty multiplies and adds and twelve float-to-fixed
conversions per edge, every frame, each a call into a software
floating-point routine.
Why not just look at the frame rate
Reading the emulator's frame counter tells you least. melonDS' speed varied a
lot between runs in earlier sessions, so wall-clock time and its frame counter
say more about the host than the console. The emulated hardware timers hold
still: the same ROM executes the same instructions and the timers count them
the same way every run.
libnds exposes two of them chained into a 32-bit counter through
cpuStartTiming() and cpuEndTiming(), which return ticks of the
hardware timer clock (about 33.5 MHz, the bus clock; the ARM9 itself runs
at twice that). A throwaway build wraps the 3D render system and stores the
result in a global per render mode:
volatile uint32_t g_diag_ticks[2]; /* [0] solid, [1] wireframe */
volatile uint32_t g_diag_count[2];
static void nds_hw3d_render_system(framer_iter_t *it)
{
int w = framer_render_mode_get_override() ==
FRAMER_RENDER_MODE_FORCE_WIREFRAME;
cpuStartTiming(0);
nds_hw3d_render_system_impl(it); /* the real system, unchanged */
g_diag_ticks[w] = cpuEndTiming();
g_diag_count[w]++;
}
A copy of the example toggles the render mode itself every 120 frames, so
one emulator launch produces both numbers, and the globals are read over
melonDS' GDB stub, with their addresses taken from nm on the ARM9 ELF:
ticks = struct.unpack('<2I', bytes(rsp.read_mem(sock, tick_addr, 8)))
count = struct.unpack('<2I', bytes(rsp.read_mem(sock, count_addr, 8)))
Two runs agreed to within a few ticks, which makes the figures usable:
| Mode |
Ticks per frame |
Time |
| Solid |
317,950 |
9.5 ms |
| Wireframe |
1,414,850 |
42 ms |
A 60 FPS frame is 16.7 ms. Solid fits with room to spare. Wireframe takes
42 ms in the 3D pass alone, more than two vertical blanks, so the frame lands
on the third and the screen updates every 50 ms: 20 FPS.
Where 1.4 million ticks go
The meshes are not small. The sphere has 20 sectors and 10 stacks, which is
430 edges and 360 triangles; the cone adds 40 edges and 40 triangles and
the cube 12 and 12. A wireframe frame therefore builds 482 quads, and a
solid frame submits 412 triangles. Dividing:
- wireframe: 1,414,850 / 482, about 2,900 ticks per edge, roughly 5,900
ARM9 cycles for the arithmetic above;
- solid: 317,950 / 412, about 770 ticks per triangle, which is a normal and
three vertices converted to fixed point and handed to the GPU, with no
square root and no divide anywhere in it.
The GPU did not set the cost in either mode. The CPU did, and in wireframe it
spent 42 ms of every frame, two and a half frame budgets, on arithmetic whose
answer is the same every frame.
The data never changes
The cube is the same cube every frame. Only the model matrix changes, and the
GPU applies that itself from a matrix stack. Every square root and divide in
that loop recomputes the same four vertices as 1/60th of a second earlier.
The DS has a mechanism for exactly this: a display list, a block of
pre-packed geometry-engine commands that glCallList() sends to the GPU
FIFO by DMA. Its layout is the hardware's own FIFO layout, documented in
GBATEK: a first word with the number of words that follow,
then groups made of one word holding up to four command ids, one per byte,
followed by the parameter words of those commands in order. A quad with
four vertices comes out as:
word 0 count
word 1 BEGIN_VTXS | VTX_16 | VTX_16 | VTX_16 (0x23232340)
word 2 1 (GL_QUADS)
word 3 x0 | y0 << 16 vertex 0
word 4 z0
word 5 x1 | y1 << 16 vertex 1
word 6 z1
word 7 x2 | y2 << 16 vertex 2
word 8 z2
word 9 VTX_16 | NOP | NOP | NOP (0x00000023)
word 10 x3 | y3 << 16 vertex 3
word 11 z3
The packer is about eighty lines of plain C with the command ids defined next
to it (BEGIN_VTXS is 0x40, NORMAL 0x21, VTX_16 0x23). It has no
libnds dependency, so it is unit-tested on the desktop, with the layout above
as one test. libnds documents one trap: END_VTXS does nothing and is
reported to cause trouble in a DMA'd list, so lists never contain it.
void gx_dl_cmd(struct gx_dl *dl, uint8_t id, const uint32_t *params, int n)
{
if (dl->slot == 4) { /* open a new command word */
dl->cmd_at = dl->len++;
dl->words[dl->cmd_at] = 0;
dl->slot = 0;
}
dl->words[dl->cmd_at] |= (uint32_t)id << (8 * dl->slot);
dl->slot++;
for (int i = 0; i < n; i++)
dl->words[dl->len++] = params[i];
}
The renderer bakes a mesh the first time it is drawn in a given mode: the
edge quads for wireframe, the triangles with their flat normals for solid.
After that a draw is a colour, a glCallList() and nothing else. Only
what is identical on every draw goes into a list; the colour, the
material, the polygon format and the model matrix stay with the caller, so
the same list serves every object that shares a mesh. Two kinds of object
keep the old triangle-by-triangle path because they vary something a list
would have to hold: objects with a colour per face, since the material
changes between faces, and textured ones, since their texture coordinates
are scaled by the texture's size. The old immediate wireframe code also
stays, as the fallback for a mesh that cannot be baked: more than eight
different meshes in a program, or no memory left for the list.
Results
Same scene, same instrumented build, measured the same way:
| Mode |
Before |
After |
Change |
| Solid |
317,950 |
18,500 |
17 times cheaper |
| Wireframe |
1,414,850 |
24,450 |
58 times cheaper |
The wireframe pass goes from 42 ms to 0.73 ms and solid from 9.5 ms to
0.55 ms. The two modes now cost about the same, which is what the original
bug report had assumed all along.
The picture must stay the same. The figure shows the top screen before and
after, captured in the same runs as the numbers. The shapes are at different
points of their rotation because the demo keeps spinning; shading and lines
are the same.
Three caveats:
- The GPU still has to consume the list. glCallList() flushes the
list from the data cache, starts the DMA and waits for it to finish, and
the DMA only completes once the geometry FIFO has accepted the data. melonDS
models the geometry engine's timing only roughly, so on a real console
that wait will be longer than 0.7 ms. It is waiting on the GPU, not
computing, and nothing was measured on real hardware.
- The first draw pays the old price once. Baking runs the original math
one time per mesh and mode, so the first frame in wireframe still does
what every frame used to. It is a one-off hitch rather than a rate, and
an unmeasured one.
- Lists cost memory. About 15 KB for the sphere's wireframe and 12 KB
for its solid list, allocated from the heap and held for the life of the
program.
What is still on the slow path
Objects with per-face colours and textured objects still submit triangle by
triangle, so a scene dominated by them gets none of this. Both can be baked: a
per-texture-size list for the textured case, one list per colour run for the
face-coloured one. They are next, measured the same way.
Introduction
The previous two articles, on cycle-level optimization and the no-heap ECS
underneath it, were about the Game Boy Advance: an FPU-less CPU with no polygon
fill, where every trick avoids soft-float calls and VRAM writes. The Nintendo
DS backend in framer-engine is the opposite kind of target. It has a
fixed-function 3D GPU with hardware transform, lighting and rasterization.
That should make lighting the easy part, but the constraint only moves from
"the CPU can't do float math" to "the GPU can't do what you ask and renders
something else instead, without telling you."
This article covers a rendering bug, a hardware surprise from GBATEK, and a fix
that gets closer to point-light falloff without leaving the GPU's lighting
hardware for a software fallback.
Note
framer-engine is a personal side project. The source code will be
made publicly available once the engine reaches a sufficient level of
maturity.
The hardware constraint
Every light in framer-engine (directional, point or spot) is the same
struct light component, and every backend (GBA's software rasterizer,
desktop OpenGL/Vulkan/software, and this one) is expected to shade point lights
with distance falloff: brighter when closer, fading to nothing at the light's
range. The DS's hardware lighting docs rule that out. libnds's glLight():
void glLight(int id, rgb color, v10 x, v10 y, v10 z)
Only parallel light sources are supported on the DS
There are four hardware light slots, each a color and a direction vector, with
no position, range or falloff term. The GPU computes per-vertex Lambertian
shading (N·L) against those four directions in fixed-function hardware at
no CPU cost per triangle, which is excellent for a directional light. A point
light can only be an approximation: pick a direction, accept that the lighting
unit does not know about distance, and improve the approximation where
possible. The alternative is per-vertex shading on the ARM946E-S, which would
throw away the reason to use the GPU's fixed-function path.
Bug 1: an ambient floor that was zero on purpose
Before the point-light work, the hardware 3D path had a simpler problem.
GL_AMBIENT, the DS material property for the color of a face catching no
light, was set to black as soon as any Light entity existed:
/* what shipped, briefly */
glMaterialf(GL_AMBIENT, RGB15(0, 0, 0));
glLight() lights a face only if its normal faces toward one of the four
active directions. Any other face gets no diffuse contribution, and with
GL_AMBIENT at black, no ambient either, so every face pointing away from all
active lights rendered flat black. The fix looked simple: sum the color of every
ambient and directional light each frame and feed that into GL_AMBIENT
instead of a hardcoded zero:
s_ambient_r += gl->r;
s_ambient_g += gl->g;
s_ambient_b += gl->b;
/* ...clamped to 1.0 after the loop, then: */
glMaterialf(GL_AMBIENT,
RGB15((int)(r * s_ambient_r * 31.0f), /* ...g, b... */));
It rendered correctly with one active light and not with two.
The hardware surprise: ambient is summed once per active light
Adding a second point light turned every previously correct face white:
blown-out, clipped white, on geometry that had looked right a commit earlier.
The cause is in GBATEK's description of the DS polygon lighting equation, and
nothing in libnds's glMaterialf() doc comment mentions it. The hardware
does not compute MaterialAmbient once and add it to the result. It computes
MaterialAmbient × LightColor for every active light and sums those.
Diffuse and specular should work that way, since that is how colored lights
combine. Ambient is conceptually the floor when nothing lights the face and
should not scale with the number of lights, but the DS does not make that
distinction. Set GL_AMBIENT to the floor you want, and with three active
lights the hardware adds three times that to every face.
The first fix was to divide by the number of active lights before setting
GL_AMBIENT, so the hardware's sum would reconstruct roughly the intended
value:
/* looked right, wasn't */
float ambient_scale = 1.0f / (float)s_num_lights;
This fixed the overexposure with two point lights. It also made a sphere lit by
one dim ambient light and two much brighter point lights far too dark, because
a flat 1/N cannot know the three lights are not equally bright. It divides
a lone dim ambient contribution by as much as it divides two unrelated point
lights. A cube's few flat faces looked fine anyway, since whichever face caught
a point light's direction was bright from diffuse. A sphere's curved surface,
mostly facing none of the three directions, was left with almost only the
over-divided ambient term and rendered close to black again, from a different
arithmetic mistake.
The actual fix reconstructs the target ambient exactly. Track the per-channel
sum of every active light's color, not just the count, and divide by that:
/* MaterialAmbient * sum(LightColor) == target once hardware sums it
* back, regardless of how many lights are active or how bright any
* one of them is. */
float ambient_scale_r = 1.0f / fmaxf(s_light_color_sum_r, 0.05f);
glMaterialf(GL_AMBIENT,
RGB15((int)(r * amb_r * ambient_scale_r * 31.0f), /* ...g, b... */));
The hardware computes MaterialAmbient × sum(LightColor), so setting
MaterialAmbient = target / sum(LightColor) makes its sum land on target
for any number of lights of any brightness. The fmaxf(..., 0.05f) floor
covers an edge case: if every active light has an exact 0 in one color
channel (a pure green light has no red or blue), that channel's sum is zero and
no MaterialAmbient can make the hardware produce a nonzero result from a
color that has none. The floor does not fix that case, since the hardware
cannot recover an ambient floor for a channel no light contributes to. It only
keeps the reconstruction from returning inf and corrupting the result.
RGB555 and "bright enough"
With the arithmetic fixed, faces pointing away from every light were no longer
wrong, but still indistinguishable from unlit black in a screenshot. RGB555 has
5 bits per channel, 32 steps. A first ambient floor of 0.18 on a 0.8-albedo
material gives roughly 0.8 * 0.18 * 31 ≈ 4/31: nonzero, but lost to display
gamma and contrast. Raising the floor to 0.45 gives roughly 11/31, about
35%, enough for a person to see that the math is right. Getting the equation
right and getting the number right were two separate bugs.
Per-object falloff, without leaving hardware lighting
With the ambient floor behaving, the remaining problem was the one in the
introduction. The point light's direction was computed once per frame, from
the world origin, not per object:
/* once per frame, not once per object */
float lx = gl->x, ly = gl->y, lz = gl->z; /* the light's position */
/* ...normalize (lx, ly, lz) as a direction from the origin... */
glLight(s_num_lights, hw_color, dx, dy, dz);
Every object, wherever it sat relative to the light, saw the same direction and
brightness with no falloff, so a point light behaved like a directional one.
That is worse than the hardware's real limit requires. The DS cannot do
per-pixel falloff, or per-vertex falloff within one object, but it can use a
different, correct direction and brightness for each object if something
recomputes them per object.
So the glLight() upload moves from once per frame to once per object, right
before that object's triangles submit, with direction and falloff computed from
that object's world position:
static void nds_upload_lights_for_object(const float pos[3])
{
for (int i = 0; i < s_num_lights; i++) {
/* ...ambient/directional lights reuse the once-per-frame
* direction/color computed earlier -- no position to react
* to, so recomputing per object would be pure waste... */
float lx = gl->x - pos[0], ly = gl->y - pos[1], lz = gl->z - pos[2];
float d2 = lx * lx + ly * ly + lz * lz;
float atten = 1.0f - d2 * gl->inv_range2; /* same falloff every backend uses */
/* ...clamp atten to [0, 1], normalize (lx, ly, lz), scale color by atten... */
glLight(i, hw_color, dx, dy, dz);
}
}
An object near the light renders bright, one near the edge of its range dim,
and one outside the range gets nothing. This is per-object point-light falloff
through the same hardware N·L calculation as before. Triangle count, vertex
count and rasterization work do not change; only the values written to two
hardware registers that were already written once per object.
It is not free. A point light's direction needs a square root to normalize, now
once per (point light, object) pair instead of once per frame. But it uses the
same fixed-point sqrtf32/divf32 primitives as the per-frame version, on
a scene with a handful of lights and objects: a few more fixed-point
operations, no new soft-float cost, no extra vertex to transform or pixel to
fill. Against the cost of submitting an object's geometry it does not register.
Two smaller wins from the same pass
Neither changes a triangle.
GL_ANTIALIAS was enabled at startup and doing half its job. The DS blends
an edge under antialiasing only where the polygon ID changes across it, and
every object defaulted to ID 0, so edge smoothing applied only where an
object's silhouette met the background. Two overlapping objects with the same
ID got a hard edge between them. Giving each object its own ID (an index mod
63, since glClearPolyID(63) reserves 63 for the backdrop) applies the
blending between objects too. It is a different bitmask OR'd into a
glPolyFmt() call that already happens once per object.
The built-in sphere/cone mesh was generated at 12 sectors × 6 stacks (120
triangles), sized for a target this GPU is not. A comment in the code gives the
DS's per-frame budget as "on the order of a couple thousand polygons". A
360-triangle sphere at 20×10 is a rounding error against that and visibly
rounder, and triangle count was never this target's constraint.
Update: the tessellation win had a hidden cost
The rounder sphere had a cost this article missed at the time.
examples/lighting ran at exactly 30 fps on NDS timing (melonDS) instead of
60, and the cause traced back to this pass.
nds_submit_tri(), which issues each triangle's vertices, also recomputed
every triangle's GL_AMBIENT/GL_DIFFUSE material state, including the
ambient-reconstruction division from the sections above. For a single-color
object that is waste: the material state is identical across its triangles and
needs setting once per object. A 12×6 (120-triangle) sphere issued 120
redundant glMaterialf() pairs into the GX FIFO every frame even before this
article's change; the 20×10 sphere (360 triangles) issued 360. With the
lighting example's four active lights, each re-triggering the reconstruction on
every call, frame time went just past one VBlank period.
swiWaitForVBlank() does not degrade gracefully. It waits for the next
VBlank interrupt after the frame's work completes, so a frame either makes a
VBlank or waits for the one after. Missing one by any margin, even a fraction
of a scanline of GX FIFO backlog, halves the frame rate: 60 fps to exactly 30,
not 59 or 58. The tessellation bump caused no gradual slowdown. It sat under
the deadline until it crossed it.
The fix leaves tessellation, lighting and the ambient math unchanged. It
changes when the material state is written: once per object (or once per
face, for the rare object whose faces have different colors) immediately
before its triangles submit, not with every triangle. The same
GL_AMBIENT/GL_DIFFUSE values reach the GPU and nothing drawn changes;
the identical FIFO command is issued fewer times.
The GBA backend is unaffected. Its software rasterizer computes each face's
final color in gba_lit_color_face() and has no separate material state to
reissue.
Confirmed on melonDS timing: back to a solid 60 fps. The shape of the bug is
the one this article keeps hitting: the GPU does what it is asked at whatever
cost that carries, and two reasonable changes (a rounder sphere, per-object
point-light falloff) compounded into a cost neither would have caused alone.
Verifying a change with nothing to count
The GBA articles used cycle_probe.py, a deterministic emulator cycle
counter diffed between frames. It does not apply here: this work runs on the
GPU's fixed-function pipeline, not the ARM9's cycles, and there is almost no
CPU-side cost to isolate with a breakpoint. Verification was the build and test
suite (native, GBA and NDS cross builds, all passing unchanged throughout),
plus looking at the frame in melonDS to confirm that the sphere in
examples/lighting is shaded by two differently colored, differently
positioned lights instead of one flat approximation.
Where this goes next
The DS GPU has capabilities this backend does not use: hardware texture
sampling from VRAM, a specular shininess table, per-vertex fog. None are CPU
cost questions; they are GPU features sitting idle. Diffuse texturing is next,
as the highest-value use of unused hardware. If the ambient bug is a guide, it
will hide its own GBATEK surprise.