Programming Macaw OS
Every program in Macaw OS is a Lua file, from the Calculator to the level editor to the games. You can open any of them in Code to see how it works. Your own programs run the same way. Each gets a window on the desktop and uses the same drawing, sound and 3D calls.
This guide shows you how to write your own. If you've never written a program before, start at the top. If you already know Lua, skip to the page for what you want to make.
Start here
- Your first program shows you how to make a window, draw in it and move something with the keys. It also explains how a program runs and what to do when it goes wrong.
- Make a game builds a small game called Seed Catcher, one step at a time.
What you can make
| Page | What's in it |
|---|---|
| Drawing | Shapes, text, colours, pictures, drawing into pictures, the screen's size and colours |
| Input and sound | The keyboard and mouse, sound effects, notes, and songs from the Music app |
| Game carts | A game in a folder with its sprites, map, sounds and music, and the editors for each |
| 3D | Textured meshes, a camera and lights, and scenes of objects that move, collide and can be clicked |
| The graphics chip | OpenGL-style 3D with matrices, draw calls, lighting and reflecting water |
| Levels | Levels built in Brushwork that you walk round in your own program |
| Apps | Buttons, text boxes and lists, menus, dialogs, drag and drop |
| Files and the system | The disk, what Lua can do here, busy programs, saved passwords, System Extensions |
| Memory | Your program's own memory, with addresses, peek and poke, malloc and free, and the window's picture |
| C | Writing programs in C, with pointers, structs, the C library and Macaw OS's calls |
| Networking | Talking to other people's computers on the Macaw network |
Where to look
- The programs that come with Macaw OS are in
/system/apps. The games are in/games. Each game is a cart folder, so right-click it in Files and choose Show Contents to look inside. - Examples are in
/home/examples. There's Seed Catcher (the game the tutorial builds), Worm (a game written in C), a greeter, a to-do list, a program that shows every UI widget, and a System Extension. - The Read Me on the desktop is the short version of this guide. It lists every call.
- In Terminal,
new mygame.luastarts a program,newcart mygamestarts a cart andnewapp myapp.luastarts an app with buttons.
The machine
| Screen | 640x360 to start with, or 640x480, 800x600 or 1024x768. It shows 256 colours, 8 colours or thousands |
| Sound | 4 effect voices, plus the S16 music chip with 16 voices of synth or recorded instruments |
| Input | Keyboard and mouse |
| Language | Lua 5.4, and C89 (see C) |
| Disk | /system and /games come with Macaw OS and can't be changed. /home is yours |
Macaw OS runs the same programs on Windows, on PowerPC Macs (Mac OS X and Mac OS 9), on the Raspberry Pi and in a web browser. A program can't reach the computer underneath. It only sees the Macaw disk and the Macaw network (and shares the clipboard).
Your first program
Make one
Open Terminal (it's on the desktop, or in the macaw menu) and type:
new first.lua
This makes /home/first.lua from a template and opens it in Code. Press Ctrl+R (Cmd+R on a Mac) to run it. You get a window with an orange ball that you move with the arrow keys. Change something and press Ctrl+R again, and the window starts over with your change. Ctrl+S saves the file.
Terminal can start other kinds of program too. newcart mygame makes a game cart, newapp myapp.lua makes an app with buttons, and new3d my3d.lua makes a program with a 3D scene in it.
What a program looks like
WINDOW = { w = 240, h = 160, title = "Hello" }
local x = 120
function _init()
-- once, when the program starts
end
function _update()
-- 60 times a second: read the keys, move things
if btn("left") then x = x - 1 end
if btn("right") then x = x + 1 end
end
function _draw()
-- draw the window
cls(colors.navy)
text("Hello, Macaw!", 8, 8, colors.yellow)
circfill(x, 80, 8, colors.orange)
end
When the program starts, the file runs once from top to bottom. Anything at the top level, like local x = 120, is set up before _init is called. After that, Macaw OS calls these functions:
| Function | When it's called |
|---|---|
_init() | Once, after the file has run and the window is open |
_update() | 60 times a second, while the program runs |
_draw() | When the window needs drawing (see below) |
_resize(w, h) | When someone resizes the window. Its new size is w x h |
_close() | When the window is closing. Save anything you need to here |
_drop(paths, x, y) | When files are dragged onto your window, at x, y |
_display(w, h, colours) | When the screen changes size or number of colours |
You only need the ones you use. A program with just _draw works fine.
The window
WINDOW describes the window you want. Every field is optional:
| Field | What it does |
|---|---|
w, h | The size of the inside of the window, in pixels |
title | The words in the title bar (settitle(s) changes them later) |
scale | Shows every pixel 2, 3 or 4 times as big, if it fits on the screen |
realtime | true draws every frame, which games need (see below) |
resizable | false stops people resizing the window |
minw, minh | The smallest size the window can be resized to |
fullscreen | true starts the window full screen |
cursor | false hides the pointer over the window, for when you draw your own |
The top-left pixel of the window is 0, 0. x goes right and y goes down. If someone resizes the window, WINDOW.w and WINDOW.h change to match and _resize is called.
When _draw runs
Most programs only change when someone does something, so Macaw OS doesn't redraw every window every frame. _draw runs while someone is using your window, after they choose a menu item, answer a dialog or drop something on it, and every so often anyway.
- If
_updatechanges what the window shows (a timer ticked, or a download finished), callredraw()and the window is drawn on the next frame. - In a game, things move all the time. Set
realtime = trueinWINDOWand the window is drawn every frame. - Windows nobody can see aren't drawn at all. That includes hidden and rolled-up windows, and windows behind a full-screen one.
When it goes wrong
If your program has a mistake, you hear a squawk and its window shows This program crashed., with what went wrong and the line it happened on. Fix it in Code and press Ctrl+R again.
print(...)writes to Terminal, so you can watch values change.- The IDE (macaw menu, Programming Tools) runs a whole project. It checks that every file compiles, and shows each mistake with its line number and the lines that called it. Click a mistake to go to its line. The IDE also has a profiler that shows which of your functions take the most time.
- The Profiler shows how long every open window's
_updateand_drawtake.
A program can't freeze Macaw OS. If it runs for a long time without finishing, because of a loop that never ends or a big file it's loading, it's paused every 30 milliseconds and the rest of the desktop carries on. See busy programs.
Keeping things
Your program can read and write files in /home:
fs.write("/home/hello-score.txt", tostring(score))
local saved = tonumber(fs.read("/home/hello-score.txt") or "") or 0
fs.read returns nil if the file isn't there yet, so the or gives you a value to start with. See Files and the system for the other file calls.
Next
Make a game builds a whole game one step at a time. Or go straight to drawing, input and sound or 3D.
Make a game: Seed Catcher
In Seed Catcher, seeds fall from the sky and you move a macaw along the ground to catch them. Miss three and the game is over. The finished game is about a hundred lines. Each step below leaves you with a program that runs, so try it as you go.
Open Terminal and type new seeds.lua. The new file opens in Code. Delete everything the template put in it, because you'll write the whole program yourself.
1. A window and the sky
WINDOW = { w = 240, h = 160, title = "Seed Catcher", realtime = true }
local GROUND = 148 -- the grass starts here
function _draw()
cls(colors.sky)
rectfill(0, GROUND, WINDOW.w, WINDOW.h - GROUND, colors.green)
end
Press Ctrl+R to run it. realtime = true tells Macaw OS to draw the window every frame. A game needs this because things move all the time. cls fills the window with a colour, and rectfill(x, y, w, h, colour) draws a filled rectangle. Here it draws the grass, from GROUND to the bottom of the window.
2. The macaw
You can make a picture from text. Each character is a pixel, and a table says which colour each character stands for. A . is see-through. Put this under the GROUND line, because the macaw's position uses it:
local BIRD = parseimage({
"...rr...",
"..rrrr..",
".rrkrry.",
".rrrryy.",
"rrrrrr..",
"bbrrrr..",
".bbrr...",
"..b..b..",
}, { r = colors.red, y = colors.yellow, b = colors.blue, k = colors.night })
local bird = { x = 116, y = GROUND - 16, flip = false }
Draw it in _draw, after the grass:
blit(BIRD, bird.x, bird.y, 0, 2, bird.flip)
blit(picture, x, y, see-through colour, scale, flip) draws the picture. The macaw is 8x8, drawn at twice the size, so it covers 16x16 pixels. Colour 0 (the dots) isn't drawn at all. For bigger pictures, draw them in Paint and load them with loadimage.
3. Moving
_update runs 60 times a second. btn says whether a key is held down:
function _update()
if btn("left") then bird.x = bird.x - 2; bird.flip = true end
if btn("right") then bird.x = bird.x + 2; bird.flip = false end
bird.x = clamp(bird.x, 0, WINDOW.w - 16)
end
clamp keeps the macaw inside the window. flip turns it to face the way it's moving.
4. Seeds
The seeds are kept in a list. Every so often a new seed starts just above the window at a random place. Each frame, every seed falls a little. Put this under the macaw, above _update:
local seeds = {}
local timer = 0
local function drop_seed()
add(seeds, { x = 4 + rnd(WINDOW.w - 8), y = -4, speed = 0.6 + rnd(0.6) })
end
In _update:
timer = timer - 1
if timer <= 0 then
drop_seed()
timer = 40 + rnd(30) -- the next one in 40 to 70 frames
end
for s in all(seeds) do
s.y = s.y + s.speed
end
And in _draw, before the macaw:
for _, s in ipairs(seeds) do circfill(s.x, s.y, 2, colors.brown) end
rnd(n) gives a random number from 0 up to n. add puts something on the end of a list. all goes through a list in a way that lets you take things out of it as you go, which the next step needs.
5. Catching
A seed is caught when it's inside the macaw's 16x16 square. Change the seed loop to this:
for s in all(seeds) do
s.y = s.y + s.speed
if s.y > bird.y and s.y < bird.y + 16 and s.x > bird.x and s.x < bird.x + 16 then
del(seeds, s)
score = score + 1
sfx("coin")
elseif s.y > GROUND then
del(seeds, s)
lives = lives - 1
sfx("hit")
end
end
Put local score, lives = 0, 3 at the top of the file, and show both in _draw:
text("score " .. score, 4, 4, colors.navy)
for i = 1, lives do circfill(WINDOW.w - 8 * i, 7, 3, colors.red) end
del takes the seed out of the list. sfx plays one of the built-in sounds: blip, coin, jump, hit, lose, squawk, rawk and chime.
6. Game over, and again
When lives reaches 0, the game stops and waits for Enter. Put everything a new game needs in one function, so that starting again only takes one call:
local function restart()
bird = { x = 116, y = GROUND - 16, flip = false }
seeds = {}
score, lives, timer, over = 0, 3, 0, false
end
restart now gives the variables their values, so they only need declaring. Replace local bird = ..., local seeds = {}, local timer = 0 and local score, lives = 0, 3 with the one line below. Put it straight under the GROUND line, above everything that uses the variables, including restart. _init starts the first game:
local bird, seeds, score, lives, timer, best, over
function _init()
restart()
end
In the seed loop, after sfx("hit"), end the game when the last life is gone:
if lives == 0 then
over = true
sfx("lose")
end
At the start of _update, wait for a key while the game is over:
if over then
if btnp("enter") or btnp("space") then restart() end
return
end
btnp is true in the frame a key goes down, and again now and then as the key repeats while it's held. btn is true every frame the key is down. With btnp, one press starts one game. To show the message at the end of _draw, use centertext, which writes text centred on an x position. Its last number makes the text bigger:
if over then
rectfill(40, 56, 160, 40, colors.night)
centertext("Game over!", 120, 64, colors.yellow, 2)
centertext("Enter plays again", 120, 84, colors.white)
end
7. A best score that stays
Files in /home are kept after the program quits. Read the best score when the game starts. Put best = load_best() in _init, before restart(), and put this above _init:
local function load_best()
return tonumber(fs.read("/home/seedcatcher.txt") or "") or 0
end
Show it under the score in _draw with text("best " .. best, 4, 14, colors.navy). Then save it when it's beaten, inside if lives == 0 then, after sfx("lose"):
if score > best then
best = score
fs.write("/home/seedcatcher.txt", tostring(best))
end
Finally, make the seeds fall faster as the score goes up by adding + score * 0.03 to their speed in drop_seed.
The whole game
Here is the complete program. It's also in /home/examples/seedcatcher.lua, and you can run it from Terminal with run /home/examples/seedcatcher.lua.
-- Seed Catcher: the game the programming guide's tutorial builds (macaw:docs/tutorial).
-- Seeds fall; the macaw catches them. Miss three and it's over.
WINDOW = { w = 240, h = 160, title = "Seed Catcher", realtime = true }
local BIRD = parseimage({
"...rr...",
"..rrrr..",
".rrkrry.",
".rrrryy.",
"rrrrrr..",
"bbrrrr..",
".bbrr...",
"..b..b..",
}, { r = colors.red, y = colors.yellow, b = colors.blue, k = colors.night })
local GROUND = 148 -- the grass starts here
local bird, seeds, score, lives, timer, best, over
local function load_best()
return tonumber(fs.read("/home/seedcatcher.txt") or "") or 0
end
local function restart()
bird = { x = 116, y = GROUND - 16, flip = false }
seeds = {}
score, lives, timer, over = 0, 3, 0, false
end
function _init()
best = load_best()
restart()
end
local function drop_seed()
-- seeds come faster as the score goes up
add(seeds, { x = 4 + rnd(WINDOW.w - 8), y = -4, speed = 0.6 + rnd(0.6) + score * 0.03 })
end
function _update()
if over then
if btnp("enter") or btnp("space") then restart() end
return
end
-- move
if btn("left") then bird.x = bird.x - 2; bird.flip = true end
if btn("right") then bird.x = bird.x + 2; bird.flip = false end
bird.x = clamp(bird.x, 0, WINDOW.w - 16)
-- a new seed every second or so
timer = timer - 1
if timer <= 0 then
drop_seed()
timer = 40 + rnd(30)
end
-- fall, get caught, or land
for s in all(seeds) do
s.y = s.y + s.speed
if s.y > bird.y and s.y < bird.y + 16 and s.x > bird.x and s.x < bird.x + 16 then
del(seeds, s)
score = score + 1
sfx("coin")
elseif s.y > GROUND then
del(seeds, s)
lives = lives - 1
sfx("hit")
if lives == 0 then
over = true
sfx("lose")
if score > best then
best = score
fs.write("/home/seedcatcher.txt", tostring(best))
end
end
end
end
end
function _draw()
cls(colors.sky)
rectfill(0, GROUND, WINDOW.w, WINDOW.h - GROUND, colors.green)
for _, s in ipairs(seeds) do circfill(s.x, s.y, 2, colors.brown) end
blit(BIRD, bird.x, bird.y, 0, 2, bird.flip)
text("score " .. score, 4, 4, colors.navy)
text("best " .. best, 4, 14, colors.navy)
for i = 1, lives do circfill(WINDOW.w - 8 * i, 7, 3, colors.red) end
if over then
rectfill(40, 56, 160, 40, colors.night)
centertext("Game over!", 120, 64, colors.yellow, 2)
centertext("Enter plays again", 120, 84, colors.white)
end
end
Where next
- Draw a better macaw and seeds in Paint, and load them with
loadimage. - Add a seed in another colour that the macaw should avoid.
- Turn the game into a cart. A cart keeps sprites, a map and music in one folder that you can share as a single file.
- Write a song for it in Music and play it with
playsong(sound).
Drawing
Everything you draw goes into your window. The top-left pixel is 0, 0 and the bottom-right pixel is WINDOW.w - 1, WINDOW.h - 1. Put your drawing calls in _draw.
Shapes
function _draw()
cls(colors.navy) -- fill the window
rectfill(10, 10, 60, 30, colors.orange) -- x, y, width, height
rect(10, 50, 60, 30, colors.white) -- just the outline
circfill(120, 40, 20, colors.yellow) -- centre x, y, radius
line(0, 100, 239, 100, colors.lime)
tri(160, 120, 200, 60, 230, 120, colors.pink)
pset(5, 5, colors.red) -- one pixel
end
| Call | What it does |
|---|---|
cls(c) | Fills the window with colour c |
pset(x, y, c) | Sets one pixel to colour c |
pget(x, y) | Returns the colour of a pixel |
line(x0, y0, x1, y1, c) | Draws a line |
rect(x, y, w, h, c) | Draws a rectangle's outline |
rectfill(x, y, w, h, c) | Draws a filled rectangle |
box(x, y, w, h, fill, [outline]) | Draws a filled rectangle with an outline |
circ(x, y, r, c) | Draws a circle's outline |
circfill(x, y, r, c) | Draws a filled circle |
tri(x0, y0, x1, y1, x2, y2, c) | Draws a filled triangle |
Text
Each character of the font is 5x8 pixels in a 6x9 cell. CHAR_W and CHAR_H hold the cell's size.
| Call | What it does |
|---|---|
text(s, x, y, c, [scale]) | Writes s with its top left at x, y, and returns the x just after it |
textwidth(s, [scale]) | Returns how wide s would be, in pixels |
centertext(s, x, y, c, [scale]) | Writes s centred on x |
shadowtext(s, x, y, c, [shadow], [scale]) | Writes s with a shadow one pixel down and to the right |
wraptext(s, columns) | Breaks s into lines of at most columns characters and returns them as a list |
Because text returns where it stopped, you can write in several colours along one line:
local x = text("Score: ", 4, 4, colors.white)
text(score, x, 4, colors.yellow)
Colours
You can use 256 colours at once, numbered 0 to 255.
- 0 to 31 have names, such as
colors.black,colors.redandcolors.sky. The full list is below. 0 is black, and it's the colour you usually pass toblitas the see-through colour. - 32 to 47 are the logo's colours.
- 48 to 63 are greys, from black to white.
- 64 to 159 are sixteen hues, each in six bright shades from dark to light.
- 160 to 255 are the same hues in six muted shades, which give you browns, skin tones and olives.
The 32 names are black, night, slate, steel, mist, white, brown, tan, sand, red, orange, yellow, green, blue, purple, pink, maroon, rust, cream, forest, lime, navy, sky, plum, lavender, teal, mint, charcoal, darkgrey, grey, silver and paper.
| Call | What it does |
|---|---|
nearestcolor(r, g, b) | Returns the closest of the 256 colours to an RGB colour (each part 0-255) |
pal(c) | Returns the r, g, b that colour c shows as now |
pal(c, r, g, b) | Changes what colour c looks like, everywhere on the screen |
pal() | Puts every colour back to normal |
drawpal(c1, c2) | Draws colour c1 as c2 from now on. Use it to flash a sprite white, for example |
drawpal() | Stops swapping colours |
Pictures
A picture (an image) is a grid of colours. You can draw it into your window, and you can draw into it.
local ship = loadimage("/home/ship.pxl") -- made in Paint
local dot = parseimage({ ".9.", "999", ".9." })
function _draw()
cls(0)
blit(ship, 50, 40, 0) -- colour 0 is see-through
blit(dot, 10, 10, 0, 4) -- four times as big
end
| Call | What it does |
|---|---|
image(w, h) | Makes a new picture filled with colour 0 |
loadimage(path) | Loads a picture saved by Paint (.pxl) |
saveimage(img, path) | Saves a picture as .pxl |
parseimage(rows, [map]) | Makes a picture from text, one character per pixel. map says what colour each character is. Without map, . is 0, and 0-9 and a-v are colours 0-31 |
decodeimage(png, [maxw], [maxh]) | Makes a picture from PNG data, shrunk to fit inside maxw x maxh |
importpicture(png, [maxw], [maxh]) | A PNG made elsewhere, for editing: each pixel the nearest of the 256 colours, see-through parts colour 0, made smaller only to fit maxw x maxh (256 x 256 if you don't say). Returns the picture and its own width and height, or nil and why |
decodeimage(png, maxw, maxh, nil, false, true) | The same for pixel art (a sprite): see-through pixels stay see-through (colour 0), and the others take the nearest colours without dithering, so the picture doesn't shimmer as it moves |
loadtexture(path, [size]) | Loads a photo texture (.tex) for 3D. It's at most 64 pixels across, or size if you give one (up to 1024) |
blit(img, x, y, [key], [scale], [flipx], [flipy]) | Draws a picture. key is a colour to leave out, usually 0 |
blitpart(img, sx, sy, sw, sh, x, y, [key], [scale], [flipx], [flipy]) | Draws part of a picture, such as one frame from a sheet |
Each picture also has its own calls:
| Call | What it does |
|---|---|
img:get(x, y) / img:set(x, y, c) | Reads or sets one pixel |
img:size() | Returns the width and height. img:width() and img:height() return one each |
img:clear([c]) | Fills the picture with one colour |
img:copy() | Makes a new picture the same as this one |
img:getrgb(x, y) / img:setrgb(x, y, r, g, b) | Reads or sets a pixel's true colour, which shows when the screen is in thousands of colours |
Drawing into a picture
target(img) sends drawing into a picture instead of your window, and target() sends it back to the window. Use it to build something once and draw it many times, such as a background or a minimap:
local bg = image(240, 160)
target(bg)
cls(colors.sky)
for i = 1, 40 do circfill(rnd(240), rnd(100), 2 + rnd(6), colors.white) end
target()
function _draw()
blit(bg, 0, 0)
end
target returns where you were drawing before, so local was = target(img) ... target(was) goes back to exactly that place. targetsize() returns the size of whatever you're drawing into.
Scrolling and clipping
| Call | What it does |
|---|---|
camera(x, y) | Moves everything drawn after this by -x, -y. Use it to scroll a big world |
camera() | Puts the camera back to 0, 0 |
clip(x, y, w, h) | Limits drawing to this rectangle |
clip() | Lets you draw anywhere again |
The screen
The screen starts at 640x360 with 256 colours. People can change it in the Monitors section of System Preferences, to 640x480, 800x600 or 1024x768, and to 8 colours, 256 or thousands.
| Call | What it does |
|---|---|
SCREEN_W, SCREEN_H | The screen's current size |
display.current() | Returns the screen's width, height and colours ("8", "256" or "thousands") |
display.sizes() | Returns the sizes the screen can be, as { {640, 360}, ... } |
display.request(opts, fn) | Asks for a different size or number of colours |
A game that wants a bigger screen can ask for one. The person sees Allow, Always Allow and Don't Allow buttons. If they allow it, the screen changes back when your program quits:
display.request({ width = 800, height = 600, colors = "thousands" }, function(ok)
if not ok then print("staying as we are") end
end)
_display(w, h, colours) is called whenever the screen changes. With thousands of colours, photos and 3D show in true colour. With 8 colours, everything is dithered to black, red, green, yellow, blue, magenta, cyan and white.
Input and sound
Keys
function _update()
if btn("left") then x = x - 1 end -- held down
if btnp("space") then sfx("jump") end -- just pressed, this frame
end
| Call | What it does |
|---|---|
btn(key) | Returns true while key is held down |
btnp(key) | Returns true in the frame key goes down, then again every so often while it's held, the way a key repeats when you type |
keysp() | Returns a list of the names of every key that went down or repeated this frame |
textin() | Returns the characters typed this frame. Use it for text entry, not for game controls |
The key names are left, right, up, down, enter, escape, space, backspace, tab, delete, home, end, pageup, pagedown, shift, ctrl, alt, cmd, f1 to f12, a to z and 0 to 9. Punctuation keys are named by their character (-, =, [, ], ;, ', ,, ., /, `).
Only the window in front gets key presses. Ctrl (Cmd on a Mac) with a letter is kept for menu shortcuts, so use the arrow keys, letters, Space and Enter for game controls.
The mouse
local mx, my, down, pressed, released, wheel = mouse()
if pressed & 1 ~= 0 then print("clicked at", mx, my) end
mouse() returns the pointer's position inside your window, then three button values. These say which buttons are held, which were pressed this frame and which were let go this frame. Each is a sum of 1 (left), 2 (right) and 4 (middle). wheel is how far the scroll wheel turned.
To make your own right-click menu, see Apps.
Sound effects
sfx("coin")
The built-in effects are blip, coin, jump, hit, lose, squawk, rawk (a shorter macaw call) and chime. In a cart, sfx(n) with a number plays the cart's own effects instead, the ones you made in the SFX editor.
Notes and tones
There are four effect voices, numbered 1 to 4. Each voice plays one sound at a time.
play(1, "C4", 200) -- voice 1, middle C, 200 ms
play(2, "E4", 200, "triangle", 0.3) -- a softer wave, quieter
tone(4, 880, 300, "square", 0.4, -2000) -- 880 Hz, falling 2000 Hz a second
| Call | What it does |
|---|---|
play(voice, note, ms, [wave], [volume]) | Plays a note such as "C4", "F#3" or "Bb5" for ms milliseconds |
tone(voice, hz, ms, [wave], [volume], [slide]) | Plays a frequency in Hz. slide is how many Hz per second the pitch rises by. A negative slide makes it fall |
note(name) | Returns the frequency of a note. note("A4") is 440 |
stop() | Stops all four voices |
The waves are square, pulse, triangle, saw, sine and noise. Volume goes from 0 to 1, and is 0.5 if you leave it out.
Music
You write songs in the Music app, which saves them as .song files. A song you play loops until you stop it:
function _init()
playsong("/home/music/island.song")
end
function _close()
stopsong()
end
| Call | What it does |
|---|---|
playsong(path or song, [loop]) | Plays a song. Pass false for loop to play it once |
stopsong() | Stops the song |
loadsong(path) | Loads a song so you can change it before you play it |
music.volume(v) | Sets the music's volume, from 0 to 1 |
music.note(channel, instrument, n, [volume]) | Plays one note on the music chip straight away. instrument is 1-16, from the song that's playing |
music.release(channel) | Releases the note playing on channel |
notenumber(name) | Returns a note's number. notenumber("C-4") is 49 |
notename(n) | Returns a note's name from its number. notename(49) is "C-4" |
The music chip has 16 voices of its own, separate from the four effect voices, so music and sound effects can play at the same time. Each instrument is either a synth, which plays a wave you draw, or a recording of a real instrument. The recorded ones include piano, strings, cello, harp, flute, clarinet, horn, trumpet, marimba and drums. The example songs are in /home/music. Double-clicking one plays it in Jukebox, and the Music app opens it to change it. demo.song (synth) and island.song (recorded) are good songs to start from, and ambient.song is an ambient piece made with the pads below.
For ambient music, the synth has pads and textures that swell in slowly and take seconds to fade: warmpad, glasspad, darkpad, choirpad, swell, drone, air, wind, shimmer, softbell, musicbox and subbass. A note that's still fading keeps ringing when the next one starts, so chords wash into each other. Two settings make a synth sound move. detune adds a second copy of the wave a few cents higher, which makes it wider and richer. drift sweeps the filter down and back up again, slowly, at driftspeed times a second, so a long note breathes.
Programs can make songs too. newrollsong() makes a new song with six tracks. Each track has clips, and each clip holds notes like { t = step, len = steps, n = note, v = volume }, with 16 steps to a bar. The code that builds and plays songs is in /system/sound.lua, and the Music app that edits them is /system/apps/music.lua.
Game carts
A cart is a whole game in one folder. It holds the code, a sheet of sprites, a tile map, sound effects and songs. Macaw OS has an editor for each part. When the game is finished, you can pack the cart into a single .cart file (at most 256 KB) that anyone can double-click to play.
Make one
In Terminal:
newcart jumper
This makes /home/carts/jumper with a small platform game in it, and opens its main.lua in Code. Press Ctrl+R to play it. Code's Cart menu opens the cart's editors:
| Editor | What it edits | The file |
|---|---|---|
| Sprites | 256 sprites of 16x16 pixels, and 8 flags for each | gfx.pxl, gfx.flags |
| Map | Layers of tiles, where each tile is a sprite number | map.map |
| SFX | 64 sound effects | sfx.sfx |
| Music | Songs | music/*.song |
cart.info holds the cart's title, its author and a short description:
return {
title = "Jumper",
author = "me",
about = "Jump between the platforms.",
}
Sharing it
| In Terminal | What it does |
|---|---|
pack jumper | Packs /home/carts/jumper into /home/carts/jumper.cart |
unpack jumper.cart | Unpacks a cart into a folder in /home/carts, so you can look inside or change it. It won't unpack over a folder that's already there |
Double-click a .cart in Files to play it. The games in /games are cart folders too. Right-click one in Files and choose Show Contents to see how it's made.
Sprites
Sprite 0 is the top-left 16x16 square of the sheet. Sprite 1 is the next one along, and sprite 16 is the first sprite in the second row. Colour 0 is see-through.
| Call | What it does |
|---|---|
spr(n, x, y, [w], [h], [flipx], [flipy]) | Draws sprite n. w and h draw a block of sprites, so 2, 2 draws a 32x32 sprite made of four |
sspr(sx, sy, sw, sh, x, y, [scale], [flipx], [flipy]) | Draws any rectangle of the sheet, given in pixels |
sprimage(n, [w], [h]) | Returns a sprite as its own picture, so you can scale it or use it as a 3D texture |
fget(n, [flag]) | Returns sprite n's flags (0-255), or whether one flag (0-7) is set |
fset(n, [flag], value) | Sets the flags, or one flag |
Flags mean whatever you decide. The template's game uses flag 0 to mark solid tiles:
-- is the tile at this pixel solid?
local function solid(x, y)
return fget(mget(x // 16, y // 16), 0)
end
The map
The map is a grid of tiles, and each tile is a sprite number (0 is empty). A map can have several layers, such as a background, the ground and things in front. You refer to a layer by its number or its name.
| Call | What it does |
|---|---|
map([cx, cy], [x, y], [cw, ch], [layer]) | Draws cw x ch tiles of the map, starting from tile cx, cy, at pixel x, y. With no arguments it draws the whole map at 0, 0 |
mget(x, y, [layer]) | Returns the tile at x, y |
mset(x, y, n, [layer]) | Sets the tile at x, y to n |
mapsize([layer]) | Returns how many tiles the map has across and down |
The map is usually bigger than the window, so scroll it with camera:
function _draw()
cls(colors.sky)
camera(cam_x, 0) -- everything after this is drawn moved left by cam_x
map()
spr(1, player.x, player.y)
camera() -- back, for the score
text(score, 4, 4, colors.white)
end
map only draws the tiles that are inside the window, so a big map doesn't slow it down.
Maps made in Tiled come in with the Map Editor's File > Import Map (or by dropping the .tmx and its picture on it): Tiled's tile n becomes sprite n, cut from the tileset's picture into the sprite sheet. Keep Tiled's Tile Layer Format as CSV. A picture of a whole level comes in with File > Import Map from Picture: it's cut into tiles, and each different one becomes a sprite. Your own code can do the same:
| Call | What it does |
|---|---|
importmapimage(path, [tilesize]) | A picture of a level (a PNG) cut into tiles tilesize across (16 if you don't say; others are made 16 x 16): each different tile becomes a sprite, numbered in the order they're first met, and the same tile again is the same sprite. See-through tiles are 0. Returns the same as importmap |
importmap(path) | A Tiled map (.tmx, .json) or a CSV of tile numbers. Returns the map (layers as newmap makes them), a 256 x 256 picture of its tiles in their sprites' places (or nil), which sprites they fill (used[n] = true), and notes on what was left out; or nil and why |
Sound and music
| Call | What it does |
|---|---|
sfx(n, [voice]) | Plays the cart's sound effect n (0-63) |
sfx(-1) | Stops all sound effects |
music(name, [loop]) | Plays music/name.song from the cart. A number works as a name too, so music(1) plays music/1.song |
music(-1) | Stops the music |
sfx("coin") with a name still plays the built-in sounds. music.volume() and the other music chip calls work in carts too.
Handy for games
These calls work in carts and in every other program:
| Call | What it does |
|---|---|
rnd(n) | Returns a random number from 0 up to n. rnd() returns one from 0 to 1, and rnd(list) returns a random item from the list |
flr(n), ceil(n) | Rounds n down or up to a whole number |
mid(a, b, c) | Returns the middle value of the three. mid(0, x, 100) keeps x between 0 and 100 |
clamp(v, lo, hi) | Keeps v between lo and hi. It does the same job as mid, with the value first |
sgn(n) | Returns -1 if n is below 0, otherwise 1 |
lerp(a, b, t) | Returns a value part way from a to b, where t goes from 0 to 1 |
round(n) | Rounds n to the nearest whole number |
add(list, v) | Puts v on the end of a list |
del(list, v) | Takes v out of a list |
all(list) | Goes through a list with for v in all(list). You can safely del items as you go |
3D
Macaw OS has a 3D renderer for textured triangles. It has a depth buffer, a sun, up to eight lamps, and fog. On a computer with a graphics card, the card draws it at the screen's full size, sharp and smooth. Otherwise the processor draws it, in the screen's colours. Your program is the same either way.
There are three ways to use it, from the simplest to the most hands-on:
- Scenes (below). You make things once, such as a camera, a cube, a terrain or a light, then move them about, and
render()draws them all. Collisions and clicking on things are built in. Start here. - Meshes, further down. You draw each model yourself every frame, with your own camera.
- The graphics chip. OpenGL-style matrices and draw calls, for full control.
All three draw into the same picture with the same depth buffer, so you can mix them. In 3D space, x goes right, y goes up and z goes forward, away from you. Angles are in degrees.
Scenes
Type new3d world.lua in Terminal to get a scene to start from. Here's a small one:
WINDOW = { w = 240, h = 160, title = "My World", scale = 2 }
local cam = newcamera()
cam:position(0, 1.5, -6)
cam:clscolor(colors.sky)
local sun = newlight("sun")
local ground = newplane(nil, 20)
ground:scale(30, 1, 30)
ground:color(colors.green)
local box = newcube()
box:position(0, 1, 2)
box:color(colors.orange)
function _update()
if btn("left") then cam:turn(-2, 0, 0) end
if btn("right") then cam:turn(2, 0, 0) end
if btn("up") then cam:move(0, 0, 0.1) end
box:turn(1, 0, 0)
updateworld()
end
function _draw()
render()
end
Each frame, move things, then call updateworld() to work out collisions. Then render() draws everything from the camera.
Making things
| Call | What it makes |
|---|---|
newcamera() | A camera to look through |
newlight("sun") | Light from far away, like the sun. It shines the way it faces, so turn it with e:rotate to light things from another side |
newlight("point", [radius], [strength]) | A lamp that lights things within radius |
newcube([texture], [tiles]) | A 2x2x2 cube |
newsphere([segments], [texture]) | A ball |
newcylinder([segments], [texture], [capped]) | A cylinder |
newcone([segments], [texture]) | A cone |
newplane([texture], [tiles]) | A flat 2x2 square, facing up |
newterrain(cells, height, [texture], [tiles]) | Hills, 2 units across, which you scale up. height is either a picture, where brighter is higher, or a function (u, v) that returns a height from 0 to 1 for each point. u and v go from 0 to 1 across the terrain |
newmesh(verts, tris, [texture]) | Your own shape (see Meshes, below) |
newmodel(path, [textures]) | A model from an .obj file |
newsprite(picture, [height]) | A flat picture that always faces the camera, for trees and people. It's 1 unit tall unless you give a height |
newpivot() | An empty thing to group others under |
tiles is how many times the texture repeats across each face, or across the whole of a terrain.
What everything can do
| Call | What it does |
|---|---|
e:position(x, y, z, [global]) | Puts it at this place. If it has a parent, the place is measured from the parent unless global is true |
e:move(x, y, z) | Moves it relative to the way it's facing (z is forward) |
e:translate(x, y, z) | Moves it along the world's directions |
e:rotate(yaw, pitch, roll) | Turns it to face this way |
e:turn(yaw, pitch, roll) | Turns it by this much |
e:point(other) or e:point(x, y, z) | Turns it to face something |
e:scale(s) or e:scale(sx, sy, sz) | Sets its size |
e:parent(p) | Makes it move and turn with p, like a moon going round a planet |
e:pos() | Returns where it is, as x, y, z |
e:forward() | Returns the way it's facing |
e:up() | Returns the way its top is facing |
e:dist(other) | Returns how far it is from something |
e:hide(), e:show() | Stops and starts drawing it |
e:visible() | Returns whether it's drawn. It's false if it or anything it's parented to is hidden |
e:texture(picture, [n]), e:color(c) | Changes how it looks. For a model with several textures, n says which one to change (the first if you leave it out) |
e:fullbright() | Stops light shading it, for lamps, the sky and glowing things |
e:twosided() | Draws both sides of it |
e:free() | Gets rid of it |
terrain:height(x, z) | Returns the ground's height at a place |
Cameras also have cam:fov(degrees) (80 to start with), cam:clscolor(c) (or false to not clear the picture), cam:fog(near, far, [c]), cam:project(e) for where something is in the window, and cam:pick(x, y, [max]).
The rest of the scene
| Call | What it does |
|---|---|
render([camera]) | Draws everything. It uses the first camera you made unless you give it another |
updateworld() | Works out collisions for everything that moved |
collisions(a, b, [shape], [response]) | Makes things of type a bump into things of type b (see below) |
resetcollisions(e) | Forgets where e was. Call it after you move something a long way in one go, so it doesn't collide with everything in between |
pick(ox, oy, oz, dx, dy, dz, [max]) | Returns the nearest pickable thing along a ray from ox, oy, oz in the direction dx, dy, dz, or nil. With max, it ignores anything further away than that |
ambient(level) | Sets how bright the light is everywhere. It starts at 0.35 |
clearworld() | Throws the whole scene away. The next thing you make starts a new, empty one |
world3d() | Returns the scene itself. The calls above are short for its methods, so render(cam) is the same as world3d():render(cam) |
Bumping into things
Give things a collision type, which can be any number. Then say which types bump into which:
ball:collide(1, 0.5) -- type 1, a sphere of radius 0.5
wall:collide(2) -- type 2
collisions(1, 2, "mesh", "slide")
After updateworld(), a ball that ran into a wall has been pushed back out of it. ball.hits lists what it touched, with the direction the surface faces (nx, ny, nz). The third argument to collisions is the shape to test the wall as. It's "mesh" for its exact shape, "box" or "sphere". The last argument is what happens. With "slide" the ball slides along the wall, and with "stop" it stops.
Clicking on things
box:pickable() -- "mesh" (exact) or "sphere" ("box" works too, tested exactly)
local mx, my, _, pressed = mouse()
if pressed & 1 ~= 0 then
local hit = cam:pick(mx, my)
if hit then hit.entity:hide() end
end
cam:pick returns a table about what's under the pointer, or nil. It has the thing itself (hit.entity), where it was hit (x, y, z), the direction the surface faces (nx, ny, nz) and how far away it is (dist). pick returns the same table.
The demos in /games show all of this. orbit has things going round other things, flyover has terrain, fog and sprites, and gallery has clicking. marble, Marble Run, is a whole game: a marble rolling round five levels made in Brushwork (see Levels).
Meshes
To draw each model yourself, set up the frame and then draw:
WINDOW = { w = 240, h = 160, title = "Box", realtime = true }
local crate = image(16, 16)
crate:clear(colors.tan)
target(crate)
rect(0, 0, 16, 16, colors.brown)
line(0, 0, 15, 15, colors.brown)
target()
local box = cube3d(1, 1, 1, crate)
local angle = 0
function _update() angle = angle + 1 end
function _draw()
clear3d(colors.navy)
camera3d(0, 0, -3)
light3d(-1, -1, 1)
box:draw(0, 0, 0, angle, angle / 2, 0)
end
| Call | What it does |
|---|---|
clear3d([c]) | Starts a frame. It clears the depth buffer, and clears the picture to c if you give it |
camera3d(x, y, z, [yaw], [pitch], [fov]) | Sets where the camera is and which way it looks. fov is 90 unless you give it |
light3d(dx, dy, dz, [sun], [ambient]) | Sets the sun's direction and strength, and the light everywhere |
pointlight3d(n, x, y, z, radius, [strength]) | Sets lamp n (1 to 8). A radius of 0 turns it off |
fog3d(near, far, c) | Adds fog that starts at near and is solid by far. fog3d() turns it off |
m:draw([x, y, z], [yaw, pitch, roll], [scale]) | Draws a mesh |
m:drawm(a, b, c, d, e, f, g, h, i, x, y, z) | Draws a mesh with your own 3x3 transform. Each corner is multiplied by the rows a b c, d e f and g h i, then moved to x, y, z. Use it to stretch or squash a mesh, or to draw it with a rotation you've worked out yourself |
m:texture(n, picture) | Changes the mesh's texture n (from 1 to 16) |
m:size() | Returns how many corners and triangles the mesh has |
project3d(x, y, z) | Returns where a point lands in the window, as x, y, distance |
line3d(x0, y0, z0, x1, y1, z1, [col], [thick]) | Draws a line in the world, seen through the camera, over the picture. The part behind you is cut off. Use it for outlines and markers |
stats3d() | Returns how many triangles were drawn this frame |
For example, m:drawm(2, 0, 0, 0, 1, 0, 0, 0, 1, x, y, z) draws a mesh twice as wide as it is.
Making meshes:
| Call | What it makes |
|---|---|
cube3d(w, h, d, texture, [tiles]) | A box. texture can be one picture or { sides, top, bottom } |
room3d(w, h, d, floor, walls, [ceiling], [tiles]) | The inside of a box, with the floor at y = 0 |
loadobj(path, [textures]) | A model from an .obj file |
billboard3d(picture, x, y, z, [height], ["fullbright"]) | Draws a picture standing at a place, facing the camera |
mesh3d(verts, tris, [textures], [texids], [options]) | Any shape |
tiles is how many times the texture repeats across each face. With 0 it repeats once for every unit of size, which is what room3d does unless you say otherwise. cube3d shows the texture once on each face unless you give it tiles.
mesh3d takes the corners as one long list, with five numbers for each, x, y, z, u, v. u and v say which part of the texture goes at that corner, from 0 to 1 across. The triangles are three corner numbers each, counting from 1. The front of a triangle is the side its corners go round anticlockwise. The options are words in a string. "double" draws both sides, and "fullbright" ignores the light.
local tri = mesh3d({ -1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1.5, 0, 0.5, 0 },
{ 1, 2, 3 }, { crate }, nil, "double")
Textures
Any picture can be a texture. Textures repeat, and colour 0 is see-through. For photos, Macaw OS comes with a set in /system/textures, which you load with loadtexture:
local rock = loadtexture("/system/textures/rock.tex")
With a graphics card they're drawn in true colour. Without one they're drawn in the nearest of the screen's colours. Photos are kept at most 64 pixels across, which is plenty for a wall where the texture repeats. For something seen big and close, loadtexture(path, 128) keeps more detail, but it takes four times the memory.
The computers Macaw OS was made for had graphics cards with very little memory. An eMac has 32 MB, and a slot-loading iMac has 8 or 16. About and the Profiler both show how much is in use. If your program uses more than it's allowed, Macaw OS tells you once in an alert, and in Terminal each time.
The graphics card
glr is only there when a graphics card is doing the drawing, so check with if glr then.
| Call | What it gives |
|---|---|
glr.vram() | Roughly how many bytes of the card's memory are in use, how many are allowed (32 MB, or 16 MB on a Rage 128), and whether it's over |
glr.info() | A table about the card. It has renderer and version (the card's name and OpenGL version), depthbits, maxtexture (the biggest texture it takes), multitexture, cubemap (whether it can do baked reflections), extensions, and how its memory is split up (texturebytes, lightmapbytes and screenbytes) |
cubemaps() is a shortcut for glr ~= nil and glr.info().cubemap.
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
| Call | What 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
| Call | What 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:
| Call | What 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:
| Call | What 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
| Call | What 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:
- Draw the scene into a picture, from a camera mirrored in the water.
- Draw the main scene.
- Call
gpu.mask(true)and draw the water's surface. Instead of drawing colours, this marks which pixels are water. Then callgpu.mask(false). - 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
})
| Option | What it does |
|---|---|
tint, tintamount | A colour mixed in, and how much of it (0.2) |
near, far | How much it reflects close to you (0.35) and far away (0.85) |
ripple | How far the ripples bend the reflection, in pixels (1.5) |
time | The time in seconds, which moves the ripples |
flow | How fast the surface texture drifts (1) |
surface, surfaceamount | A texture for the water itself, and how much it shows (0.3) |
drops | Where drips fell, as { u, v, seconds ago } for each, up to 16. Each one sends out rings |
env | A 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).
Levels
Brushwork is the level editor. It's in the macaw menu, and double-clicking a .lvl file opens it too. You build levels the way the old first-person-shooter editors did, out of brushes. A brush is a solid convex shape like a box, wedge, stair or arch, and brushes can be added together or cut out of each other. Put in lamps and a player start, press Bake (F5) to work out the light, then Play (F6) to walk around.
File > Open Example opens a copy of one of the levels that come with Macaw OS (the Sample, the Atrium, Threefold or the Keep), so you can see how they're made. Your copy goes in /home/maps, and opening the example again never overwrites your changes.
Your own programs can load these levels and draw them quickly. A level is cut into pieces with a BSP tree and portals, so only what the camera can see gets drawn.
The levels that come with it
| File | What it is |
|---|---|
/system/maps/sample.lvl | A small room with a few brushes, a good one to start from |
/system/maps/atrium.lvl | A sunlit hall of pillars and arches around a pool |
/system/maps/keep.lvl | A fortress of rooms on three floors, about as big as a level in an old shooter |
/system/maps/threefold.lvl | A castle, an underground base and a temple, joined into one long level |
Each has its baked light next to it in a .lit file. Level Player plays any of them: /games/threefold is a cart that only opens Level Player on threefold.lvl, and you can make your own the same way.
Marble Run (/games/marble) is a game of its own made from levels. Its five courses, in /games/marble/levels, float in the sky: each is closed in by a box of faces with the sky texture, so the sky shows all round and lights the course when it's baked. Its rings are crystal entities and its finish is a goal, kinds it describes for itself in /games/marble/entities.lua (see Entities for your game). The game rolls the marble with L.lvl:tracebox.
Walking round a level
WINDOW = { w = 320, h = 180, title = "Walk", realtime = true }
local L = assert(openlevel("/system/maps/sample.lvl"))
local x, y, z, yaw = levelstart(L.lv) -- the player start's feet, and which way it faces
local HALF, HH = 0.3, 0.8 -- half the player's width, and half its height
function _update()
if btn("left") then yaw = yaw - 3 end
if btn("right") then yaw = yaw + 3 end
local step = (btn("up") and 0.08 or 0) - (btn("down") and 0.08 or 0)
if step ~= 0 then
local dx, dz = math.sin(math.rad(yaw)) * step, math.cos(math.rad(yaw)) * step
-- slide the player's box along, as far as it gets before it hits something
local f = L.lvl:tracebox(x, y + HH, z, x + dx, y + HH, z + dz, HALF, HH, HALF)
x, z = x + dx * f, z + dz * f
end
end
function _draw()
clear3d(colors.black)
camera3d(x, y + 1.5, z, yaw)
L.lvl:drawbsp()
end
openlevel loads the level (.lvl), builds it, and puts on its baked light from the .lit file next to it. It gives you back a table:
| Field | What it is |
|---|---|
L.lv | The level as a Lua table, with its brushes, entities and settings (see /system/levels.lua) |
L.lvl | The built level, which draws and collides |
L.lit | Whether its baked light was put on (false if there's no .lit, or it was baked for a different version of the level) |
L.water | Its water, if it has any (see below) |
L.probes | Its reflection probes, if it has any (see below) |
L.path | The file it came from |
Drawing
| Call | What it does |
|---|---|
L.lvl:drawbsp() | Draws what the camera can see, through the BSP and portals. This is the fast way. Returns how many leaves and faces it drew |
L.lvl:draw() | Draws all of it. With a graphics card the card keeps the whole level, so this is quick too |
L.lvl:draw{ camera = "gpu" } | Draws with the graphics chip's camera, viewport and fog instead of camera3d's |
L.lvl:draw{ above = y } | Draws only what's above a height (for reflections). L.lvl:draw(y) is short for the same thing |
Levels use the same renderer as everything else in 3D, so you can draw meshes, scenes and billboards into them for people, pickups and doors.
Bumping into it
| Call | What it does |
|---|---|
L.lvl:tracebox(ax, ay, az, bx, by, bz, hx, hy, hz) | Moves a box (half-size hx, hy, hz) with its middle going from a to b. Returns how far it gets (0 to 1), the direction nx, ny, nz of whatever stopped it, and whether anything did |
L.lvl:trace(x0, y0, z0, x1, y1, z1) | How far along a line it gets before hitting something (0 to 1, where 1 means nothing) |
L.lvl:raycast(x, y, z, dx, dy, dz) | Where a ray from x, y, z going dx, dy, dz first goes into a brush. It returns t, so the spot is x + t * dx and so on, or nil if it hits nothing. It tries every brush, so it works straight after building a level |
L.lvl:boxsolid(x0, y0, z0, x1, y1, z1) | Whether a box touches anything solid |
L.lvl:boxinside(x, y, z, hx, hy, hz) | Whether a box is inside anything |
These run in C, so they're quick enough to call many times a frame. Water isn't solid, so you can walk into it.
Water
In Brushwork, Level > Water turns the selected brushes into water. Water isn't solid, and its top is a reflecting surface. L.water is a list of those surfaces, and each one can draw itself with a reflection:
function _draw()
local cam = { x = x, y = y + 1.5, z = z, yaw = yaw, pitch = 0, fov = 90 }
for _, w in ipairs(L.water) do
w:reflect(cam, function(c, above)
camera3d(c.x, c.y, c.z, c.yaw, c.pitch, c.fov)
L.lvl:draw{ above = above }
end)
end
clear3d(colors.black)
camera3d(cam.x, cam.y, cam.z, cam.yaw, cam.pitch, cam.fov)
L.lvl:drawbsp()
for _, w in ipairs(L.water) do w:draw(cam, time()) end
end
reflect draws a live reflection. The level is drawn a second time from a camera mirrored under the water, then mixed in with ripples and the water's own drifting surface. The function you give reflect gets the mirrored camera and the water's height.
That second drawing costs time. On a slow computer you can leave it out by not calling reflect (or setting w.reflections = false), and the water becomes a plain sheet.
You can also bake the reflection instead. w:bake(draw, ray) draws six views from just above the middle of the water, one each time you call it, and returns true once all six are done. After that w:draw reflects those views and nothing gets drawn twice. draw is the same function reflect takes, and ray finds the walls around the water so they show up in the right place:
if w.env == nil then
w:bake(draw, function(...) return L.lvl:raycast(...) end)
end
Baking needs a graphics card with cube maps (cubemaps() tells you). Without one, w.env becomes false and the water stays a plain sheet. Things that move don't show up in a baked reflection.
w:draw(cam, t, how) takes an optional how. Give it "plain" for just the water's surface, or "baked" to use the baked reflection even when there's a live one.
On a PC, Level Player draws live reflections, and drops them for a while if the frame rate falls too low. On PowerPC Macs it never draws them live. It bakes them instead if the graphics card has cube maps (an eMac's Radeon does), and otherwise the water is plain (an iMac G3's Rage 128). In a web browser the water is always plain.
watercamera(c) points the graphics chip the same way as camera3d, for gpu.* drawing in the reflection. It also makes clockwise triangles the front ones.
Shiny surfaces and reflection probes
Any brush can be shiny. In Brushwork, select it and type an amount into its shine field, from 0 (not shiny) to 1 (a mirror). Polished floors look good around 0.2 to 0.4.
A shiny surface reflects the nearest reflection probe. A probe is a point in the level, and the view from there is baked into a cube map. Put probes in with the Probe tool (R). One probe per room is usually enough. Put it near the middle, at about eye height, since that's where the reflections will look most right. A surface uses the closest probe in front of it, and prefers one in the same room.
Bake in Brushwork bakes the probes too. Once the lighting is done, it bakes each probe in the lit level, and they're saved next to the level as a .prb file, with its .lit file. A level that has them opens with its reflections ready, so nothing is baked while it's being played.
In your own programs, openlevel makes the probes ready, with the ones Brushwork baked already in place. bakeprobes bakes any that weren't, like those of a level that was never baked in Brushwork. Call it once a frame until it returns true. Each call draws one of a probe's six views, so it never holds things up:
function _draw()
bakeprobes(L)
clear3d(colors.black)
camera3d(x, y + 1.5, z, yaw)
L.lvl:drawbsp()
end
Only one probe is on the graphics card at a time, the one nearest the camera, so a level can have many without filling the card's memory. Surfaces that use another probe aren't shiny until you get closer to it. When you do, the old probe is taken off the card and the new one is sent a face per frame, then its reflections fade in. Baked water works the same way. Only the nearest water's reflection is kept on the card.
To keep more on the card, call L.lvl:probelimit(n): then the n probes nearest the camera are on it (from 1 to 64), and surfaces that use any of them shine. Each probe takes about 400 KB of the card's memory, so on an eMac's 32 MB card a few are plenty. L.lvl:probelimit() gives the current limit.
L = openlevel("/home/hall.lvl")
L.lvl:probelimit(3) -- the three nearest probes reflect at once
If nothing in the level is shiny, bakeprobes does nothing and returns true straight away. Probes need a graphics card with cube maps. Without one, shiny surfaces are drawn as they are. A probe sees the level as it was when it was baked, so things that move aren't in it.
For more control, newprobe(x, y, z) makes a probe of your own. Call p:bake(draw, ray) until it returns true, the same way as w:bake, then p.env is its cube map. L.lvl:setprobes({ env, ... }) tells the level which cube maps to use (up to 64), and L.lvl:setprobes() takes them away. env:pixels() gives a cube map's six faces as bytes, and gpu.envmap(bytes, where) makes it again from them. levelprobedata and applylevelprobes(L, text) do that for a level's probes and its .prb file.
Entities for your game
Besides brushes, a level holds entities: things at a place, each of a kind (its class) with fields. Macaw OS has its own (lamps, area lights, the start and probes) and a few generic kinds any game can use:
| Class | What it's for | Its fields |
|---|---|---|
marker | A named place, for a game to find | name, angle |
pickup | Something to pick up | kind, value, respawn |
enemy | Something that gets in the way | kind, health, speed, angle |
trigger | A box: something happens when the player's in it | name, w, h, d, once, target |
sound | A sound that plays near here | file, volume, radius, loop |
sign | Words to read | text, angle |
A game can describe kinds of its own in an entities.lua in its folder. Brushwork finds it for any level in that folder or below it (/home/mygame/levels/one.lvl finds /home/mygame/entities.lua), lists its kinds in the Entity tab with the rest, and gives each field a row in Properties: a number or text to type, yes or no, a choice, a colour. You can add a field of your own to any entity there too, as name = value.
-- /home/mygame/entities.lua
return {
{ name = "coin", label = "Coin", about = "Worth a point.",
colour = "#ffd700", shape = "ring", size = 0.4, float = 0.6,
fields = {
{ "value", "number", 1, min = 0 },
{ "kind", "choice", "gold", choices = { "gold", "silver" } },
{ "spins", "bool", true },
} },
{ name = "door", label = "Door", colour = "#a06030", shape = "zone",
fields = { { "w", "number", 2 }, { "h", "number", 3 }, { "d", "number", 0.5 },
{ "key", "text", "" } } },
}
shape is how Brushwork draws it: ring, flag, ball, box, diamond, star, figure (person-sized), zone (a box w by h by d), speaker or sign. size is how big that is, and float how far over a floor it goes when you put one down (0 stands on it). A field is { name, type, default }, the type one of number (with min and max if you like), text, bool, choice (with choices), colour or angle. A kind with the same name as a generic one takes its place. The file is only read for its table, never run as part of a program.
In the game, levelentities gives you each one with all its fields, the defaults filled in:
local L = assert(openlevel(APP_DIR .. "/levels/one.lvl"))
local coins = {}
for _, c in ipairs(levelentities(L.lv, "coin")) do
coins[#coins + 1] = { x = c[1], y = c[2], z = c[3], value = c.value, spins = c.spins }
end
| Call | What it does |
|---|---|
entityclasses(path) | Returns the kinds a level at path can have: { list = { class, ... }, by = { name = class }, file = its entities.lua }. openlevel puts them in L.classes |
entityclass(classes, name) | Returns one kind (one nothing describes gets a plain box) |
entitydefaults(class, e) | Fills in the fields e doesn't have with the kind's defaults |
entityvalue(field, v) | Returns v made the field's type (or its default), and whether it fitted |
Building levels from code
Levels are Lua tables, so programs can make them too. The format is described at the top of /system/levels.lua. A brush is a box { x0, y0, z0, x1, y1, z1, tex = { six names } } or a convex shape made of planes, and it can have glowing faces (glow), be water (water = true) or be shiny (shine = 0.3). Entities are lamps (light), area lights (glowing panels, arealight), the player start (start) and reflection probes (probe), plus whatever kinds a game uses: the generic ones and its own (see Entities for your game). An entity's fields are numbers, text or true/false, and the level keeps every one.
| Call | What it does |
|---|---|
newlevel() | Returns an empty level table |
loadlevel(path) / savelevel(lv, path) | Read and write .lvl files |
buildlevel(lv) | Builds a level table into something that draws (L.lvl above) |
levelstart(lv) | Returns where the player starts, as x, y, z, angle. It's 0, 2, 0, 0 if there's no start |
levellights(lv) | Returns its lamps and area lights, ready for baking |
levelwater(lv) | Returns its water surfaces as { { x0 =, z0 =, x1 =, z1 =, y = }, ... }, for newwater |
levelprobes(lv) | Returns its probes as { { x, y, z }, ... }, for newprobe |
levelentities(lv, class) | Returns its entities of one class, like "pickup", as { { x, y, z, field = value, ... }, ... }: copies, with their class's defaults for any field the level doesn't give (a level from openlevel) |
levellitpath(path) | Returns where a level's .lit file goes |
levelskies() / levelsky(name) | Returns the skies there are, and a sky's six pictures for lvl:setsky |
leveltexture(name) | Returns the picture for one of the built-in texture names |
And on a built level:
| Call | What it does |
|---|---|
lvl:bake(lights, [options]) | Starts working out the light. The options are ambient (0.08), bounce (1, how much light bounces) and softness (0.35, the size of lamps that don't give one) |
lvl:bakestep([ms]) | Bakes for up to ms milliseconds (30 if left out). Returns whether it's done, how far it's got (0 to 1), and what it's doing |
lvl:lightdata() / lvl:setlight(data) | Gets the baked light to save it, and puts it back. setlight returns false if the light was baked for a different level |
lvl:unbake() | Back to plain shading |
lvl:setsky({ px, nx, py, ny, pz, nz }) | Puts a sky around the level, from six square pictures. lvl:setsky() takes it away |
lvl:faces() | Returns every face of the built level, with its corners, texture number and which way it faces |
lvl:stats() | Returns numbers about it, such as faces, leaves, portals, luxels, baked, drawn (faces drawn last time), shiny and probes |
/games/threefold/main.lua shows how small a cart around Level Player can be, and the Atrium and Threefold levels are worth opening in Brushwork to see how they're put together.
Apps
Programs with buttons, text boxes and lists use ui, the toolkit every Macaw OS program gets. To start one, type newapp myapp.lua in Terminal. There are three examples to read in /home/examples: greeter.lua, todo.lua and widgets.lua, which shows every widget there is.
How it works
You don't make widgets once and keep them. Instead, _draw calls them in order each frame, between ui.begin() and ui.finish(). Each widget draws itself and tells you what the person did with it. Your program keeps the values:
WINDOW = { w = 260, h = 180, title = "Settings" }
local name, loud, volume = "", false, 5
function _draw()
ui.begin()
ui.heading("Settings")
name = ui.textbox("name", name, { placeholder = "your name" })
loud = ui.checkbox("Loud", loud)
volume = ui.slider("Volume", volume, 0, 10, 1)
ui.row(2)
if ui.button("Save") then print("saved", name) end
if ui.button("Cancel") then close() end
ui.finish()
end
ui.begin() clears the window to the paper colour. Use ui.begin({ bg = false }) if you don't want that. Widgets stack down the window from the top. Tab moves between them, and Enter or Space presses the one with the focus.
Widgets
| Call | What it does |
|---|---|
ui.label(text, [colour]) | Some text |
ui.heading(text) | A heading |
ui.separator() | A line across the window |
ui.button(label, [{ w = }]) | A button. Returns true in the frame it's clicked |
ui.checkbox(label, value) | A tick box. Returns the new value |
ui.radio(label, selected) | One of a set of choices. Returns true when it's clicked |
ui.slider(label, v, min, max, [step]) | A slider. Returns the new value |
ui.textbox(id, text, [opts]) | A box to type in. Returns the new text, and whether Enter was pressed. opts can have placeholder, password and w |
ui.listbox(id, items, selected, [rows]) | A list. Returns the number of the selected item, and whether it was double-clicked |
ui.dropdown(id, items, selected) | A drop-down menu. Returns the number of the selected item |
ui.tabs(id, names, current) | Tabs along the top. Returns the current tab |
ui.progress(fraction, [label]) | A progress bar, from 0 to 1 |
ui.swatches(colour, [{ all = true }]) | Colours to pick from. With all it shows all 256 |
ui.image(picture, [scale]) | A picture. Returns true when it's clicked |
Text boxes, lists, drop-downs and tabs take an id. This is a name you choose, different for each one, so the widget can remember things between frames, such as where the cursor is or how far the list is scrolled.
A password box ({ password = true }) has a key button. It saves the password in Nestchain, or fills it in from there.
Layout
| Call | What it does |
|---|---|
ui.row(n, [weights]) | Puts the next n widgets side by side. With weights such as { 2, 1 }, the first is twice as wide as the second |
ui.space([pixels]) | Leaves a gap |
ui.group(title) ... ui.endgroup() | Draws a box with a title around the widgets in between |
ui.at(x, y, w) | Puts the next widget at exactly this place |
ui.disabled = true | Greys out the widgets that follow, until you set it back to false |
Menus
Set MENUS and the menu bar shows your menus while your window is in front:
MENUS = {
{ "File", {
{ "New", new_file, "n" }, -- label, what it does, Ctrl+key
{ "Save", save, "s" },
"-", -- a dividing line
{ "Close", close, "w" },
} },
{ "View", {
{ "Grid", toggle_grid, checked = show_grid },
{ "Zoom In", zoom_in, "=", enabled = zoom < 4 },
} },
}
MENUS can also be a function that returns the menus. Then checked and enabled are worked out again each time a menu opens.
Right-click menus
Define CONTEXT_MENU(x, y) to give your window a right-click menu. It's called with the place that was clicked and returns the items:
function CONTEXT_MENU(x, y)
return { { "Paint here", function() paint(x, y) end }, "-", { "Clear", clear_all } }
end
To open a menu from your own code, call popupmenu(items, [x, y]). Without x and y it opens at the pointer.
Dialogs
Dialogs don't pause your program. Instead they call a function when the person answers.
| Call | What it does |
|---|---|
alert(message) | Shows a message with an OK button |
confirm(question, fn) | Asks a question with OK and Cancel buttons, and calls fn() if they click OK |
askstring(prompt, default, fn) | Asks for some text, then calls fn(text) |
openfile(fn, [opts]) | Shows the Open dialog, then calls fn(path). opts can have dir and ext = { "pxl", "png" } |
savefile(fn, [opts]) | Shows the Save dialog, then calls fn(path). opts can have dir and name |
pickcolour(fn, [hex], [title]) | Shows the colour picker, then calls fn("#rrggbb") |
openfile(function(path)
picture = loadimage(path)
end, { dir = "/home", ext = { "pxl" } })
Drag and drop
| Call | What it does |
|---|---|
function _drop(paths, x, y) | Called when files are dropped on your window, at x, y: dragged from Files, or from the computer (those are put in /home/Imports first) |
pickfiles() | Asks the person to pick files from their computer (the website only). They come to your _drop(paths, -1, -1) once they're in. Returns false where it can't |
canpickfiles() | true where pickfiles works (the website) |
startdrag(paths) | Starts dragging files out of your window, to Files, the Trash, the desktop or another program |
putondesktop(path) | Puts an alias of a file, folder, program or game on the desktop, and returns the alias's file in /home/Desktop (or nil and why) |
The rest of the desktop
| Call | What it does |
|---|---|
open(path, ...) | Opens a file the way double-clicking it would. For a program, the extra arguments reach it as ARGS |
close() | Closes your window |
settitle(s) | Changes your window's title |
fullscreen(on) | Makes your window fill the screen, or puts it back |
focused() | Returns whether your window is in front |
setclipboard(s) / getclipboard() | Puts text on the clipboard and gets it back. Every program shares it, and so does the computer underneath |
getpref(key) / setpref(key, value) | Reads and changes system preferences. For example, getpref("highlight") is the highlight colour |
Files and the system
The disk
| Folder | What's in it |
|---|---|
/home | Your own programs, pictures, songs and carts |
/games | The games that come with Macaw OS |
/system | Macaw OS itself, with its programs, libraries, textures, sounds and this guide |
/prefs | Settings, saved passwords and installed extensions |
/trash | The Trash |
/ram | A place for scratch files |
/system and /games come packed with Macaw OS, so you can't change them. You can read and copy from them, but save your own files in /home. Paths always start with / and use / between folders.
| Call | What it does |
|---|---|
fs.read(path) | Returns a file's contents as a string, or nil and the reason |
fs.write(path, s) | Writes a file. It makes the file, or replaces what was there |
fs.append(path, s) | Adds to the end of a file |
fs.list(dir) | Returns a list of the names in a folder. Folders come first and end in / |
fs.exists(path) | Returns whether it's there, and whether it's a folder |
fs.info(path) | Returns its size, when it was last changed (in seconds since 1970), and whether it's a folder |
fs.mkdir(path) | Makes a folder |
fs.remove(path) | Deletes a file or an empty folder for good. It doesn't go to the Trash |
fs.rename(a, b) | Moves or renames a file or folder |
For working with paths there's basename(p) (the last part), dirname(p) (the folder it's in), joinpath(a, b) and extension(p) (such as "lua", in lower case).
Your program can keep its files next to it. APP_PATH is your program's path and APP_DIR is its folder. include("other.lua") runs another Lua file from your folder in your program's globals, so you can split a big program into several files.
To save a table, write it out as Lua and load it back in:
local function save(t)
local out = { "return {" }
for k, v in pairs(t) do out[#out + 1] = (" %s = %q,"):format(k, v) end
out[#out + 1] = "}"
fs.write("/home/mygame-save.lua", table.concat(out, "\n"))
end
local function restore()
local src = fs.read("/home/mygame-save.lua")
local f = src and load(src, "save", "t", {})
return f and f() or {}
end
When you give load an empty table as its last argument, the file runs with nothing it can call. So a save file can only hand back its values.
Lua in Macaw OS
Programs are written in Lua 5.4. You get the usual string, table, math, utf8 and coroutine libraries, and os.time, os.date and os.clock. A few things are left out so that a program can't reach the computer Macaw OS runs on:
- There's no
io,packageorrequire. Usefs.*andincludeinstead. loadonly takes Lua source, not precompiled chunks. It runs the code in your program's own globals unless you give it a different table. There's nostring.dump.debugonly hastracebackandgetinfo.
Files stay on the Macaw disk, and the only network a program can use is the Macaw network.
| Call | What it does |
|---|---|
time() | A clock in seconds, with fractions. Take one reading from another to time something |
print(...) | Writes to Terminal and the log |
markdown(text) | Turns Markdown into HTML, and also returns the first heading as a title |
split(s, [sep]) | Cuts a string into a list at each sep. Without sep it cuts at new lines |
trim(s) | Returns s without the spaces at each end |
The system
| Call | What it does |
|---|---|
sys.platform | What Macaw OS is running on. It's "windows", "web", "emac" (any PowerPC Mac on Mac OS X), "mac9" (Mac OS 9), "mac", or "unix" (the Raspberry Pi and other Linux) |
ismac() | Returns whether Macaw OS is running on a Mac (any of them) |
modkey() | Returns the name of the key that shortcuts are held with: "Cmd" on a Mac, "Ctrl" elsewhere. Text from strings already says it: a Ctrl+ in it shows as Cmd+ on a Mac |
sys.version | Which version of Macaw OS this is |
sys.fps() | The current frame rate, in frames a second |
sys.display() | The screen's width, height and colours. The colours are 8, 256 or "thousands" |
sys.volume([v]) | Returns the volume for all sound, from 0 to 1. Give it v to change it. This changes it for the whole of Macaw OS, not just your program, until someone sets it in System Preferences or Macaw OS starts again |
sys.screenshot(path) | Saves the whole screen as a PNG file at path. Returns true if it worked |
sys.title(s) | Sets the title of the window Macaw OS runs in on the computer underneath. It does nothing on Mac OS 9 |
sys.cursor(on) | Shows (true) or hides (false) the computer's own pointer over Macaw OS. It starts hidden, because Macaw OS draws its own. It stays as you leave it after your program quits, so set it back |
sys.clipboard() | Returns the text on the computer's own clipboard, or nil if there isn't any |
sys.setclipboard(s) | Puts text on the computer's own clipboard |
To change the screen's size or colours, ask with display.request (see Drawing). For the clipboard, getclipboard() and setclipboard(s) from Apps are usually the better choice. They share one clipboard with every Macaw OS program as well as the computer, and they change characters the Macaw font doesn't have into ones it does.
Busy programs
A program that takes a long time doesn't hold up the rest of Macaw OS, whether it's loading a big level, laying out a long web page, or stuck in a loop that never ends. Your code runs in slices. If it hasn't finished after 30 milliseconds it's paused, and it carries on in the next frame. While it's paused, its window says "Loading..." or "Working...", the pointer spins over it, and everything else keeps running.
You don't need to do anything to get this, and it means a long job in _init is fine. The exception is _draw, which always finishes within its frame, so keep your drawing quick.
Saved passwords
Nestchain is Macaw OS's keychain. Each program has its own, kept apart from every other program's:
| Call | What it does |
|---|---|
nestchain.set(service, account, password, [note]) | Saves a password |
nestchain.get(service, account) | Returns the password, or nil |
nestchain.has(service, account) | Returns whether there's a password saved |
nestchain.remove(service, account) | Forgets the password |
nestchain.list([service]) | Lists what's saved, as { service, account, label, changed } for each. It never includes the passwords |
A program can only have the system's own passwords if the person says so. These are the ones Dial-Up and Hotline save, and ones saved from password boxes:
| Call | What it does |
|---|---|
nestchain.request(service, account, fn) | Asks for one. The person chooses Allow Once, Always Allow or Don't Allow, then fn(password, why) is called. why is "denied" if they said no, or "none" if there's no password |
nestchain.choose(fn) | Lets the person pick one of their saved passwords for you, then calls fn(password, service, account) |
nestchain.keep(password, [{ service =, account = }], [fn]) | Asks the person what the password is for, then saves it. Your program can read it back later without asking |
Passwords are kept encrypted in /prefs. Never print one or save it anywhere else.
System Extensions
An extension is a piece of Lua with no window that loads when Macaw OS starts. You might use one for a clock in the menu bar, an item in the macaw menu, or a check for new mail every minute. To install one, drop it on Extensions (under System Tools in the macaw menu). You turn it on and off there, and the change happens straight away without a restart.
EXTENSION = { name = "Clock", version = "1.0", author = "me",
about = "The time, in the menu bar." }
local m = ext.menu("12:00", { { "Hello", function() ext.alert("Hi!") end } })
ext.every(1, function() m:settitle(os.date("%H:%M")) end)