Expand description

Craydate

This crate and its related crates together provide a safe Rust API for the Playdate hand held gaming system. It is built on the Playdate C Api.

The name is crustacean pun, with our dear friends the crayfishes.

Requirements

Using these crates requires the Playdate SDK, which has its own license. Install the SDK and add an environment variable named PLAYDATE_SDK_PATH that points to the directory where you installed it, such as PLAYDATE_SDK_PATH=C:\playdate.

This crate uses unstable features in order to provide a #![no_std] application to run on the Playdate simulator and hardware device. Thus it requires use of the Rust nightly compiler.

Getting Started

Building a #![no_std] application that is compiled for the Playdate simulator requires a bit of extra Cargo setup, which we try to make easy for you. The dependency structure of your project will look like this:

- your-game-project**
  ├── [dependencies] your-game** (`#![no_std]` crate)
  |   ├── [dependencies] craydate (`#![no_std]` crate)
  |   └── [dependencies] euclid (with `default-features = false` and `features = ["libm"]`)
  └── [build-dependencies] craydate-build
 
** = is specific to your game and provided by the game developer.

Note that your game’s crate must include the #![no_std] directive in its crate root in order to build for the Playdate device.

The euclid crate is used in the craydate public Apis, which is why you will need it. The features listed above are specified to make the crate compatible with a #![no_std] application.

If you choose not to use the root project crate talked about below, then you do not need the craydate-build in [build-dependencies], but will be responsible to build the pdx image and install it yourself.

The root project crate

We provide an template of a root project crate at craydate-project, which will act as the coordination point to build your game for the Playdate simulator and the Playdate device. To use it, please rename and customize it for your game.

To start using it, download the latest release, unzip it and edit it as follows. See below for more details.

  1. Ensure your PLAYDATE_SDK_PATH environment variable is set to the location of the Playdate SDK.
  2. In the Cargo.toml file, change the name to include your game’s name, such as foo-project for the game crate foo.
  3. In the Cargo.toml file, change the game dependency’s package and path to point to your game’s crate.
  4. In the Cargo.toml file, if you want to use it, change the game-assets dependency’s package and path to point to your game’s asset-generating crate (when you have one, you can leave it commented out with a # for now).
  5. If you have a game-assets dependency for generating assets, uncomment and fix the call to it from src/bin/make_pdx.rs (when you have one, you can ignore this for now).
  6. If you have a game-assets dependency for generating assets, uncomment “game-assets” in the bins feature (when you have one, you can ignore this for now). It would look like bins = ["craydate-build", game-assets"].

Development Workflow

To build your game for the Playdate simulator, simply build your customized root project your-game-project crate with the Cargo --lib flag, which will build your game as a dependency.

After building the game, the root project crate (if based on craydate-project) includes 2 binaries to help you get it onto the Playdate simulator or a hardware device. Build them by building your root project your-game-project crate with the Cargo --bins flag. The binaries are:

  • make_pdx
  • run_simulator
make_pdx

Combines your built game, along with any asset files into a pdx image for the device or simulator.

The your-game-assets dependency seen above is an optional place to construct and collect assets for your game that will be included by make_pdx when building the game’s pdx image. To do so, edit the make_pdx.rs file to call your-game-assets. Assets should be collected into env!("PDX_SOURCE_DIR"). For example:

  your_game_assets::generate_assets(env!("PDX_SOURCE_DIR"))?;

The make_pdx binary would then include those assets into your game’s pdx image.

run_simulator

Runs the Playdate simulator, loading the pdx image generated by make_pdx.

VSCode

We provide configurations for VSCode in the template root project craydate-project to build and use the make_pdx and run_simulator binaries correctly. The .vscode/settings.json file configures these tasks. You should not need to change the configuration unless you move the .vscode directory out of the root project crate.

  • The "projectRootCrate" variable should point to the root project crate. By default, since the .vscode directory is inside that crate, it is ".".
  • The "rust-analyzer.linkedProjects" variable should point to the root project crate’s Cargo.toml file. By default it is "./Cargo.toml".

When running the simulator with this task, VSCode will capture the stdout and stderr output of the game and write it to a file called stdout.txt in the project’s root directory.

Panics

The Cargo.toml for the root project crate must also set panic = "abort". This is included in the template root project craydate-project crate:

[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"

Otherwise you will get a compilation error:

error: language item required, but not found: `eh_personality`
  |
  = note: this can occur when a binary crate with `#![no_std]` is compiled for a target where `eh_personality` is defined in the standard library

Your first game

Your game’s crate must include a function that will be called after the Playdate system initializes. This function should contain your game’s main game loop. It’s simplest form would look like:

#[craydate::main]
async fn main(api: craydate::Api) -> ! {
  let events = api.system.system_event_watcher();
  loop {
    match events.next().await {
      craydate::SystemEvent::NextFrame { inputs, .. } => {
        // Read inputs, update game state and draw.
      }
      _ => (),
    }
  }
}

Then, handle the various events that can be returned from next(). In particular, handle input, update game state, and draw to the screen when the SystemEvent::NextFrame event happens. You can access the Playdate device through the craydate::Api parameter to main().

Logging to the Playdate simulator’s console, for debugging, is possible through the craydate::log() and craydate::log_error() functions.

Platforms

Currently the craydate project only supports development for the Windows simulator. We will expand support to the Playdate hardware device once we get access to one. Simulators on other platforms (e.g. Mac) are possible, and would only need changes to the root project crate.

  • The “osx.craydateHostTarget” setting may need to change if you’re working on an ARM-based mac.
  • The “linux.craydateHostTarget” setting hasn’t been tested to see if it’s correct.
  • A MacOSX simulator build has not been tested and may not link.
  • A Linux simulator build has not been tested and may not link.
  • There’s no VSCode task to install the pdx on a Playdate device yet.
  • The build for a Playdate device has not been tested yet and may not load at all.

License

This project is licensed under either of

  • Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
  • MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Craydate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Macros

Reexport some of alloc, since things in alloc are not guaranteed to work in no_std as it all depends on our global allocator. This makes it clear they can be used, and avoids the need for extern crate alloc elsewhere. Creates a String using interpolation of runtime expressions.

Structs

A sentinel that marks a font as the currently active font. Destroying this object will unset the font as current.

Apis used to access the Playdate device’s display, sound, files, clock, menus, etc.

A buffer of audio data which can be played with a SamplePlayer or as part of a MIDI Instrument in a Synth.

A bitmap image.

Information about a single bitmap, used in testing for collision between two bitmaps opaque pixels.

Metadata for an Bitmap.

Provide readonly access to the pixels in an Bitmap, through its BitmapData.

Provide mutable access to the pixels in an Bitmap, through its BitmapData.

A borrow of a Bitmap (or SharedBitmap) is held as this type.

The state of all buttons, along with changes since the last frame.

A builder pattern to construct a callback that will later be called when SystemEvent::Callback fires. Connects a closure to a Callbacks object which can later run the closure.

A CallbackBuilder which includes an argument passed from the system to the callback.

A SoundSource that is a user-defined function that writes to the audio buffer directly.

Provides an API to run a closure tied to a callback when the SystemEventWatcher reports a callback is ready to be run via SystemEvent::Callback. This type uses its type argument T to define the values that the caller will pass along to the closure when running it.

A floating point value that is clamped to be within LOW and HIGH.

Holds a reference on an Bitmap that was placed into the context stack. The reference can be used to retrieve that Bitmap on a future frame, after it is released.

A Control signal object is used for automating effect parameters, channel pan and level, etc.

A DelayLineTap provides signals that modulate a DelayLine at a position.

Access to the details and configuration of the Playdate device display screen.

An Envelope is used to modulate sounds in a Synth.

Access to the file system of the Playdate device.

An error performing an operation on a filesystem path.

A filesystem timestamp, which can represent when a file or folder was last accessed, modified, etc.

FilePlayer is used for streaming audio from a file on disk.

Font which can be used to draw text when made active with Graphics::set_font().

Information about a specific character’s font glyph.

Information about a set of 256 chars.

A sentinel that marks a bitmap acting as the stencil for drawing. Destroying this object will unset the bitmap as the stencil.

Access to drawing functions to draw to the Playdate device’s screen.

The system’s high resolution timer. There is only one timer available in the system.

The set of all input state and/or changes since the last frame.

Instrument collects a number of Synth objects together to provide polyphony.

An Lfo (Low-frequency oscillation) is used to modulate sounds in a Synth with a function.

A system menu item. The game can specify up to 3 custom menu items in the system menu.

The OnePoleFilter is a simple low/high pass filter, with a single parameter describing the cutoff frequency: values above 0 (up to 1) are high-pass, values below 0 (down to -1) are low-pass. A OnePoleFilter acts as a SoundEffect which can be added to a

A pattern is 8x8 bits of data that repeats over a surface. The pattern includes two pieces of data: 8x8 pixels of black/white colors, and an 8x8 mask which is used to draw the pixel color or omit it. Together this forms an 8x8 tri-state of (draw black, draw white, draw nothing).

A single pixel’s color, either black or white.

A span of time with a relative (signed) start and end.

An error when trying to rename a file or folder, which comes with additional context.

A SamplePlayer will play an AudioSample.

Represents a MIDI music file, as a collection of SequenceTracks that can be played together.

A SequenceTrack plays (multiple at a time) notes on an Instrument as part of a full Sequence, which represents a MIDI file.

Access to the speaker and headphone outputs of the Playdate device, along with the audio clock.

A channel is where sound is played to, once it has been added to the system via Sound::add_channel(). Sounds can be played into a SoundChannel by attaching a SoundSource with add_source().

A SoundEffect can be attached to a SoundChannel to filter/mutate the sound being played on it. They all include a mix modulator that allows adjusting how much to mix the SoundEffect into the channel, between replacing the existing signal or leaving it unchanged.

A SoundSource produces sound that can be played into a SoundChannel, thus playing to the device’s sound outputs.

A volume with two channels: left and right.

Reexport some of alloc, since things in alloc are not guaranteed to work in no_std as it all depends on our global allocator. This makes it clear they can be used, and avoids the need for extern crate alloc elsewhere. A UTF-8–encoded, growable string.

A collection of Synth objects make up an Instrument used to play a MIDI Sequence.

The implementation of a generator for a Synth.

A virtual function pointer table (vtable) that specifies the behaviour of a SynthGenerator.

Parameters for the SynthGeneraterRenderFunc.

A SynthSignal represents a signal that can be used as a modulator for a Synth.

Access to Playdate device’s system resources such as the menu, clock, battery state, and system settings.

An object used to watch for the next system event. Call next() to get the next event when it is ready.

The difference between two TimeTicks.

A span of time with an absolute (unsigned) start and end.

Represents the current device time, which is a monotonically increasing value.

A MIDI note which is played as part of a SequenceTrack in a SequenceTrack.

A mutable Bitmap that is not owned by the application, so can only be used as a borrowed BitmapRef.

A Bitmap that is not owned by the application, so can only be used as a borrowed BitmapRef.

A three-dimensional vector.

A Video file that can be rendered into the display or a Bitmap.

A volume, which is a value between 0 and 1. Setting it to a value outside the valid range will result in the value being clamped to within 0 and 1.

Represents a wall-clock time.

Enums

The state of the auto-lock system.

The set of input buttons.

Events which describe changes in state for a button.

The current state of a button, which indicates if the player is holding the button down or not.

Represents a method used for operations that draw to the display or a bitmap.

The status of the crank input device.

Whether using the crank makes sounds when docked or undocked.

The Error type for all errors in the craydate crate.

Information about a file path in the filesystem.

The state of the headphone jack.

A span of time for sound to loop over.

A range of MIDI notes, which can include all notes, a single note, or a contiguous set of notes.

Playdate device system events.

Constants

Traits

Provides explicit access to a type’s SoundSource methods when it can act as a SoundSource.

Provides explicit access to a type’s SynthSignal methods when it can act as a SynthSignal.

Reexport some of alloc, since things in alloc are not guaranteed to work in no_std as it all depends on our global allocator. This makes it clear they can be used, and avoids the need for extern crate alloc elsewhere. A generalization of Clone to borrowed data.

Functions

Log a string to the Playdate console, and to stdout.

Prints an error string in red to the Playdate console, and pauses Playdate. Also prints the string to stdout.

A helper implementation of panic_handler for the toplevel crate to forward to.

Returns the number of bytes per sample frame for the SoundFormat.

Returns whether a SoundFormat is 16 bit. Otherwise, it is 8 bit.

Returns whether a SoundFormat is stereo. Otherwise, it is mono.

Type Definitions

A callback builder for a closure to be called on headphone change events.

A callback builder for a closure to be called on menu events.

A callback builder for a closure to be called on sound completion events.

Attribute Macros

A game crate should annotate their game loop function with this attribute macro.