# The app

> The entry point that opens the window, runs the frame and closes everything on every platform, how a game asks to quit, and the state that outlives a scene.

Source: https://omardev29.github.io/rmp-docs/manual/core/app.html

The app is what runs a game: it opens the window, runs one frame after another, and closes everything in the right order on the way out — on a desktop, in a browser, on a phone. A game written with scenes meets it once, in the last line of `src/main.cpp`, and after that only when it wants to quit or keep something across scenes.

## The entry point

This is the whole of `src/main.cpp` in a new game:

[src/main.cpp](https://github.com/omardev29/raylib_multiplatform/blob/982bf2a1e307c49776bff84211260703b8de6895/src/main.cpp#L1-L13)

```cpp
// Your game starts here, and this is all of it.
//
// RMP_GAME opens the window from [window] in raylib_multiplatform.toml, enters
// the scene you name, runs it every frame, and shuts everything down on the way
// out — on every target, including the two where main() is not a main() at
// all. Your work is in src/scenes/ and src/objects/.

#include <rmp/app.h>

#include "scenes/main_menu.h"

RMP_GAME(MainMenuScene);
```

[`RMP_GAME`](https://omardev29.github.io/rmp-docs/reference/macros.html#RMP_GAME) takes the type of the first scene. It opens the window from `[window]` in `raylib_multiplatform.toml`, then makes that scene and puts it on the stack, runs the stack every frame, and shuts everything down when the game ends. The window is open before the scene is made, so a texture, a font or a sheet among the scene's members loads exactly as one in `_ready()` does. There is no `InitWindow()`, no frame loop and no unloading in the game, because those were the same lines in every game and none of them was ever yours to get right.

A texture, a font or a sheet asked for before the window opens has nothing to draw: raylib's GPU calls have nowhere to go yet. That is a load at namespace scope, or in the constructor of a global. The framework names the first one, once, when the window opens: `ASSETS: 'hero.png' was loaded before the window opened, so it has nothing to draw`; in a debug build that is on the screen too, and a CI boot fails on it. Load it in a scene.

It also writes the entry point the platform expects, and the platforms do not agree on what that is. The difference between them is who owns the frame loop:

| Platform | What `RMP_GAME` writes |
|---|---|
| Windows, Linux, macOS, the BSDs, Android | A `main()` with the frame loop in it: the game owns the loop. On Android, raylib's own entry point calls that `main()`. |
| The web | A `main()` that hands each frame to the browser: the browser owns the loop. |
| iOS | The three callbacks UIKit calls instead of a `main()`: UIKit owns the loop, and there is nothing to return to. |

The web is a loop the browser runs and not a `while` loop for a reason that costs real bytes. A loop that never returns would freeze the page, and the only way to run one there is Emscripten's `ASYNCIFY`, which instruments every function that might be on the stack — most of them — and makes the whole program larger and slower whether or not it ever waits. Handing each frame to the browser is what lets the web build go without it.

### Why the first scene is named in code

Naming the first scene in the `.toml` would mean looking it up by a string, and a string-to-type lookup in C++ is built from objects that register themselves when the program starts. In a static library, and in the prebuilt framework iOS links, the linker throws away any object file nothing refers to — and a self-registering object is exactly that. It would not fail to compile; it would work on your desktop and find no scenes on the phone. So the scene is named where a C++ program starts, in `main.cpp`, where the linker can see it.

A program with no entry point, or with two, is a link error that names the symbol `rmp_entry_point_is_declared_exactly_once`: missing, or defined twice. The linker's own complaint about `main` comes with it, and on its own it says neither what to write nor which file to look at. The framework asks for the symbol from a static initializer, the one kind of code every linker keeps, so the name is there even when the linker discards everything else unused.

## Before the first scene

Before your first scene exists, the app:

1. tells the asset layer where `resources/` is;
2. seeds [`rmp::random`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-random.html) from the clock, so a shipped game plays a different sequence every launch;
3. switches on `[dev] strict` when the build is a debug build and the `.toml` asks for it;
4. in a debug build, has the warnings the framework says once in the log shown on screen as well, as [notices](https://omardev29.github.io/rmp-docs/manual/modules/ui.html#the-frameworks-warnings-on-screen);
5. on iOS, moves into the app bundle, where the resources are; in a release build on a desktop, moves into the executable's folder when there is a `resources/` folder in it (see [where a release finds its files](https://omardev29.github.io/rmp-docs/manual/core/app.html#where-a-release-finds-its-files));
6. opens the asset pack if there is one, so that a scene can load files from its first line;
7. opens the window: always resizable, with vsync when `[window] vsync` is on, capped at `[window] fps` when that is not 0 (except on the web and iOS, which pace the frame themselves), at `[window] width` by `height`, titled `[window] title`;
8. puts your first scene on the stack, which runs its `_ready()`.

So a scene's `_ready()` always runs with the window open and the assets available, which is why it is where a scene loads what it draws. Once that first `_ready()` has returned, the app turns raylib's exit key off, so that Escape belongs to the game; see [the Escape key](https://omardev29.github.io/rmp-docs/manual/core/app.html#the-escape-key).

### Where a release finds its files

A release build reads its files from `./resources/`, and `.` is whatever folder the game was started from: a file manager, a shortcut or a terminal somewhere else would leave it loading nothing. So on Windows, Linux, macOS and FreeBSD a release moves into the folder the executable is in before anything is loaded, when that folder holds a `resources/`. The game starts the same from anywhere, and plain raylib calls with relative paths, such as `LoadTexture(RMP_RESOURCES_PATH "x.png")`, find their files too.

When the executable's folder has no `resources/` — a release built in the project and started from the project's root, with the executable in `build/release/` — the game keeps the folder it was started from and says so in its log. On NetBSD and OpenBSD raylib's `GetApplicationDirectory()`, which the framework asks, has no code and answers nothing, so a release there always reads `resources/` from the folder it was started from, and logs that it does. The web, Android and iOS read the copy packaged with the game and never need it.

## The frame

Every frame runs the same steps in the same order, and the order is the contract — it is what every property of the [scene stack](https://omardev29.github.io/rmp-docs/manual/core/scenes.html) is built on:

1. **Input.** The keyboard, the mouse — whose position raylib also takes from the first touch — and the first gamepad are read once, before anything of the game runs, and the UI starts its frame. Reading once is what stops two scenes in the same frame disagreeing about what is held down.
2. **Update**, from the bottom of the stack upwards, for every scene that is running. For each one: the pointer is offered to its objects ([`on_click`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#on_click), [`on_drag`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#on_drag)), then the scene's [`_update()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#_update) runs, then its [objects](https://omardev29.github.io/rmp-docs/manual/core/objects.html#the-frame-of-an-object) update and move, then the [collision pass](https://omardev29.github.io/rmp-docs/manual/core/collision.html) resolves where they ended up, and last the [camera](https://omardev29.github.io/rmp-docs/manual/core/camera.html) follows.
3. **Draw**, from the bottom upwards, for every scene that is visible. The screen is cleared with the background of the lowest of them; then for each scene its map and its objects are drawn through its camera, and its own [`_draw()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#_draw) runs after, in screen space. The [notices](https://omardev29.github.io/rmp-docs/manual/modules/ui.html#notices) go last, over everything.
4. **Present.** The frame goes to the screen and the UI ends its frame.
5. **Deferred work.** Objects destroyed during the frame are freed, and the scene changes asked for during the frame are applied, in the order they were asked for.

After each frame the music that is playing is fed, whatever else is going on — under a pause menu too, since a streamed track that is not fed stutters.

### delta

Every `_update(float delta)` receives the seconds the last frame took. Real time has no ceiling: drag the window, stop at a breakpoint, let a disk stall, and a frame comes back half a second long. A bullet moving 900 units a second then moves 450 units in one step, straight through a wall it never overlapped.

So `delta` is clamped to `[app] max_delta`, a twentieth of a second by default. A frame that really took longer arrives as that, and the game runs a moment of slow motion instead of teleporting through the level: nobody minds a hitch, and everybody minds falling out of the world. Setting `max_delta = 0` switches the clamp off. A negative reading, which a clock can produce across a suspend, arrives as 0.

The first frame's `delta` is 0, because raylib has no previous frame to measure from.

### The frame rate

With `[window] vsync` on, the default, each frame waits for the screen's refresh, which paces the game at the display's rate. `[window] fps` caps it, for a desktop without vsync. The browser and iOS pace the frame themselves and ignore `fps`; never call `SetTargetFPS()` in a game that builds for the web, where a wait inside the browser's frame would only stall it.

## A window of another size

`[window] width` and `height` are the *design* size: what the game is drawn for. The window, though, can be resized, a phone's screen is whatever it is, and a monitor may be 21:9. `[window] stretch` says what the world does in a window that is not the design size. Below, *s* is how much bigger the window is than the design — `min(window width / design width, window height / design height)`, the most the whole design fits:

| `stretch` | The world |
|---|---|
| `"none"` | At 1:1 around the camera: a bigger window shows more of it and a smaller one less, and nothing is scaled. |
| `"letterbox"` | The design, scaled by *s* and centred; the rest of the window is bars of the clear colour. Every player sees the same part of the world, the interface stays inside it, and nothing is cut off: a court, a board, a single screen. |
| `"expand"` | Scaled by *s* like `letterbox`, with no bars: more of the world shows the way the window is longer than the design — above and below on a 4:3 monitor for a 16:9 design, at the sides on a 21:9 one. For a level that scrolls anyway, where seeing further is fine. |

The framework's `.toml` says `letterbox`, and so does every game `rmp new` makes from it. A `.toml` without the line gets `none`.

```toml
[window]
stretch = "expand"
```

[`rmp::app::stretch()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-app.html#stretch) is the mode in use, starting from the `.toml`'s, and [`rmp::app::set_stretch()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-app.html#set_stretch) changes it from anywhere, at once: the next thing that asks sees the new one. The `.toml` is the place for a game's own mode. The framework's examples share one `.toml`, so the ones that need another set it in their first scene's `_ready()`:

```cpp
rmp::app::set_stretch(rmp::app::Stretch::EXPAND);
```

Everything that places the world follows the mode, and nothing in a scene has to ask which one is on: the [camera](https://omardev29.github.io/rmp-docs/manual/core/camera.html#the-window-is-not-the-design-size), with `view()`, `to_world()` and the `raylib()` camera a game draws with; `rmp::input::pointer()` and a click on an object, which go through it; and [the interface](https://omardev29.github.io/rmp-docs/manual/modules/ui.html#scale-and-design-units), which keeps inside the game's area. [The stretch example](https://omardev29.github.io/rmp-docs/examples/scenes/02_stretch.html) is a court in all three modes, with a key and a button to go round them and a window to resize.

Android and a Linux consoleOn [Android](https://omardev29.github.io/rmp-docs/manual/platforms/android.html), and on [a Linux console](https://omardev29.github.io/rmp-docs/manual/platforms/linux-console.html) with no desktop, every mode is a letterbox. raylib keeps the window at the size `InitWindow()` asked for there and scales that to the display itself, so the framework never sees a window of another shape: `expand` shows no more of the world, and `none` is letterboxed too. The desktop and the web follow the mode.

## Quitting

```cpp
if (rmp::ui::button("Quit")) rmp::app::quit();
```

[`rmp::app::quit()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-app.html#quit) can be called from anywhere — a menu, a callback, ten calls deep in your own code — and it *returns*. It raises a flag that the app checks before the next frame, so the frame you are in finishes normally, and then the game shuts down exactly as it does when the window's close button is pressed. A second call does nothing.

That is the reason not to call `std::exit()` instead: it ends the process on the spot, so nothing is shut down, the window is not closed properly, and on Android the app's activity is left behind while its process disappears. It is not an exception either. Exceptions are switched off in plenty of game builds, unwinding through raylib's C code is undefined, and throwing in the middle of a frame would leave a frame and a UI pass half open. A flag costs one check a frame and cannot leave anything half done.

[`rmp::app::quit_requested()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-app.html#quit_requested) says whether it has been called, for code that wants to skip work on the way out.

### Per platform

| Platform | What `quit()` does |
|---|---|
| Desktops and the web | The frame loop ends after this frame, and the game shuts down. |
| Android | The same, and the app's activity is finished, so that it goes away instead of leaving an empty task in the recent apps. |
| iOS | Nothing. It logs a warning, once, and returns — except in a debug build with `[dev] strict = true`, where that warning aborts the app instead. |

iOS is not an oversight. Apple's guidance is that an app which ends itself "will appear to the user to have crashed", App Review rejects apps that crash or appear to, and a quit control fails Apple's interface guidelines by itself. So the same code ships everywhere, and on an iPhone the call is inert and says so: `APP: quit() does nothing on iOS … Apple rejects apps that terminate
themselves (QA1561). Ignoring.` If a dead button bothers you, leave it out of the iOS build — which is what the menu of a new game does:

```cpp
#if !defined(PLATFORM_IOS)
if (rmp::ui::button("Quit")) rmp::app::quit();
#endif
```

[iOS](https://omardev29.github.io/rmp-docs/manual/platforms/ios.html) has the rest of what is different there.

### The Escape key

Escape does not close the game. raylib's `InitWindow()` makes Escape its exit key, which ends the frame loop when it is pressed, and in a game Escape means "back" or "pause": [`rmp::ui`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html) goes back on it, and the standard `ui_cancel` action is bound to it. So the app turns the exit key off, on every platform, right after the ready hook — the first scene's `_ready()` with `RMP_GAME`, your `on_ready()` with `RMP_ENTRY_POINT` — because that is where the window has just opened. The window's close button still closes it: that is the window asking, not a key.

Because it happens after the ready hook, a `SetExitKey()` of your own there is overwritten. A game that wants a key to quit says so where it reads its keys, and `rmp::app::quit()` shuts down the same way the close button does:

```cpp
if (IsKeyPressed(KEY_ESCAPE)) rmp::app::quit();
```

Every backend goes through the exit key: raylib 6.2's Win32 backend closes on it and not on Escape by name, and the framework's copy of raylib is patched where the DRM backend did not — its terminal keyboard hands a lone Escape to the game instead of to the exit check, a patch listed in `thirdparty/raylib/PATCHES.md`.

## The way out

However the game ends — `rmp::app::quit()` or the window's close button — the shutdown is the same, and its order matters, because a texture released after the window is closed is a write into a graphics context that no longer exists:

1. Every scene leaves the stack, top down, getting its [`_end()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#_end), and its objects are destroyed after it, each getting theirs.
2. Every [global](https://omardev29.github.io/rmp-docs/manual/core/app.html#rmp-global) is destroyed, in the reverse of the order they were first used.
3. The UI's font, the sounds that are playing, and every texture, font and sound still held are released.
4. The window closes.
5. The sound device and the asset pack, which own nothing on the graphics card, close last.

Everything that owns something on the graphics card goes while the window is still open, so a scene or a global that holds an [`rmp::Texture`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#Texture) as a member releases it safely without anyone writing an unload.

## State that outlives a scene

A scene owns its state and loses it when it leaves the stack. That is exactly right for the enemies of a level and exactly wrong for the player's best score. The second kind has one home, [`rmp::global<T>()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#global):

[examples/scenes/01_stack/include/progress.h](https://github.com/omardev29/raylib_multiplatform/blob/982bf2a1e307c49776bff84211260703b8de6895/examples/scenes/01_stack/include/progress.h#L1-L10)

```cpp
#pragma once
// State that has to survive a scene change lives in exactly one place. A scene
// owns its state and loses it on the way out, which is right for the enemies
// and wrong for the score. Every scene reaches this through
// rmp::global<Progress>(), and there is exactly one for the life of the app.
struct Progress {
    int best_score = 0;
    int runs = 0;
};
```

```cpp
++rmp::global<Progress>().runs;

Progress &progress = rmp::global<Progress>();
if (score > progress.best_score) progress.best_score = score;
```

[The scene-stack example](https://omardev29.github.io/rmp-docs/examples/scenes/01_stack.html) keeps its best score this way, across a menu, a game and a pause overlay.

There is one instance per type, built the first time it is asked for and destroyed by the framework on the way out, before the window closes. The type is the key: there is no registration, no name and no lookup, and the type knows nothing about it — no `instance()` method, no private constructor, no macro. Any type with a default constructor works, including a plain struct written a minute ago.

It is called `global` because that is what it is, and a softer name would get used for things that should have been passed as arguments — to a scene's constructor, for instance, which is how a [level number](https://omardev29.github.io/rmp-docs/manual/core/scenes.html#passing-data-to-the-next-scene) crosses a transition. Reaching for it should be a decision, not a habit.

A global lives in memory for as long as the app runs; it is not saved anywhere. Keeping the best score between launches is the job of [`rmp::save`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-save.html); see [Saving](https://omardev29.github.io/rmp-docs/manual/modules/saving.html).

A global first asked for while the globals are being destroyed — by a destructor that reaches for one late in the shutdown — is still a working object, but it is never destroyed by the framework, and the log says so once: `GLOBAL: a global was created while the globals were being destroyed; it
will not be destroyed by the framework.`

## Without scenes

`RMP_GAME` is built on a lower-level entry point, [`RMP_ENTRY_POINT`](https://omardev29.github.io/rmp-docs/reference/macros.html#RMP_ENTRY_POINT), which takes three functions of yours instead of a scene and runs them on the same platform runners:

```cpp
static void on_ready() {
    SetConfigFlags(FLAG_WINDOW_RESIZABLE); // before InitWindow, or it is ignored
    InitWindow(RMP_WINDOW_WIDTH, RMP_WINDOW_HEIGHT, RMP_WINDOW_TITLE);
}

static void on_frame(float delta) {
    BeginDrawing();
    ClearBackground(RAYWHITE);
    DrawText(TextFormat("%.1f ms", delta * 1000), 20, 20, 20, DARKGRAY);
    EndDrawing();
}

static void on_exit() { CloseWindow(); }

RMP_ENTRY_POINT(on_ready, on_frame, on_exit);
```

There is no scene stack and no objects, and the window and the drawing are yours: the hooks are `on_` and not `_` because they are functions you hand over. What the platform runners do around them is the same as for `RMP_GAME` — the asset pack opened before `on_ready` and closed after `on_exit`, a release moved next to its `resources/`, the exit key turned off after `on_ready`, the input devices read once before each `on_frame`, so that [`rmp::input`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-input.html)'s actions and [`pointer_screen()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-input.html#pointer_screen) work in it as they do in a scene, the same clamped `delta`, the same `quit()`, the music fed every frame. What `RMP_GAME` adds is the part that reads `[window]`: with `RMP_ENTRY_POINT`, vsync and the frame cap are yours to set, like the window.

In a scene, [`pointer()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-input.html#pointer) is the pointer in world units, converted through the current scene's camera. With no scene on the stack there is no camera to go through, so here it is the position on the screen, the same as `pointer_screen()`, and it says nothing about it: either one works in a game without scenes.

The UI examples are written this way, because a menu needs no scene. Plain C is one step further down: [Plain C](https://omardev29.github.io/rmp-docs/manual/raylib/plain-c.html) is a game with its own `main()`, raylib, and no framework library: what it keeps of the framework is the build, the `.toml`'s values from `rmp/config.h` and the C hooks CI boots it with.
