Programming Macaw OS

C

Macaw OS runs programs written in C as well as Lua. It's C89, the C of the late 1980s and 1990s, with its whole standard library, plus a few later additions like // comments, long long and <stdint.h>. A C program gets its own memory with real addresses (see Memory), and its window works the same way a Lua program's does.

Your first C program

In Terminal, type:

new hello.c

That makes /home/hello.c from a template and opens it in Code. Press Ctrl+R to compile and run it. You can also double-click a .c file to run it. There's a whole game in C, Worm, at the end of this page.

#include <macaw.h>

int x = 60, y = 40;

void _update(void) {
  if (btn("left")) x--;
  if (btn("right")) x++;
}

void _draw(void) {
  cls(NAVY);
  circfill(x, y, 8, ORANGE);
}

int main(void) {
  window(160, 100, "Hello from C");
  realtime(1);
  return 0;
}

main runs once when the program starts. If the program defines _init, _update, _draw or _close, Macaw OS calls them the same way it calls a Lua program's. window(w, h, title) and realtime(1) take the place of Lua's WINDOW table.

A program with no window and no _draw is a console program. Whatever it prints shows in a window of its own, like a terminal.

#include <stdio.h>

int main(void) {
  int i;
  for (i = 1; i <= 10; i++) printf("%d squared is %d\n", i, i * i);
  return 0;
}

Programs in more than one file

Give cc every file, and a name for the program with -o:

cc main.c util.c -o game.mx

Each file is compiled on its own, then they're linked into one program. A function or global that one file uses has to be defined in exactly one of them. One marked static belongs to its own file, so two files can each have a static int count without a clash.

/* util.c */
static int calls = 0;
int twice(int n) { calls++; return n * 2; }
int calls_so_far(void) { return calls; }
/* main.c */
#include <stdio.h>
int twice(int n);
int calls_so_far(void);

int main(void) {
  printf("%d %d\n", twice(21), calls_so_far());
  return 0;
}

The .mx file is the compiled program. Double-click it, or type game in Terminal, to run it. You don't need the .c files to run it. With no -o, cc only checks that the files compile and link.

Today a .mx holds the program compiled to Lua. A faster interpreter for C is on the way, and its programs will be .mx files too. A version of Macaw OS that can't run a .mx says so instead of trying.

When something's wrong

A mistake that stops the program compiling is shown before anything runs, with the line it's on:

/home/hello.c:12: y isn't declared

So is one that stops it linking:

/home/main.c:3: twice is used but never defined (in any of the files)

A mistake while it runs, like using a NULL pointer, reading memory that malloc didn't give out or dividing by zero, stops the program with the line it happened on:

/home/hello.c:20: bad address 0x00000004: that's the null page (a NULL pointer?)

It only ever stops that program. A bad pointer can't touch anything else.

The language

All of C89 is there:

Numbers bigger than a byte are stored most significant byte first, as on a PowerPC.

A few things work differently from a C compiler on another computer:

Headers

HeaderWhat's in it
<stdio.h>printf and the rest of its family, scanf's family, and files: fopen, fclose, fgets, fputs, fread, fwrite, fseek, ftell, fflush, remove, rename and the rest
<stdlib.h>malloc, calloc, realloc and free, atoi, atof, strtol, strtoul, strtod, rand and srand (RAND_MAX is 32767), qsort, bsearch, abs, div, exit, atexit, abort and getenv
<string.h>strlen, strcpy, strcat, strcmp and their n versions, strchr, strrchr, strstr, strspn, strcspn, strpbrk, strtok, strerror, memcpy, memmove, memset, memcmp and memchr
<math.h>sin, cos, tan and their inverses, sinh, cosh, tanh, exp, log, log10, pow, sqrt, fabs, floor, ceil, fmod, frexp, ldexp and modf, and M_PI
<ctype.h>isdigit, isalpha, isspace, isprint and the rest, toupper and tolower
<time.h>time, clock, difftime, mktime, localtime, gmtime, asctime, ctime and strftime
<setjmp.h>, <signal.h>setjmp and longjmp; signal and raise
<errno.h>, <assert.h>, <locale.h>, <stdarg.h>errno, assert, setlocale and localeconv, and va_list
<stddef.h>, <limits.h>, <float.h>, <stdbool.h>, <stdint.h>size_t and NULL, INT_MAX, DBL_MAX and so on, bool, and int32_t and its friends
<macaw.h>stdio, stdlib, string and math, plus Macaw OS's own calls (below)

A file's name is looked up from the program's own folder, unless it starts with /. A file is read when it's opened, and written when it's flushed or closed, or when the program ends. Nobody can type into a program's stdin, so getchar and scanf find nothing there: use textinput instead.

Macaw OS's calls

<macaw.h> names every colour in capitals, so NAVY, ORANGE and WHITE are the same numbers as colors.navy and the rest in Lua. Its calls work the way the Lua ones of the same name do:

KindCalls
The windowwindow, realtime, redraw, close, settitle
Drawingcls, pset, pget, line, rect, rectfill, circ, circfill, tri, text, textwidth, clip
Screen memoryscreenmem (the window picture's address), screenwidth, screenheight
Picturesnewpicture, loadpicture (a .pxl or .png), freepicture, picturewidth, pictureheight, drawpicture, drawpart, drawinto
Inputbtn, btnp, mouse (three int * to fill in with the position and buttons), textinput (what's been typed since last time)
Soundsfx, play, tone, and music, which plays a song from Tracker (music(NULL) stops it)
Timenow, the seconds since Macaw OS started, as a double
Foldersfileexists, isfolder, makefolder, and listfolder, which gives the name of a folder's first, second, third ... thing
The clipboardgetclipboard, setclipboard
The networknet_connect, net_listen, net_accept, net_send, net_receive, net_readline, net_read, net_status, net_close
The systemplatform, the name of the computer Macaw OS is running on

A picture, a connection and a listener are each a number, and 0 means it didn't work. The last number you give drawpicture and drawpart is a colour to leave out, or -1 to draw every pixel. drawinto(p) draws into picture p instead of the window, and drawinto(0) goes back to the window.

The network calls never wait. net_receive takes whatever has arrived so far, and net_readline gives -1 until a whole line is there, so call them from _update. net_status is 0 while connecting, 1 when open, 2 once closed and 3 if it failed. listfolder(path, i, name, size) counts from 0, and gives 0 once there's nothing left.

Here's a program that draws straight into its window's memory:

#include <macaw.h>

void _draw(void) {
  unsigned char *pixels = (unsigned char *)screenmem();
  int w = screenwidth(), h = screenheight(), x, y;
  for (y = 0; y < h; y++)
    for (x = 0; x < w; x++)
      pixels[y * w + x] = (x ^ y) & 31;
}

int main(void) {
  window(128, 128, "Pattern");
  realtime(1);
  return 0;
}

A whole game in C

Worm is a small game written in C. It's in /home/examples/worm.c, so open it in Code and press Ctrl+R to play. Steer the worm to the red berries with the arrow keys. Each berry makes it longer, and every fifth makes it faster. It's over when the worm runs into a wall or into itself, and Enter starts another game.

It uses a lot of what's on this page:

Here's all of it:

/* Worm: a whole game in C. Steer the worm to the berries with the arrow keys. Each one
   makes it longer, and every fifth makes it faster. Don't hit the walls or yourself.
   Ctrl+R in Code compiles and runs it. The best score is kept in /home/worm.txt. */
#include <macaw.h>
#include <time.h>

#define CELL 8                    /* each square of the garden, in pixels */
#define COLS 20
#define ROWS 14
#define TOP 12                    /* the score bar's height */
#define MAXLEN (COLS * ROWS)
#define BEST_FILE "/home/worm.txt"

typedef struct {
  int x, y;
} point;

typedef struct {
  point body[MAXLEN];             /* body[0] is the head */
  int length;
  int dx, dy;                     /* the way it's going */
  int nextdx, nextdy;             /* the way the keys last said to go */
} worm;

static worm w;
static point berry;
static int score, best, over, ticks, speed;

/* the best score so far, from its file (0 if there isn't one yet) */
static int load_best(void) {
  FILE *f = fopen(BEST_FILE, "r");
  int n = 0;
  if (f) {
    if (fscanf(f, "%d", &n) != 1) n = 0;
    fclose(f);
  }
  return n;
}

static void save_best(int n) {
  FILE *f = fopen(BEST_FILE, "w");
  if (f) {
    fprintf(f, "%d\n", n);
    fclose(f);
  }
}

/* is p on one of the first n squares of the worm? */
static int on_worm(const worm *wm, point p, int n) {
  int i;
  for (i = 0; i < n; i++)
    if (wm->body[i].x == p.x && wm->body[i].y == p.y) return 1;
  return 0;
}

/* a berry somewhere the worm isn't */
static void place_berry(void) {
  do {
    berry.x = rand() % COLS;
    berry.y = rand() % ROWS;
  } while (on_worm(&w, berry, w.length));
}

static void restart(void) {
  int i;
  w.length = 4;
  for (i = 0; i < w.length; i++) {
    w.body[i].x = 8 - i;
    w.body[i].y = ROWS / 2;
  }
  w.dx = w.nextdx = 1;
  w.dy = w.nextdy = 0;
  score = 0;
  over = 0;
  ticks = 0;
  speed = 8;                      /* frames between moves */
  place_berry();
}

/* turn, but never straight back on itself */
static void steer(int dx, int dy) {
  if (dx != -w.dx || dy != -w.dy) {
    w.nextdx = dx;
    w.nextdy = dy;
  }
}

static void game_over(void) {
  over = 1;
  sfx("lose");
  if (score > best) {
    best = score;
    save_best(best);
  }
}

/* one move of one square */
static void step(void) {
  point head;
  int i, grow;
  w.dx = w.nextdx;
  w.dy = w.nextdy;
  head.x = w.body[0].x + w.dx;
  head.y = w.body[0].y + w.dy;
  grow = head.x == berry.x && head.y == berry.y;

  /* the tail moves out of the way, unless the worm is growing */
  if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= ROWS
      || on_worm(&w, head, grow ? w.length : w.length - 1)) {
    game_over();
    return;
  }
  if (grow) w.length++;
  for (i = w.length - 1; i > 0; i--) w.body[i] = w.body[i - 1];
  w.body[0] = head;

  if (grow) {
    score++;
    sfx("coin");
    if (score % 5 == 0 && speed > 3) speed--;
    if (w.length == MAXLEN) game_over();   /* the whole garden is worm */
    else place_berry();
  }
}

void _update(void) {
  if (over) {
    if (btnp("enter") || btnp("space")) restart();
    return;
  }
  if (btnp("left")) steer(-1, 0);
  if (btnp("right")) steer(1, 0);
  if (btnp("up")) steer(0, -1);
  if (btnp("down")) steer(0, 1);
  if (++ticks >= speed) {
    ticks = 0;
    step();
  }
}

static void square(point p, int colour) {
  rectfill(p.x * CELL, TOP + p.y * CELL, CELL - 1, CELL - 1, colour);
}

static void centred(const char *s, int y, int colour) {
  text(s, (COLS * CELL - textwidth(s)) / 2, y, colour);
}

void _draw(void) {
  char line[32];
  int i;
  cls(FOREST);
  rectfill(0, 0, COLS * CELL, TOP, NIGHT);
  sprintf(line, "Score %d", score);
  text(line, 2, 2, WHITE);
  sprintf(line, "Best %d", best);
  text(line, COLS * CELL - textwidth(line) - 2, 2, YELLOW);

  circfill(berry.x * CELL + 3, TOP + berry.y * CELL + 3, 3, RED);
  for (i = w.length - 1; i > 0; i--) square(w.body[i], GREEN);
  square(w.body[0], LIME);

  if (over) {
    rectfill(16, 44, COLS * CELL - 32, 36, NIGHT);
    centred("Game over", 50, WHITE);
    centred("Enter plays again", 64, SILVER);
  }
}

int main(void) {
  srand((unsigned)time(NULL));
  best = load_best();
  restart();
  window(COLS * CELL, TOP + ROWS * CELL, "Worm");
  realtime(1);
  return 0;
}

Some things to try: make the worm come out the other side when it reaches an edge instead of crashing, put a few rocks in the garden, or give it a second berry that makes it shorter.