Programming Macaw OS

The graphics chip

gpu.* talks to the 3D hardware directly, the way OpenGL 1.x does. You switch features on and off, set up matrices, and send triangles. If you've used old OpenGL, you'll know it already. It draws with the same renderer as scenes and meshes and shares their depth buffer, so you can mix them.

The eye looks down -z with y up, and matrices are column-major. The front of a triangle is the side its corners go round anticlockwise. Each window has its own chip state, so programs can't upset each other.

A spinning pyramid

WINDOW = { w = 240, h = 160, title = "Pyramid", realtime = true }
local t = 0
local SIDES = { colors.red, colors.yellow, colors.green, colors.sky }
local CORNERS = { { -1, -1, 1 }, { 1, -1, 1 }, { 1, -1, -1 }, { -1, -1, -1 } }

function _update() t = t + 1 / 60 end

function _draw()
  gpu.clearcolor(colors.navy)
  gpu.clear()

  gpu.matrixmode("projection")
  gpu.loadidentity()
  gpu.perspective(60, nil, 0.1, 50)    -- field of view, aspect (nil: the window's), near, far
  gpu.matrixmode("modelview")
  gpu.loadidentity()
  gpu.translate(0, 0, -4)
  gpu.rotate(20, 1, 0, 0)
  gpu.rotate(t * 90, 0, 1, 0)

  gpu.enable("depth_test", "cull_face")
  gpu.begin("triangles")
  for i = 1, 4 do
    local a, b = CORNERS[i], CORNERS[i % 4 + 1]
    gpu.color(SIDES[i])
    gpu.vertex(a[1], a[2], a[3])
    gpu.vertex(b[1], b[2], b[3])
    gpu.vertex(0, 1, 0)                -- the top
  end
  gpu.done()
end

Each side is a triangle in its own colour. depth_test makes the near sides hide the far ones, and cull_face skips the sides facing away.

State

CallWhat it does
gpu.enable(cap, ...)Switches on "depth_test", "cull_face", "lighting", "fog" or "texture"
gpu.disable(cap, ...)Switches them off
gpu.isenabled(cap)Returns whether one is on
gpu.depthmask(on)Sets whether drawing writes to the depth buffer
gpu.cullface("back")Sets which side culling hides, "front" or "back"
gpu.frontface("ccw")Sets which way round the corners of a front face go, "ccw" or "cw"
gpu.viewport(x, y, w, h)Draws into part of the window, counting from its top left. gpu.viewport() goes back to the whole window
gpu.clearcolor(c)Sets the colour gpu.clear clears to
gpu.clear(["color depth"])Clears the picture, the depth buffer, or both
gpu.reset()Puts everything back how it started

Matrices

CallWhat it does
gpu.matrixmode(m)Picks which matrix the calls below change, "modelview" or "projection"
gpu.loadidentity()Resets the matrix
gpu.pushmatrix() / gpu.popmatrix()Saves the matrix and gets it back
gpu.translate(x, y, z)Moves
gpu.rotate(degrees, x, y, z)Turns round an axis
gpu.scale(x, [y, z])Grows or shrinks
gpu.perspective(fovy, [aspect], [near], [far])Sets up a perspective projection
gpu.ortho(left, right, bottom, top, [near], [far])Sets up a flat projection
gpu.frustum(left, right, bottom, top, near, far)Sets up a perspective projection by its edges
gpu.lookat(ex, ey, ez, tx, ty, tz, [ux, uy, uz])Looks from the eye at a target. The last three say which way is up, and it's straight up if you leave them out
gpu.loadmatrix(m) / gpu.multmatrix(m)Sets the matrix to your own 16 numbers, or multiplies it by them
gpu.getmatrix(["modelview" or "projection"])Returns a matrix as 16 numbers. Without an argument it returns the current one
gpu.project(x, y, z)Returns where a point lands in the window, as x, y and a depth from 0 (near) to 1 (far). Returns nil if the point is behind the camera

Drawing

Immediate mode sends one corner at a time, between gpu.begin and gpu.done:

CallWhat it does
gpu.begin(mode)Starts drawing. The mode is "triangles", "tristrip", "trifan", "quads", "quadstrip", "polygon", "lines", "linestrip", "lineloop" or "points"
gpu.color(c, [bright])Sets the colour of the next corners
gpu.texcoord(u, v)Sets where on the texture the next corner is
gpu.normal(x, y, z)Sets which way the surface faces, for lighting
gpu.vertex(x, y, [z], [w])Sends a corner
gpu.done()Finishes drawing. It's also gpu["end"](), as in OpenGL

For models with lots of triangles, put them in a buffer once and draw the buffer each frame:

CallWhat it does
gpu.buffer(numbers, [layout])Makes a vertex buffer. buf:set(numbers) replaces what's in it, and buf:count() returns how many corners it holds. layout lists what each corner has, in order. p is the position (3 numbers), t the texture position (2), n the normal (3), c the colour (1), and l light baked in beforehand (1, where 1 is lit as usual)
gpu.indices(list)Makes an index buffer. It counts from 1 and can use at most 65536 corners
gpu.drawarrays(mode, buffer, [first], [count])Draws the corners in order
gpu.drawelements(mode, buffer, indices)Draws the corners the indices pick
local quad = gpu.buffer({
  -1, -1, 0,  0, 1,      -- position, then texture
   1, -1, 0,  1, 1,
   1,  1, 0,  1, 0,
  -1,  1, 0,  0, 0,
}, "pt")
local ix = gpu.indices({ 1, 2, 3, 1, 3, 4 })
-- in _draw:  gpu.bindtexture(img); gpu.drawelements("triangles", quad, ix)

Textures, light and fog

CallWhat it does
gpu.bindtexture(picture)Draws with this texture, or with none if you give nil
gpu.light(n, x, y, z, [w], [strength], [radius])Sets light n (1 to 8). With w at 0 it's a direction the light comes from, like the sun. With w at 1, the default, it's a lamp at that place that fades out by radius. gpu.light(n, false) turns it off
gpu.ambient(a)Sets the light everywhere, from 0 to 1
gpu.shademodel(m)Sets the shading. "flat" shades each face in one colour. "smooth" works the light out at the corners and blends it. "phong" works it out across the face, so highlights land where they should
gpu.material(shine, [sharpness])Sets how shiny surfaces are (0 to 1) and how tight the highlight is (from 2, which is broad, to 64)
gpu.fog(near, far, c)Sets the fog. Switch on "fog" as well
gpu.pointsize(n)Sets how big points are
gpu.stats()Returns what was drawn. That's triangles and corners, then the display lists used, made and missed

Reflecting water

The chip can draw water that reflects like a mirror, the way /games/sphinx draws its pool:

  1. Draw the scene into a picture, from a camera mirrored in the water.
  2. Draw the main scene.
  3. Call gpu.mask(true) and draw the water's surface. Instead of drawing colours, this marks which pixels are water. Then call gpu.mask(false).
  4. Call gpu.water(reflection, options). It mixes the reflection into the marked pixels, with ripples, a tint, and a surface texture drifting over it.
gpu.water(reflection, {
  tint = colors.teal, tintamount = 0.3,
  ripple = 1, time = t,
  surface = loadtexture("/system/textures/water.tex"), surfaceamount = 0.3,
  drops = { { 0.5, 0.5, 1.2 } },          -- where a drip fell (u, v) and how long ago
})
OptionWhat it does
tint, tintamountA colour mixed in, and how much of it (0.2)
near, farHow much it reflects close to you (0.35) and far away (0.85)
rippleHow far the ripples bend the reflection, in pixels (1.5)
timeThe time in seconds, which moves the ripples
flowHow fast the surface texture drifts (1)
surface, surfaceamountA texture for the water itself, and how much it shows (0.3)
dropsWhere drips fell, as { u, v, seconds ago } for each, up to 16. Each one sends out rings
envA baked reflection to use instead of the picture (see below)

The numbers in brackets are what you get if you leave an option out. gpu.clearmask() clears the marked pixels without drawing anything.

Draw the water as a grid of squares rather than one big square, so the graphics card's ripples have corners to move. Draw the mirrored scene without cull_face, because the mirror camera sees floors from underneath. Levels do all of this for you.

Baked reflections

Drawing the scene twice every frame is a lot of work for an older card. Instead, the water can reflect six views that you draw once, from just above its middle:

local faces = {}
local turns = { {90, 0}, {-90, 0}, {0, 90}, {0, -90}, {0, 0}, {180, 0} }  -- +x -x +y -y +z -z
for i, t in ipairs(turns) do
  faces[i] = image(128, 128)
  local was = target(faces[i])
  clear3d(colors.black)
  camera3d(x, y, z, t[1], t[2], 90)        -- square pictures, a quarter turn wide
  drawscene()
  target(was)
end
local env = gpu.envmap(faces, { x = x, y = y, z = z, box = { x0, y0, z0, x1, y1, z1 } })
-- then, each frame, in place of the reflection picture:
gpu.water(nil, { env = env, tint = colors.teal, time = t })

The first time you draw with a cube map (what gpu.envmap makes), it goes onto the graphics card one face per frame, and nothing shows until all six faces are there. env:loaded() tells you whether they are. env:unload() takes it off the card to save memory, and the next time you draw with it, it comes back a face per frame.

box is the room around that place. With it, nearby walls show up in the right place in the water. gpu.envmap returns nil when the graphics card can't do cube maps, and then you draw only the water's surface. newprobe, and a level's water and probes, do all of this for you (see Levels).