cavernos icon indicating copy to clipboard operation
cavernos copied to clipboard

C or C++ examples?

Open Zireael07 opened this issue 5 years ago • 1 comments

See title.

Zireael07 avatar Jul 13 '20 09:07 Zireael07

I haven't tried building anything in C/C++, but it should definitely be possible. This article might be useful for building without Emscripten: https://surma.dev/things/c-to-webassembly/

It's been too long since I've built anything with C, but here's a quick attempt that might get you started. It's totally untested though and my C is pretty rusty (in both senses of the word):

struct Config {
  unsigned char columns;
  unsigned char rows;
  unsigned char reserved[254];
}

struct ScreenData {
  unsigned char should_update;
  unsigned char cell_data[65535];
}

struct CavernOS {
    struct Config config;
    unsigned char inputs[256];
    unsigned char reserved[2560];
    struct ScreenData character;
    struct ScreenData bg_color;
    struct ScreenData fg_color;
};

static struct CavernOS OS = {
  {80,20, {0}},
  {0},  // inputs
  {0},
  {0},  // characters
  {0},  // bg_color
  {1},  // fg_color
};

void* init (CavernOS *os) {
  // You could malloc some app state here and return a pointer, which the runtime will pass back to the `frame` function
  return 0;
}

void frame (CavernOS *os, void *app_state, double dt) {
  // This should set the top left cell to a smiley face
  OS.characters.cell_data[0] = 1;
  OS.characters.should_update = 1;
}

Combine that with the instructions here to build your .wasm file: https://surma.dev/things/c-to-webassembly/

Build the JavaScript host bundle using (cd host-js && ./build.sh). Finally, copy the main.js, index.html from host-js/dist, all the files from /example-rs/assets, and your .wasm file into a single directory. Update the manifest.json as necessary.

It's a bit convoluted, but only because the build scripts do all that for Rust. Check build-example-rs.sh.

Once you've got it working, all the interactions are basically just reading and writing to the OS struct on each frame. See also these docs for explanations of the interface:

https://jordwest.github.io/cavernos/api.html

If you get stuck let me know, happy to help walk you through it. Or if you manage to get it working please share, I'd love to add an example to the repo.

jordwest avatar Jul 15 '20 08:07 jordwest