diff --git a/README.md b/README.md index 161acd7..2aef170 100644 --- a/README.md +++ b/README.md @@ -17,11 +17,11 @@ This repository contains multiple packages with separate [releases][github-relea ## Documentation -The full documentation can be found at: [https://nanoforge-dev.github.io/docs/engine](https://nanoforge-dev.github.io/docs/engine) +The full documentation can be found at: [https://docs.nanoforge.eu/docs/engine/getting-started/index](https://docs.nanoforge.eu/docs/engine/getting-started/index) ## Usage -To use Nanoforge Engine, please refer to the [CLI documentation][cli-source] ! +To use Nanoforge Engine, please refer to the [CLI documentation][cli-docs] ! First, install the CLI : @@ -37,18 +37,17 @@ nf new ## Packages +- `@nanoforge-dev/asset` ([source][asset-source]) - The built-in asset library, to read the files shipped with a game - `@nanoforge-dev/common` ([source][common-source]) - Common interfaces and utilities used by Nanoforge Engine -- `@nanoforge-dev/core` ([source][core-source]) - A core package that contains game main loop -- `@nanoforge-dev/ecs-lib` ([source][ecs-lib-source]) - A powerful data structure for managing game entities (_do not use this in your projects_) -- `@nanoforge-dev/ecs-client` ([source][ecs-client-source]) - A wrapper of `@nanoforge-dev/ecs-lib` for client-side usage -- `@nanoforge-dev/ecs-server` ([source][ecs-server-source]) - A wrapper of `@nanoforge-dev/ecs-lib` for server-side usage -- `@nanoforge-dev/config` ([source][config-source]) - A wrapper of `class-validator` and `class-transformer` to imports validation and transformation decorators +- `@nanoforge-dev/core` ([source][core-source]) - A core package that creates the application and runs the game loop +- `@nanoforge-dev/env` ([source][env-source]) - A wrapper of `class-validator` and `class-transformer` to validate environment variables +- `@nanoforge-dev/ecs` ([source][ecs-source]) - A powerful data structure for managing game entities, for the client and the server +- `@nanoforge-dev/editor-lib` ([source][editor-source]) - The bridge between a running game and the NanoForge editor - `@nanoforge-dev/graphics-2d` ([source][graphics-2d-source]) - A base 2D graphics library -- `@nanoforge-dev/asset-manager` ([source][asset-manager-source]) - A manager for loading assets to uniform workwith between client and server -- `@nanoforge-dev/network-client` ([source][network-client-source]) - A network lib with tcp and udp support for client-side usage -- `@nanoforge-dev/network-server` ([source][network-server-source]) - A network lib with tcp and udp support for server-side usage -- `@nanoforge-dev/input` ([source][input-source]) - An input manager for handling keyboard and mouse events +- `@nanoforge-dev/graphics-3d` ([source][graphics-3d-source]) - A 3D graphics library built on Three.js +- `@nanoforge-dev/input` ([source][input-source]) - An input manager for handling keyboard, mouse and controller events - `@nanoforge-dev/music` ([source][music-source]) - A music player for your game +- `@nanoforge-dev/network` ([source][network-source]) - A network lib with tcp and udp support, for the client and the server - `@nanoforge-dev/scene` ([source][scene-source]) - A scene manager, with vars shared by scenes and systems - `@nanoforge-dev/sound` ([source][sound-source]) - A sound manager for your game @@ -62,20 +61,19 @@ If you don't understand something in the documentation, you are experiencing pro [contributing]: https://github.com/NanoForge-dev/Engine/blob/main/.github/CONTRIBUTING.md [discussions]: https://github.com/NanoForge-dev/Engine/discussions -[cli-source]: https://github.com/NanoForge-dev/CLI +[cli-docs]: https://docs.nanoforge.eu/docs/cli/getting-started/quickstart [github-releases]: https://github.com/NanoForge-dev/Engine/releases -[asset-manager-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/asset-manager +[asset-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/asset [common-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/common -[config-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/config [core-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/core -[ecs-client-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-client -[ecs-lib-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-lib -[ecs-server-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-server -[graphics-2d-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/graphics-2d -[input-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/input -[music-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/music -[network-client-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/network-client -[network-server-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/network-server +[env-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/env +[ecs-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/ecs +[editor-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/editor +[graphics-2d-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/graphics-2d +[graphics-3d-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/graphics-3d +[input-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/input +[music-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/music +[network-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/network [scene-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/scene -[sound-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/sound +[sound-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/sound [good-first-issue]: https://github.com/NanoForge-dev/Engine/contribute diff --git a/docs/docs/graphics-3d/editor-proposal.mdx b/docs/design/graphics-3d-editor-proposal.md similarity index 100% rename from docs/docs/graphics-3d/editor-proposal.mdx rename to docs/design/graphics-3d-editor-proposal.md diff --git a/docs/docs/lib-graphic-3d/babylon-js.mdx b/docs/design/lib-graphic-3d/babylon-js.md similarity index 100% rename from docs/docs/lib-graphic-3d/babylon-js.mdx rename to docs/design/lib-graphic-3d/babylon-js.md diff --git a/docs/docs/lib-graphic-3d/index.mdx b/docs/design/lib-graphic-3d/index.md similarity index 100% rename from docs/docs/lib-graphic-3d/index.mdx rename to docs/design/lib-graphic-3d/index.md diff --git a/docs/docs/lib-graphic-3d/luma-gl.mdx b/docs/design/lib-graphic-3d/luma-gl.md similarity index 100% rename from docs/docs/lib-graphic-3d/luma-gl.mdx rename to docs/design/lib-graphic-3d/luma-gl.md diff --git a/docs/docs/lib-graphic-3d/playcanvas.mdx b/docs/design/lib-graphic-3d/playcanvas.md similarity index 100% rename from docs/docs/lib-graphic-3d/playcanvas.mdx rename to docs/design/lib-graphic-3d/playcanvas.md diff --git a/docs/docs/lib-graphic-3d/poc.mdx b/docs/design/lib-graphic-3d/poc.md similarity index 100% rename from docs/docs/lib-graphic-3d/poc.mdx rename to docs/design/lib-graphic-3d/poc.md diff --git a/docs/docs/lib-graphic-3d/three-js.mdx b/docs/design/lib-graphic-3d/three-js.md similarity index 100% rename from docs/docs/lib-graphic-3d/three-js.mdx rename to docs/design/lib-graphic-3d/three-js.md diff --git a/docs/docs/assets/index.mdx b/docs/docs/assets/index.mdx new file mode 100644 index 0000000..7789b42 --- /dev/null +++ b/docs/docs/assets/index.mdx @@ -0,0 +1,43 @@ +--- +title: "Assets" +icon: "image" +description: "Load images, sounds and data files shipped with your game" +--- + +Assets are the files your game ships with: images, sounds, levels, configuration. Put them in your project's `assets` folder. `nf build` copies its content next to the game code, so `assets/hero.png` becomes `/hero.png`. + +## Read an asset + +The asset library is built into every application: you never register it. Read a file with `ctx.assets.getAsset(path)` wherever you have the context. Load each file once, not on every tick: a scene's `load` is a good place, and it can wait for the file (see [Scenes](../scene/index)). + +```ts +export class Level extends Scene { + override async load(ctx: Context) { + const level = await ctx.assets.getAsset("/levels/1.json").json(); + + const hero = new window.Image(); + hero.src = ctx.assets.getAsset("/hero.png").path; + ctx.graphics.baseLayer.add(new Image({ image: hero, x: level.x, y: level.y })); + + ctx.sound.load("jump", ctx.assets.getAsset("/jump.wav").path); + } +} +``` + +`getAsset` returns an `NfFile`: + +| Member | Gives | +| -------------------------------------------------- | ----------------------------------------------------------------------------- | +| `path` | The URL of the file. Pass it to anything that loads a URL: an image, a sound. | +| `json()` | The content parsed as JSON. | +| `text()` | The content as a string. | +| `arrayBuffer()`, `bytes()`, `blob()`, `formData()` | The content in that format. | + +- Paths are normalized: `"hero.png"`, `"/hero.png"` and `"//hero.png"` find the same file. +- `getAsset` throws `NfNotFound` when no file has that path. The read methods fetch the file and throw `NfFetchException` when the fetch fails. + +## In `main` + +`main` has no context. There, read the URL from the run options: `options.files.get("/hero.png")` returns the same URL as `getAsset("/hero.png").path`, or `undefined` when the file is missing. [Sound and music](../audio/index) shows an example. + +To change the folder name, set `dir.assets` in the app's `nanoforge.config.ts`. See [the configuration file](/docs/cli/configuration/configuration-file). diff --git a/docs/docs/audio/index.mdx b/docs/docs/audio/index.mdx new file mode 100644 index 0000000..5d4ae80 --- /dev/null +++ b/docs/docs/audio/index.mdx @@ -0,0 +1,76 @@ +--- +title: "Sound and music" +icon: "volume-high" +description: "Play sound effects and background music" +--- + +Two client libraries play audio: + +| Library | Package | Context key | For | +| -------------- | ---------------------- | ----------- | ------------------------------------------------- | +| `SoundLibrary` | `@nanoforge-dev/sound` | `ctx.sound` | Sound effects. Several can play at the same time. | +| `MusicLibrary` | `@nanoforge-dev/music` | `ctx.music` | Music. Playing a track stops the one before it. | + +Both have the same three methods: `load(key, url)`, `play(key)` and `mute()`. + +## Load your files + +Put the audio files in your project's `assets` folder, then load each one under a key after `app.init`: + +```ts +const app = NanoforgeFactory.createClient(); +const sound = new SoundLibrary(); +const music = new MusicLibrary(); +app.use(sound); +app.use(music); + +await app.init(options); + +// `main` has no context: read the URLs of the files in `assets/` from the run options. +const url = (path: string): string => { + const file = options.files.get(path); + if (!file) throw new Error(`Missing asset: ${path}`); + return file; +}; +sound.load("jump", url("/jump.wav")); +music.load("theme", url("/theme.mp3")); +music.play("theme"); + +await app.run(); +``` + +## Play + +From a system, or anywhere you have the context: + +```ts +if (ctx.input.isKeyPressed(InputEnum.Space)) ctx.sound.play("jump"); +``` + +- `ctx.music.play(key)` stops the track that was playing before. +- `play` throws `NfNotFound` when no file was loaded under that key. +- Playing a sound that is already playing has no effect until it ends. + +## Turn the sound on + + + Both libraries start **muted**, and `mute()` toggles the muted state: call it once to turn the + sound on. Browsers also block audio until the player has interacted with the page, so tie it to a + key press or a click. + + +A system runs on every tick, so toggle on the press, not while the key is held: + +```ts +let wasPressed = false; + +// Toggles sound and music once per press of M. +export const toggleSound = (_registry: Registry, ctx: Context) => { + const pressed = ctx.input.isKeyPressed(InputEnum.KeyM) ?? false; + if (pressed && !wasPressed) { + ctx.sound.mute(); + ctx.music.mute(); + } + wasPressed = pressed; +}; +``` diff --git a/docs/docs/ecs/index.mdx b/docs/docs/ecs/index.mdx new file mode 100644 index 0000000..bfe4be5 --- /dev/null +++ b/docs/docs/ecs/index.mdx @@ -0,0 +1,119 @@ +--- +title: "ECS" +icon: "boxes-stacked" +description: "Store the game state as entities and components, and update it with systems" +--- + +The ECS (entity component system) holds the state of your game. It comes from `@nanoforge-dev/ecs`, a registry written in C++ and compiled to WebAssembly. + +- An **entity** is an id. It has no data of its own. +- A **component** is a data object attached to an entity: a position, a velocity, a health value. +- A **system** is a function called on every tick. It finds the entities that have some components and updates them. + +## Register the library + +Import `EcsLibrary` from the entry point of your side of the game: + +```ts +import { EcsLibrary } from "@nanoforge-dev/ecs/client"; + +// or "@nanoforge-dev/ecs/server" + +const ecs = new EcsLibrary(); +app.use(ecs); +await app.init(options); + +const registry = ecs.registry; // also ctx.ecs.registry in systems +``` + +`ecs.registry` throws before `app.init` has resolved. The types `Registry`, `Entity`, `Component` and `System` come from the same entry point. + +## Components + +A component is an instance of a class with a `name` field equal to its class name: + +```ts +export class Position { + name = this.constructor.name; + + constructor( + public x: number, + public y: number, + ) {} +} +``` + +The registry files each component under its `name`. When you add a component it reads `name` on the instance; when you query, it reads `name` on the class you pass. The two must match. + + + Don't give a component class the name of another class in your game's bundle. When two classes + share a name, the bundler renames one (`Position2`), and the results of `getZipper` are then keyed + by that new name: destructuring `({Position})` gives `undefined`. Three.js and Konva export many + classes (`Sphere`, `Plane`, `Box3`, `Text`, `Image`, `Line`...), so prefer names that are clearly + yours, such as `Hitbox` or `PlayerSprite`. + + +An entity has at most one component of each type: adding a second `Position` replaces the first. + +## Entities + +```ts +const enemy = registry.spawnEntity(); +registry.addComponent(enemy, new Health(3)); +registry.addComponent(enemy, new Poisoned()); + +const health = registry.getEntityComponent(enemy, Health); // the Health instance, or undefined +registry.removeComponent(enemy, Poisoned); +registry.killEntity(enemy); +``` + +`killEntity` removes every component of the entity. + +## Systems + +A system has the type `(registry, ctx) => void`. Add it with `registry.addSystem(system)`. Systems run on every tick, in the order you added them, unless the game is paused. + +`registry.getZipper([A, B])` returns one object per entity that has every listed component, keyed by component name: + +```ts +export const move = (registry: Registry, ctx: Context) => { + const seconds = ctx.app.delta / 1000; + registry.getZipper([Position, Velocity]).forEach(({ Position, Velocity }) => { + Position.x += Velocity.x * seconds; + Position.y += Velocity.y * seconds; + }); +}; +``` + +The objects in the result are your component instances: changing them changes the game state. + +To know which entity a result belongs to, use `getIndexedZipper`. Each object also has an `id`, which `entityFromIndex` turns back into an entity: + +```ts +export const poison = (registry: Registry) => { + registry.getIndexedZipper([Health, Poisoned]).forEach(({ id, Health }) => { + Health.value -= 1; + if (Health.value <= 0) registry.killEntity(registry.entityFromIndex(id)); + }); +}; +``` + +Other registry methods: + +| Method | What it does | +| -------------------------- | ------------------------------------------------------------- | +| `removeSystem(index)` | Removes the system at that position in the list. | +| `clearSystems()` | Removes every system. | +| `clearEntities()` | Removes every entity and component. | +| `getComponents(Component)` | The sparse array of one component type, indexed by entity id. | +| `maxEntities()` | The number of entity ids used so far. | + +To add and remove a group of entities and systems together, such as a level, use a scene: see [Scenes](../scene/index). + +## Errors + +An error thrown in the C++ registry reaches JavaScript as a runtime error, with less detail than a JavaScript error. For example, `entityFromIndex` throws for an id that was never spawned or was killed: check your ids before calling it. + +## Editor manifests + +Projects generated by `nf new` export an `EDITOR_COMPONENT_MANIFEST` next to each component and an `EDITOR_SYSTEM_MANIFEST` next to each system. The NanoForge editor reads them to show and generate your components and systems. The types are `EditorComponentManifest` and `EditorSystemManifest`. To generate a new component or system with its manifest, see the CLI [component](/docs/cli/schematics/component) and [system](/docs/cli/schematics/system) schematics. diff --git a/docs/docs/editor/protocol.mdx b/docs/docs/editor/protocol.mdx index c670e45..e3035ea 100644 --- a/docs/docs/editor/protocol.mdx +++ b/docs/docs/editor/protocol.mdx @@ -4,6 +4,8 @@ icon: "book" description: "How a running game and the NanoForge editor talk to each other" --- +To run and inspect your game in the NanoForge editor, register `EditorLibrary` from `@nanoforge-dev/editor-lib`. That is all a game needs: the rest of this page describes the protocol, for people who write an editor host or a library with editor features. + When the editor starts a game, it passes two event emitters in `RunOptions.editor`: - `fromEditor`: editor → engine commands. `EditorLibrary` drains it at the start of every tick, including paused ticks. @@ -50,12 +52,13 @@ The hook is not part of the engine: `EditorLibrary` calls it with `ctx.app.callH ## Run control -| Command | Effect | -| -------- | --------------------------------------------- | -| `pause` | `ctx.app.requestPause()` | -| `resume` | `ctx.app.requestResume()` | -| `step` | runs exactly one tick while paused | -| `stop` | `ctx.app.requestStop()`: clears every library | +| Command | Effect | +| -------- | ------------------------------------------------------------------------------------------------------- | +| `pause` | `ctx.app.requestPause()` | +| `resume` | `ctx.app.requestResume()` | +| `step` | runs exactly one tick while paused | +| `stop` | `ctx.app.requestStop()`: clears every library | +| `mute` | mutes (`true`) or unmutes (`false`) the sound and music libraries, on top of the game's own muted state | A command applies on the tick it is drained in. After a `stop`, that tick still completes before the libraries are cleared. @@ -63,17 +66,28 @@ The engine reports each change of its run state with the `state` event: `"runnin ## Optional features -Each feature is enabled only if the editor asks for it in `welcome.features`. +Each feature is enabled only if the editor asks for it in `welcome.features`. The base features are: + +| Feature | Event | Payload | +| --------------------------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `frameStats: { intervalMs }` | `frame-stats` | `{ windowMs, ticks, tps, tick: { avg, max }, libraries: { [key]: { avg, max } } }`, durations in ms | +| `logs: true` | `log` | `{ level, message }` for each `console.debug`, `log`, `info`, `warn` and `error` call made by the game's code (`log` is reported as `info`) | +| `logs: { values: true }` | `log` | also `values` (the logged values, as trees) and `caller` (`::`) | +| `networkTrace: { sampleRate?, maxPerSecond?, maxBytes? }` | `network-trace` | `{ direction, transport, clientId?, size, head, data?, time }` (network libraries); `data` holds the first `maxBytes` bytes, hex encoded. A `network-stats` event also sends the totals every second. | +| `viewport: true` | `viewport` | the game's `ViewportState`, at once and on every change (clients) | + +Libraries add their own features: -| Feature | Event | Payload | -| ---------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------- | -| `frameStats: { intervalMs }` | `frame-stats` | `{ windowMs, ticks, tps, tick: { avg, max }, libraries: { [key]: { avg, max } } }`, durations in ms | -| `logs: true` | `log` | `{ level, message }` for each console call made by the game's code | -| `logs: { values: true }` | `log` | also `values` (the logged values, as trees) and `caller` (`::`) | -| `networkTrace: { sampleRate?, maxPerSecond? }` | `network-trace` | `{ direction, transport, clientId?, size, head, time }` (network libraries) | -| `viewport: true` | `viewport` | the game's `ViewportState`, at once and on every change (clients) | +| Feature | Library | Events | Commands | +| -------------------------------- | ------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `ecsWorld: { intervalMs }` | `ecs` | `ecs-world` | `ecs-set-component`, `ecs-add-component`, `ecs-remove-component`, `ecs-spawn-entity`, `ecs-remove-entity`, `ecs-set-system-enabled` | +| `ecsSystemStats: { intervalMs }` | `ecs` | `ecs-system-stats` | | +| `scenes: { intervalMs }` | `scene` | `scenes` | `scenes-load`, `scenes-unload`, `scenes-set-var` | +| `graphicsCamera: true` | `graphics-3d` | `graphics-camera`, `graphics-capture` | `graphics-capture` | -Log forwarding only forwards console calls whose stack contains a frame of the game bundle. Output from before the `welcome` (library `__init`, the start of `main`) is kept, up to 200 lines, and sent as soon as the editor asks for logs. It is dropped if the editor doesn't ask for them. A client runs inside the editor page, and this keeps the editor's own console output out of the game logs. +The feature only turns the events on: the commands are handled whenever the library and `EditorLibrary` are registered. Their payloads are typed in each package (`EcsEditorCommands`, `SceneEditorCommands`...). See the API reference tab. + +Log forwarding only forwards console calls whose stack contains a frame of the game bundle. Output from before the `welcome` (library `__init`, the start of `main`) is kept, up to 200 lines, and sent as soon as the editor asks for logs. It is dropped if the editor doesn't ask for them. When more than 200 lines were waiting, a warning line says how many earlier lines were dropped. A client runs inside the editor page, and this keeps the editor's own console output out of the game logs. ### Logged values belong to the host @@ -90,7 +104,10 @@ A point `(x, y)` of the game is drawn at `(contentLeft + originX + x * scaleX, c ## Hosting a game ```ts -import { QueuedEventEmitter } from "@nanoforge-dev/editor-lib"; +import { EDITOR_PROTOCOL_VERSION, QueuedEventEmitter } from "@nanoforge-dev/editor-lib"; + +// `main` is the game's entry point, `options` its run options, `handle` your event handler +// and `serializeLogValue` your value serializer (optional, see above). const fromEditor = new QueuedEventEmitter(); // drained by the engine const toEditor = { @@ -102,7 +119,10 @@ const toEditor = { }; await main({ ...options, editor: { toEditor, fromEditor, serializeLogValue } }); -fromEditor.emit("welcome", { protocolVersion: 1, features: { frameStats: { intervalMs: 500 } } }); +fromEditor.emit("welcome", { + protocolVersion: EDITOR_PROTOCOL_VERSION, + features: { frameStats: { intervalMs: 500 } }, +}); ``` The game started by `main` must have registered `EditorLibrary`, or `RunOptions.editor` is ignored. diff --git a/docs/docs/env/index.mdx b/docs/docs/env/index.mdx new file mode 100644 index 0000000..02b2167 --- /dev/null +++ b/docs/docs/env/index.mdx @@ -0,0 +1,61 @@ +--- +title: "Environment" +icon: "sliders" +description: "Read and validate environment variables in your game" +--- + +Environment variables configure a game without changing its code: a server address, a port, a game mode. + +## Set them + +Put them in a `.env` file at the root of the project. Their names start with `NANOFORGE_`, and the prefix is removed before the game sees them: `NANOFORGE_GAME_MODE` becomes `GAME_MODE`. In the `.env` file, `NANOFORGE_CLIENT_X` is meant for the client and `NANOFORGE_SERVER_X` for the server; both become `X`. See [Environment variables](/docs/cli/configuration/environment-variables) in the CLI docs. + +Never put a secret in a variable the client receives: the client runs in the player's browser. Put server-only values in the `.env` file with the `NANOFORGE_SERVER_` prefix, and never export secrets in the shell or container environment that runs `nf start` or `nf dev`. + +## Read them + +The run options carry the variables as raw strings: `options.env` in `main`, and `ctx.env` in a library's `__init`. To check them and convert them to typed values, describe them with a class and pass it to `registerEnv` from `@nanoforge-dev/env`: + +```ts +declare module "@nanoforge-dev/common" { + interface Context { + rules: { mode: "coop" | "versus"; debug: boolean }; + } +} + +class GameEnv { + @Expose() + @Default("coop") + @IsIn(["coop", "versus"]) + GAME_MODE!: "coop" | "versus"; + + @Expose() + @TransformToBoolean() + @IsBoolean() + @Default(false) + DEBUG!: boolean; +} + +export class RulesLibrary extends Library { + readonly key = defineLibraryKey("rules"); + + private _env?: GameEnv; + + public override async __init(ctx: InitContext): Promise { + this._env = await registerEnv(GameEnv, ctx.env); + } + + public override expose() { + if (!this._env) this.throwNotInitializedError(); + return { mode: this._env.GAME_MODE, debug: this._env.DEBUG }; + } +} +``` + +- The `declare module` block types `ctx.rules`: see [Writing your own library](../getting-started/concepts#writing-your-own-library). +- Mark every variable with `@Expose()`: the others are dropped. +- `@Default(value)` gives the value of a missing variable. `@TransformToBoolean()` turns `"true"` and `"false"` into booleans. `@IsIpOrURL()` checks an address. +- The package re-exports the [class-validator](https://github.com/typestack/class-validator) decorators (`@IsIn`, `@IsPort`, `@IsString`, `@IsOptional`...) and `Transform` from class-transformer. +- `registerEnv` throws `NfEnvValidationException` with every failed check, so a bad value stops the game at start-up instead of later. + +The network library reads its own variables this way: see [Network](../network/index#environment-variables). diff --git a/docs/docs/getting-started/concepts.mdx b/docs/docs/getting-started/concepts.mdx new file mode 100644 index 0000000..6a3333e --- /dev/null +++ b/docs/docs/getting-started/concepts.mdx @@ -0,0 +1,136 @@ +--- +title: "Core concepts" +icon: "lightbulb" +description: "Applications, libraries, the context, the game loop, the ECS and the client/server split" +--- + +This page explains the pieces every NanoForge game is made of. The [quickstart](./quickstart) shows them working together. + +## The application + +Your game's `src/main.ts` exports a `main` function. The NanoForge loader calls it with the run options: the page element to draw in (`container`, client only), the game files (`files`) and the environment variables (`env`). You pass these options on to the application. + +You create the application with `NanoforgeFactory` from `@nanoforge-dev/core`: + +| Call | Use it for | Options | +| ---------------------------------------- | ----------------------- | ------------------------------------- | +| `NanoforgeFactory.createClient(options)` | the game in the browser | `tickRate` (default `60`), `viewport` | +| `NanoforgeFactory.createServer(options)` | a game server, on Bun | `tickRate` (default `60`) | + +The `viewport` option sets the game's design resolution (`width` and `height`, default 1920 by 1080) and how it fits the window (`fit`: `"contain"` by default, `"cover"` or `"fill"`). Game coordinates are always in that resolution; the engine scales the canvas to the window. + +Every application has the same three steps: + +```ts +const app = NanoforgeFactory.createClient({ tickRate: 60 }); +app.use(new EcsLibrary()); // 1. register libraries +await app.init(options); // 2. initialize them +await app.run(); // 3. start the game loop +``` + +`app.use` throws once `init` has resolved: register every library before. Libraries are ready only after `init` resolves. + +## Libraries + +Everything the engine does, it does through a **library**: the ECS, graphics, input, audio, networking and scenes are all libraries. You register the ones your game needs with `app.use`, and each one adds a key to the context: + +| Library | Context key | +| ------------------------------------------------------- | ------------------------ | +| `EcsLibrary` (`@nanoforge-dev/ecs/client` or `/server`) | `ctx.ecs` | +| `Graphics2DLibrary` or `Graphics3DLibrary` | `ctx.graphics` | +| `InputLibrary` (`@nanoforge-dev/input`) | `ctx.input` | +| `ControllerLibrary` (`@nanoforge-dev/input/controller`) | `ctx.controller` | +| `SoundLibrary`, `MusicLibrary` | `ctx.sound`, `ctx.music` | +| `SceneLibrary` (`@nanoforge-dev/scene`) | `ctx.scenes` | +| `NetworkClientLibrary` or `NetworkServerLibrary` | `ctx.network` | +| `EditorLibrary` (`@nanoforge-dev/editor-lib`) | `ctx.editor` | + +Two libraries can't share a key: registering both graphics libraries throws. + +## The context + +The context (`Context` from `@nanoforge-dev/common`) is the object every system and library receives each tick. It always has: + +- `ctx.app`: the loop state and controls. `delta` (milliseconds since the last tick), `tickRate`, `isRunning`, `isPaused`, and `requestStop()`, `requestPause()`, `requestResume()`, `requestStep()`. +- `ctx.assets`: the game files. `ctx.assets.getAsset("/hero.png")`. See [Assets](../assets/index). +- `ctx.vars`: a key/value store shared by every library and system for the whole run. +- `ctx.viewport`: on the client only, the design resolution and conversions between screen and game coordinates. + +The other keys come from the libraries you registered, as in the table above. + +## The game loop + +`app.run()` starts a loop that runs `tickRate` times per second. Each library has four hooks, called in this order: + +1. `__init`, once, during `app.init`. A library that lists another in its `dependencies` is initialized after it. +2. `__events`, every tick, even when the game is paused. +3. `__run`, every tick unless the game is paused. This is where `EcsLibrary` runs your systems. +4. `__clear`, once, after `ctx.app.requestStop()` stops the loop. + +The engine orders libraries for each tick. For example the network library runs before the ECS, so packets received this tick are ready for your systems. + +## Entities, components and systems + +The game state lives in the ECS registry, `ctx.ecs.registry` (or `ecs.registry` in `main`): + +- an **entity** is an id, made with `registry.spawnEntity()`; +- a **component** is a data object attached to an entity with `registry.addComponent(entity, component)`; +- a **system** is a function `(registry, ctx) => void`, added with `registry.addSystem(system)` and called on every tick. + +See [ECS](../ecs/index) for the details. + +## Client and server + +A game can run as a client alone, or as a client plus a server: + +- The **client** runs in the browser. It draws, plays sounds and reads input. The graphics, input and audio libraries work only there. +- The **server** runs on Bun. It has no screen: it owns the shared game state and sends it to the clients. It uses `EcsLibrary` from `@nanoforge-dev/ecs/server` and `NetworkServerLibrary`. +- Both sides share their packet definitions through a common file. See [Network](../network/index), and [Peer-to-peer](../network/network-peer) to run the server inside a player's browser instead. + +## Writing your own library + +A library is a class that extends `Library` from `@nanoforge-dev/common`. It declares its context key, then overrides the hooks it needs and `expose()`, which returns what `ctx.[key]` gives to game code: + +```ts +import { type Context, Library, defineLibraryKey } from "@nanoforge-dev/common"; + +export interface ScoreApi { + add(points: number): void; + readonly value: number; +} + +declare module "@nanoforge-dev/common" { + interface Context { + score: ScoreApi; + } +} + +export class ScoreLibrary extends Library { + readonly key = defineLibraryKey("score"); + + private _value = 0; + + public override async __run(ctx: Context): Promise { + if (this._value >= 10) ctx.app.requestStop(); + } + + public override expose(): ScoreApi { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const library = this; + return { + add: (points) => { + library._value += points; + }, + get value() { + return library._value; + }, + }; + } +} +``` + +Register it like any other library: `app.use(new ScoreLibrary())`. Systems can then call `ctx.score.add(1)`. + +- The `declare module` block types `ctx.score`. `defineLibraryKey` only accepts a key declared there. +- Return a plain object from `expose()`, never `this`, so game code can't call the hooks. +- To set the order, pass relationships to `super()` in the constructor: `dependencies` are initialized first, `runBefore` libraries run before this one each tick, `runAfter` libraries run after it. In `runBefore` and `runAfter`, `"*"` means every other library; `dependencies` only takes library keys. diff --git a/docs/docs/getting-started/documentation.mdx b/docs/docs/getting-started/documentation.mdx index 6fba61c..609e85f 100644 --- a/docs/docs/getting-started/documentation.mdx +++ b/docs/docs/getting-started/documentation.mdx @@ -1,12 +1,16 @@ --- -title: "Documentation" -icon: "book" -description: "How the engine documentation is written and published" +title: "About this documentation" +icon: "book-open" +description: "Where the engine guides and API reference are, and how to report a mistake" --- -The engine documentation lives in the engine repository and is published to this site automatically at each engine release. +The engine documentation has two parts: -- **Pages** are the `.mdx` files in `docs/docs`. Their order and groups come from `docs/docs/navigation.json`: every page is listed there exactly once. -- **API references** are generated from the TSDoc comments of each package by `pnpm run docs` (TypeDoc), into `docs/references`. They are never written by hand. +- **Guides**, in this tab: what each package is for and how to use it, with examples. Start with [Create a project](./how-to-use). +- **API reference**, in the API reference tab: every class, method, option and type of every package. It is generated from the comments in the engine source code. -To change a page, edit it in the engine repository. Links between pages are relative to the file, like `./how-to-use` or `../network/index`. +Both are published from the [engine repository](https://github.com/NanoForge-dev/Engine) at each engine release, so they match the latest published packages. + +## Report a mistake + +If a page is wrong, unclear or missing, open an issue on the [engine repository](https://github.com/NanoForge-dev/Engine/issues), or ask on [Discussions](https://github.com/NanoForge-dev/Engine/discussions). The guides are the `.mdx` files in the repository's `docs/docs` folder: you can also propose a change there with a pull request. diff --git a/docs/docs/getting-started/how-to-use.mdx b/docs/docs/getting-started/how-to-use.mdx index a4fc200..0b589eb 100644 --- a/docs/docs/getting-started/how-to-use.mdx +++ b/docs/docs/getting-started/how-to-use.mdx @@ -1,15 +1,70 @@ --- -title: "Introduction to using the Engine" -icon: "book" -description: "Getting started with the engine" +title: "Create a project" +icon: "folder-plus" +description: "Generate a NanoForge game project with the CLI and run it in the browser" --- -Whether you work on this engine as a developer or you want to use it, you will want a test project. This page is a walkthrough for setting up a basic project. +The fastest way to start is the NanoForge CLI, `nf`. It generates a project with the engine packages already installed and wired, then builds and serves it for you. You don't need to set anything up by hand. -## As a developer on the engine + + + ```bash + npm install -g @nanoforge-dev/cli + ``` -As a developer you want to be able to use your changes in your own project. Therefore it is recommended to use the provided [CLI](https://github.com/NanoForge-dev/CLI). + See [Installation](/docs/cli/getting-started/installation) for the other package managers. -## As a user + + + ```bash + nf new + ``` -As a user you can either use the template and change the dependency location, or create a project and add the Nanoforge dependencies. It is recommended to use Bun as a package manager. + Answer the prompts: name, language, package manager, and whether you want a server. For a first game, choose TypeScript (`ts`, the language of the examples in this documentation) and no server: the whole game then runs in the browser. + + + + ```bash + cd my-game + ``` + + Follow the [quickstart](./quickstart): it replaces the generated `src` files with a small + game, then runs it with `nf dev`, which builds the game, serves it, and rebuilds when you + save a file. + + + The sample the CLI generates for a project without a server registers the network + library, which needs a server address. Until the CLI template changes, running it as it + is fails at start-up with an environment validation error. The quickstart code doesn't + use the network library. + + + + + +## What you get + +Without a server, the project is one client application: + +``` +my-game/ +├── nanoforge.config.ts # type: "client" +├── package.json +├── assets/ # images, sounds, data files +└── src/ + ├── main.ts # entry point: creates and runs the application + ├── components/ + └── systems/ +``` + +With a server, the project is a workspace with one such folder per application, `apps/client` and `apps/server`, and a root `nanoforge.config.ts` that lists them. + +- `src/main.ts` exports a `main` function. The NanoForge loader calls it with the options the game needs (the page element to draw in, the game files, the environment). +- `src/components` and `src/systems` hold the game logic. See [ECS](../ecs/index). +- Files in `assets/` are served with the game. See [Assets](../assets/index). + +The CLI documentation covers every command and option: [CLI quickstart](/docs/cli/getting-started/quickstart), [nf new](/docs/cli/commands/new) and [the configuration file](/docs/cli/configuration/configuration-file). + +## Next + +Follow the [quickstart](./quickstart) to replace the sample with your own small game. diff --git a/docs/docs/getting-started/index.mdx b/docs/docs/getting-started/index.mdx index 2b289b5..dda1b69 100644 --- a/docs/docs/getting-started/index.mdx +++ b/docs/docs/getting-started/index.mdx @@ -1,19 +1,48 @@ --- title: "Engine" icon: "book" -description: "Nanoforge engine documentation" +description: "What the NanoForge engine is, what its packages do, and where to start" --- -This documentation covers the engine, its packages, and the surrounding usage guides. +NanoForge is a game engine for the web browser, written in TypeScript. A game is a set of small libraries that you register on an application: an ECS to hold the game state, a renderer, an input reader, audio, networking. You only add the ones your game needs. -## Start Here +A game has a **client**, which runs in the browser, and can have a **server**, which runs on Bun. Both use the same engine and the same ECS. -- [Documentation](./documentation) -- [How to Use](./how-to-use) +## Start here + + + + Install the CLI and generate a project with `nf new`. + + + Build a small 2D game you move with the arrow keys. + + + Applications, libraries, the context, the game loop and the ECS. + + + Where the guides and the API reference are. + + ## Packages -- [Registry](../registry/index) -- [Network](../network/index) -- [Graphics 3D](../graphics-3d/index) -- [Editor protocol](../editor/protocol) +Every package is published on npm under `@nanoforge-dev/`. Projects made with `nf new` already depend on the ones they use. + +| Package | Side | What it is for | Guide | +| ---------------------------- | ------ | -------------------------------------------------------------------------------------------------- | ------------------------------------- | +| `@nanoforge-dev/core` | both | Creates the client or server application and runs the game loop. | [Core concepts](./concepts) | +| `@nanoforge-dev/common` | both | Shared types (`Context`, `Library`, run options) and exceptions. | [Core concepts](./concepts) | +| `@nanoforge-dev/ecs` | both | The entity component system: entities, components and systems. Import from `/client` or `/server`. | [ECS](../ecs/index) | +| `@nanoforge-dev/asset` | both | The built-in asset library behind `ctx.assets`. You never register it. | [Assets](../assets/index) | +| `@nanoforge-dev/env` | both | Validates environment variables into a typed class. | [Environment](../env/index) | +| `@nanoforge-dev/graphics-2d` | client | 2D drawing with [Konva](https://konvajs.org/): shapes, images, text, layers. | [Graphics 2D](../graphics-2d/index) | +| `@nanoforge-dev/graphics-3d` | client | 3D rendering with [Three.js](https://threejs.org/). | [Graphics 3D](../graphics-3d/index) | +| `@nanoforge-dev/input` | client | Keyboard and mouse, and controllers from `/controller`. | [Input](../input/index) | +| `@nanoforge-dev/sound` | client | Short sound effects. | [Sound and music](../audio/index) | +| `@nanoforge-dev/music` | client | Background music, one track at a time. | [Sound and music](../audio/index) | +| `@nanoforge-dev/scene` | both | Scenes (menus, levels, pause screens) and values shared between them. | [Scenes](../scene/index) | +| `@nanoforge-dev/network` | both | Client/server and peer-to-peer networking. Import from `/client` or `/server`. | [Network](../network/index) | +| `@nanoforge-dev/editor-lib` | both | Lets the NanoForge editor run and inspect your game. | [Editor protocol](../editor/protocol) | + +The full list of classes, methods and options of each package is in the **API reference** tab. diff --git a/docs/docs/getting-started/quickstart.mdx b/docs/docs/getting-started/quickstart.mdx new file mode 100644 index 0000000..4eeba47 --- /dev/null +++ b/docs/docs/getting-started/quickstart.mdx @@ -0,0 +1,170 @@ +--- +title: "Quickstart" +icon: "rocket" +description: "Build a small 2D game: a square you move with the arrow keys" +--- + +This page builds a complete client-only game: a square on a dark background that you move with the arrow keys. It uses the ECS, 2D graphics and input libraries, which is all most 2D games start from. + +You need a project first. If you don't have one, follow [Create a project](./how-to-use) with TypeScript and no server. + +## 1. Define the components + +A component is plain data attached to an entity. Each one is a class with a `name` field equal to its class name: the ECS uses that name to find the component again. + +Replace the files in `src/components` with one file, `src/components/components.ts`: + +```ts src/components/components.ts +import { Rect } from "@nanoforge-dev/graphics-2d"; + +export class Position { + name = this.constructor.name; + + constructor( + public x: number, + public y: number, + ) {} +} + +export class Velocity { + name = this.constructor.name; + + constructor( + public x: number, + public y: number, + ) {} +} + +export class Drawable { + name = this.constructor.name; + + constructor(public shape: Rect) {} +} + +export class Player { + name = this.constructor.name; + + constructor(public speed: number) {} +} +``` + +`Drawable` holds a Konva shape from `@nanoforge-dev/graphics-2d`. The shape is what you see; `Position` is where the game thinks the entity is. + +## 2. Write the systems + +A system is a function the engine calls on every tick with the registry and the context. It reads and changes components. `registry.getZipper([A, B])` returns every entity that has both components, as objects keyed by component name. + +Replace the files in `src/systems` with `src/systems/systems.ts`: + +```ts src/systems/systems.ts +import type { Context } from "@nanoforge-dev/common"; +import type { Registry } from "@nanoforge-dev/ecs/client"; +import { InputEnum } from "@nanoforge-dev/input"; + +import { Drawable, Player, Position, Velocity } from "../components/components"; + +const WIDTH = 800; +const HEIGHT = 600; +const SIZE = 50; + +// Arrow keys set the player's velocity, in game units per second. +export const controlPlayer = (registry: Registry, ctx: Context) => { + registry.getZipper([Player, Velocity]).forEach(({ Player, Velocity }) => { + const axis = (minus: InputEnum, plus: InputEnum) => + (ctx.input.isKeyPressed(plus) ? 1 : 0) - (ctx.input.isKeyPressed(minus) ? 1 : 0); + Velocity.x = axis(InputEnum.ArrowLeft, InputEnum.ArrowRight) * Player.speed; + Velocity.y = axis(InputEnum.ArrowUp, InputEnum.ArrowDown) * Player.speed; + }); +}; + +// Moves every entity by its velocity, scaled by the time since the last tick. +export const move = (registry: Registry, ctx: Context) => { + const seconds = ctx.app.delta / 1000; + registry.getZipper([Position, Velocity]).forEach(({ Position, Velocity }) => { + Position.x = Math.min(Math.max(Position.x + Velocity.x * seconds, 0), WIDTH - SIZE); + Position.y = Math.min(Math.max(Position.y + Velocity.y * seconds, 0), HEIGHT - SIZE); + }); +}; + +// Copies each position to its shape, so the screen follows the game state. +export const draw = (registry: Registry) => { + registry.getZipper([Position, Drawable]).forEach(({ Position, Drawable }) => { + Drawable.shape.position({ x: Position.x, y: Position.y }); + }); +}; +``` + +- `ctx.input` comes from the input library, and `ctx.app.delta` is the time since the last tick, in milliseconds. Multiplying by it keeps the speed the same at any frame rate. +- Systems run in the order you add them: read input, then move, then draw. + +## 3. Write the entry point + +`main` creates the application, registers the libraries, spawns the player entity and starts the game loop. Replace `src/main.ts`: + +```ts src/main.ts +import type { ClientRunOptions } from "@nanoforge-dev/common"; +import { NanoforgeFactory } from "@nanoforge-dev/core"; +import { EcsLibrary } from "@nanoforge-dev/ecs/client"; +import { Graphics2DLibrary, Rect } from "@nanoforge-dev/graphics-2d"; +import { InputLibrary } from "@nanoforge-dev/input"; + +import { Drawable, Player, Position, Velocity } from "./components/components"; +import { controlPlayer, draw, move } from "./systems/systems"; + +export const main = async (options: ClientRunOptions): Promise => { + const app = NanoforgeFactory.createClient({ + tickRate: 60, + viewport: { width: 800, height: 600, fit: "contain" }, + }); + + const graphics = new Graphics2DLibrary(); + const ecs = new EcsLibrary(); + app.use(graphics); + app.use(ecs); + app.use(new InputLibrary()); + + await app.init(options); + + graphics.baseLayer.add(new Rect({ x: 0, y: 0, width: 800, height: 600, fill: "#1e1e2e" })); + + const registry = ecs.registry; + const player = registry.spawnEntity(); + const shape = new Rect({ width: 50, height: 50, fill: "#f38ba8" }); + graphics.baseLayer.add(shape); + registry.addComponent(player, new Position(375, 275)); + registry.addComponent(player, new Velocity(0, 0)); + registry.addComponent(player, new Drawable(shape)); + registry.addComponent(player, new Player(300)); + + registry.addSystem(controlPlayer); + registry.addSystem(move); + registry.addSystem(draw); + + await app.run(); +}; +``` + +The order matters: + +1. `app.use` registers each library. It must happen before `init`. +2. `await app.init(options)` initializes every library. `graphics.baseLayer` and `ecs.registry` exist only after it. +3. Spawn entities and add systems. +4. `await app.run()` starts the game loop. + +The viewport sets the game's own resolution, 800 by 600 here. Positions are in these game units, and the engine scales the canvas to fit the browser window. + +## 4. Run it + +```bash +nf dev +``` + +Open the address `nf dev` prints and press the arrow keys: the square moves and stops at the edges. + +## What's next + +- [Core concepts](./concepts) explains the application, libraries, the context and the game loop. +- [ECS](../ecs/index) covers entities, components and systems in more depth. +- [Graphics 2D](../graphics-2d/index), [Input](../input/index) and [Sound and music](../audio/index) cover the libraries this game uses, and the ones it could add. +- [Assets](../assets/index) shows how to load images and sounds from the `assets` folder. +- [Network](../network/index) shows how to add a server and other players. diff --git a/docs/docs/graphics-2d/index.mdx b/docs/docs/graphics-2d/index.mdx new file mode 100644 index 0000000..1b90f1e --- /dev/null +++ b/docs/docs/graphics-2d/index.mdx @@ -0,0 +1,49 @@ +--- +title: "Graphics 2D" +icon: "shapes" +description: "Draw shapes, images and text with the 2D graphics library" +--- + +`@nanoforge-dev/graphics-2d` draws your game with [Konva](https://konvajs.org/), a canvas library. It works on the client only. + +## Register the library + +```ts +import { Graphics2DLibrary } from "@nanoforge-dev/graphics-2d"; + +const graphics = new Graphics2DLibrary(); +app.use(graphics); +await app.init(options); +``` + +After `init`, `graphics.stage` and `graphics.baseLayer` are ready. Systems reach the same objects through `ctx.graphics.stage` and `ctx.graphics.baseLayer`. Both throw before `init`. + +You can't register `Graphics2DLibrary` and `Graphics3DLibrary` in the same app: both use the `graphics` key. + +## Draw + +The package re-exports the Konva classes: `Rect`, `Circle`, `Ellipse`, `Line`, `Text`, `Image`, `Sprite`, `Group`, `Layer` and the others. Create a shape and add it to a layer: + +```ts +const hud = new Layer(); +ctx.graphics.stage.add(hud); +const score = new Text({ x: 20, y: 20, text: "Score: 0", fontSize: 32, fill: "white" }); +hud.add(score); +ctx.graphics.baseLayer.add(new Circle({ x: 400, y: 300, radius: 40, fill: "red" })); + +score.text("Score: 1"); +``` + +- Change a shape through its methods (`shape.x(10)`, `shape.position({ x, y })`, `shape.fill("blue")`): the layer redraws on its own. +- Add your own `Layer`s to `ctx.graphics.stage` to draw groups of shapes above or below others. Layers added later are drawn on top. +- Keep the shape in a component and copy the entity's position to it in a system, as the [quickstart](../getting-started/quickstart) does. + +The [Konva documentation](https://konvajs.org/docs/) lists every shape and option. + +## Images + +Load an image from the `assets` folder with `ctx.assets`, then give it to an `Image` shape. See [Assets](../assets/index). + +## Coordinates and window size + +Positions are in game units, set by the `viewport` option of `NanoforgeFactory.createClient` (1920 by 1080 by default). The library scales the stage to the window and follows its size changes, so you never resize the canvas yourself. See [Core concepts](../getting-started/concepts#the-application). diff --git a/docs/docs/graphics-3d/advanced.mdx b/docs/docs/graphics-3d/advanced.mdx index 1f14494..98fdc1b 100644 --- a/docs/docs/graphics-3d/advanced.mdx +++ b/docs/docs/graphics-3d/advanced.mdx @@ -18,17 +18,17 @@ The subpaths only re-export `three`. `three` is a peer dependency that the app i ### Loading a model -Load project files through `ctx.assets`. It returns the URL the game serves the file at. +Load project files through `ctx.assets`, from a system or a library's `__run`. `getAsset(path).path` is the URL the game serves the file at. See [Assets](../assets/index). ```ts import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; -const file = ctx.assets.getAsset("models/robot.glb"); +const file = ctx.assets.getAsset("/models/robot.glb"); const gltf = await new GLTFLoader().loadAsync(file.path); ctx.graphics.scene.add(gltf.scene); ``` -Do not await asset loads in a library's `__init`: start them and add the objects when they arrive. +`ctx.assets` does not exist yet in a library's `__init`, and a system can't wait for a promise. Start the load once, and add the object to the scene when it arrives. ### Node materials and TSL @@ -45,7 +45,7 @@ ctx.graphics.scene.add(new Mesh(new SphereGeometry(), material)); ## Cameras -Assign any camera to `graphics.camera`. The viewport is applied to it at once, and again on every change. For a `PerspectiveCamera`, the library sets `aspect`. For an `OrthographicCamera`, you choose `left`/`right`/`top`/`bottom` in design proportions. +Assign a camera to `graphics.camera`. For a `PerspectiveCamera` or an `OrthographicCamera`, the viewport is applied to it at once, and again on every change; other cameras are used as they are. For a `PerspectiveCamera`, the library sets `aspect`. For an `OrthographicCamera`, you choose `left`/`right`/`top`/`bottom` in design proportions. ```ts import { OrthographicCamera } from "@nanoforge-dev/graphics-3d/three"; @@ -60,6 +60,7 @@ After changing `fov`, `near` or `far`, call `camera.updateProjectionMatrix()`. `raycast` takes page coordinates, the ones pointer events give: ```ts +const canvas = ctx.graphics.renderer.domElement; canvas.addEventListener("pointerdown", (event) => { const [hit] = ctx.graphics.raycast(event.clientX, event.clientY); if (hit) console.log("clicked", hit.object.name, "at", hit.point); @@ -70,7 +71,7 @@ canvas.addEventListener("pointerdown", (event) => { ## Render loop -Never call `renderer.setAnimationLoop` or render from `requestAnimationFrame`. The engine renders once per tick, and the editor relies on this: pause freezes the image, and step draws exactly one frame. To draw something else than `scene` through `camera`, such as a post-processing pipeline, replace the library's render step. The library still calls it once per tick, and for editor screenshots: +Never call `renderer.setAnimationLoop` or render from `requestAnimationFrame`. The engine renders once per tick, and the editor relies on this: pause freezes the image, and step draws exactly one frame. To draw something else than `scene` through `camera`, such as a post-processing pipeline, replace the library's render step. The library still calls it once per tick, when the viewport or the container changes size, and for editor screenshots: ```ts import { RenderPipeline } from "@nanoforge-dev/graphics-3d/three"; @@ -88,13 +89,13 @@ Assign `undefined` to go back to the default render. The custom render is reset ## Editor bridge -When the editor starts the game, the library adds to the editor protocol: +You don't need this section to write a game: it is for editor hosts. When the editor starts the game (with `EditorLibrary` registered), the library adds to the [editor protocol](../editor/protocol): -| Name | Direction | Payload | Purpose | -| ------------------ | --------------- | ---------------------- | -------------------------------------------------------------------------------------- | -| `graphicsCamera` | feature | `boolean` | Asked for in the editor's `welcome`. | -| `graphics-camera` | engine → editor | `{ view, projection }` | The active camera's matrices (16 numbers, column-major), on start and on every change. | -| `graphics-capture` | editor → engine | none | Renders a frame now, even while paused. | -| `graphics-capture` | engine → editor | PNG data URL | That frame. WebGL and WebGPU canvases are only readable right after a render. | +| Name | Direction | Payload | Purpose | +| ------------------ | --------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `graphicsCamera` | feature | `boolean` | Asked for in the editor's `welcome`. | +| `graphics-camera` | engine → editor | `{ view, projection }` | The active camera's matrices (16 numbers, column-major), on start and on every change. | +| `graphics-capture` | editor → engine | none | Renders a frame now, even while paused. | +| `graphics-capture` | engine → editor | PNG data URL | That frame, or an empty string when there is no renderer. WebGL and WebGPU canvases are only readable right after a render. | The projection includes the viewport crop, so its normalized device coordinates span the canvas. The canvas is drawn `visibleWidth` × `visibleHeight` CSS px at (`contentLeft`, `contentTop`) of the container (see the `viewport` event). diff --git a/docs/docs/graphics-3d/index.mdx b/docs/docs/graphics-3d/index.mdx index f6d66f4..22f92d3 100644 --- a/docs/docs/graphics-3d/index.mdx +++ b/docs/docs/graphics-3d/index.mdx @@ -4,7 +4,7 @@ icon: "cube" description: "Render a 3D scene with @nanoforge-dev/graphics-3d, built on Three.js" --- -`@nanoforge-dev/graphics-3d` renders a 3D scene in the game's container with [Three.js](https://threejs.org/). It was chosen in the [3D graphics library benchmark](../lib-graphic-3d/index). +`@nanoforge-dev/graphics-3d` renders a 3D scene in the game's container with [Three.js](https://threejs.org/). - **Client only.** `__init` throws on a server (no container). - **One graphics library per app.** It uses the `graphics` key, like graphics-2d, so an app registers one or the other. @@ -25,19 +25,34 @@ pnpm add @nanoforge-dev/graphics-3d three ### 2. Register the library +In `src/main.ts`, register the 3D library with the ECS: + ```ts +import type { ClientRunOptions } from "@nanoforge-dev/common"; +import { NanoforgeFactory } from "@nanoforge-dev/core"; +import { EcsLibrary } from "@nanoforge-dev/ecs/client"; import { Graphics3DLibrary } from "@nanoforge-dev/graphics-3d"; -const app = NanoforgeFactory.createClient({ - tickRate: 60, - viewport: { width: 1920, height: 1080, fit: "contain" }, -}); -const graphics = new Graphics3DLibrary(); -app.use(graphics); +export const main = async (options: ClientRunOptions): Promise => { + const app = NanoforgeFactory.createClient({ + tickRate: 60, + viewport: { width: 1920, height: 1080, fit: "contain" }, + }); + const graphics = new Graphics3DLibrary(); + const ecs = new EcsLibrary(); + app.use(graphics); + app.use(ecs); + + await app.init(options); -await app.init(options); + // steps 3 to 5 go here + + await app.run(); +}; ``` +`graphics.scene`, `graphics.camera` and `graphics.renderer` exist only after `app.init` has resolved: before, they throw. + ### 3. Add a light and an object Everything Three.js offers is imported from `@nanoforge-dev/graphics-3d/three`. Add objects to `graphics.scene` to show them. Without a light, `MeshStandardMaterial` objects are black. @@ -61,7 +76,7 @@ graphics.scene.add(cube); ### 4. Place the camera -The library starts with a perspective camera at `(0, 0, 5)`, looking at the origin. +The library starts with a perspective camera at `(0, 0, 5)`, looking at the origin (field of view 50, near 0.1, far 1000). ```ts graphics.camera.position.set(0, 1.5, 4); @@ -70,17 +85,33 @@ graphics.camera.lookAt(0, 0, 0); ### 5. Move things from a system -The scene is drawn after the systems run, so a system changes objects and the next frame shows them. `ctx.app.delta` is in milliseconds. +The scene is drawn after the systems run, so a system changes objects and the next frame shows them. Keep each object in a component: + +```ts +import type { Object3D } from "@nanoforge-dev/graphics-3d/three"; + +export class Model { + name = this.constructor.name; + + constructor(public object: Object3D) {} +} +``` + +Then attach it to an entity in `main`, and add a system that turns it. `ctx.app.delta` is in milliseconds. ```ts -export function spin(registry: Registry, ctx: Context) { +const registry = ecs.registry; +const entity = registry.spawnEntity(); +registry.addComponent(entity, new Model(cube)); + +registry.addSystem((registry: Registry, ctx: Context) => { registry.getZipper([Model]).forEach(({ Model }) => { Model.object.rotation.y += ctx.app.delta / 1000; }); -} +}); ``` -Systems reach the library through `ctx.graphics`. Do not keep the scene in a module-level variable. +`Registry` comes from `@nanoforge-dev/ecs/client` and `Context` from `@nanoforge-dev/common`. In systems, reach the library through `ctx.graphics` (`ctx.graphics.scene`, `ctx.graphics.camera`) rather than a module-level variable. See [ECS](../ecs/index) for components and systems. ## Viewport @@ -88,21 +119,21 @@ The canvas follows `Context.viewport` like the 2D stage: - the camera's full frame is the design resolution (`width` × `height` in `createClient`); - `contain` letterboxes it, `cover` crops it, `fill` stretches it; -- the canvas is resized on every window, fullscreen or pixel-ratio change. +- the canvas is resized when the window or the container changes size, and on fullscreen changes. You never call `renderer.setSize`, and you never set a camera's `aspect` yourself. ## `Context.graphics` -| Member | What it is | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| `scene` | The Three.js `Scene` rendered every tick. | -| `camera` | The camera used for rendering. Assign another one to switch; the viewport is applied to it. | -| `renderer` | The `WebGPURenderer`. Never call `setAnimationLoop`: the engine drives rendering. | -| `render` | Draws one frame. Assign your own function for post-processing (see [Advanced](./advanced#render-loop)). | -| `backend` | `"webgpu"` or `"webgl"`. | -| `raycast(clientX, clientY, objects?)` | Objects under a page point (e.g. a `PointerEvent`), nearest first. | -| `worldToScreen(point)` | Where a world point is drawn in the page, in CSS px. | +| Member | What it is | +| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scene` | The Three.js `Scene` rendered every tick. | +| `camera` | The camera used for rendering. Assign another one to switch. The viewport is applied to `PerspectiveCamera` and `OrthographicCamera` cameras only. | +| `renderer` | The `WebGPURenderer`. Never call `setAnimationLoop`: the engine drives rendering. | +| `render` | Draws one frame. Assign your own function for post-processing (see [Advanced](./advanced#render-loop)). | +| `backend` | `"webgpu"` or `"webgl"`. | +| `raycast(clientX, clientY, objects?)` | Objects under a page point (e.g. a `PointerEvent`), nearest first. | +| `worldToScreen(point)` | Where a world point is drawn in the page, in CSS px. | ## Options @@ -124,4 +155,3 @@ Objects you removed from the scene yourself are not disposed by the library. Cal - [Advanced](./advanced): Three.js add-ons, custom shaders, cameras, picking, editor events. - [Performance](./performance): many objects, and `InstancedMesh`. -- [Editor proposal](./editor-proposal): what the editor needs for a 3D Scene screen. diff --git a/docs/docs/graphics-3d/performance.mdx b/docs/docs/graphics-3d/performance.mdx index 9a57081..d2af501 100644 --- a/docs/docs/graphics-3d/performance.mdx +++ b/docs/docs/graphics-3d/performance.mdx @@ -4,7 +4,7 @@ icon: "gauge" description: "Drawing many objects with @nanoforge-dev/graphics-3d" --- -Each `Mesh` costs one draw call per frame. In the [benchmark POC](../lib-graphic-3d/poc), 2,000 meshes run at the display rate, while 20,000 run at about 12 FPS. +Each `Mesh` costs one draw call per frame. In the engine team's benchmark, 2,000 meshes run at the display rate, while 20,000 run at about 12 FPS. When a frame has more than 2,000 draw calls, the library logs this warning once: diff --git a/docs/docs/input/index.mdx b/docs/docs/input/index.mdx new file mode 100644 index 0000000..75c91ee --- /dev/null +++ b/docs/docs/input/index.mdx @@ -0,0 +1,57 @@ +--- +title: "Input" +icon: "keyboard" +description: "Read the keyboard, the mouse and game controllers" +--- + +`@nanoforge-dev/input` reads the player's input on the client. It has two libraries: + +| Library | Import from | Context key | +| ------------------- | ------------------------------------- | ---------------- | +| `InputLibrary` | `@nanoforge-dev/input/keyboard-mouse` | `ctx.input` | +| `ControllerLibrary` | `@nanoforge-dev/input/controller` | `ctx.controller` | + +The root `@nanoforge-dev/input` exports the keyboard and mouse library too. Register the ones you need with `app.use(new InputLibrary())`. Both read the current state: call them from a system on every tick. + +## Keyboard and mouse + +Keys and mouse buttons are members of `InputEnum` (`InputEnum.KeyA`, `InputEnum.Space`, `InputEnum.ArrowUp`, `InputEnum.MouseLeft`...). Their values are the browser's `KeyboardEvent.code`, so they name a key's position, not its letter. + +```ts +if (ctx.input.isKeyPressed(InputEnum.Space)) { + // jump +} +const mouse = ctx.input.getMousePosition(); // game coordinates +if (ctx.input.isDragging(InputEnum.MouseLeft)) { + const drag = ctx.input.getDragState(); // startX, startY, x, y, deltaX, deltaY + void drag; +} +``` + +| Method | Returns | +| --------------------- | ------------------------------------------------------------------------------------------ | +| `isKeyPressed(key)` | Whether the key or mouse button is held down. | +| `getPressedKeys()` | Every key held down. | +| `getMousePosition()` | The pointer position, in game coordinates. | +| `getMouseState()` | Position, previous position, movement, and whether the pointer is over the game (`focus`). | +| `isDragging(button?)` | Whether a drag is in progress, with that button if given. | +| `getDragState()` | Where the drag started, where it is, and how far it moved. | +| `getWheelState()` | The scroll wheel movement. | + +Mouse positions use the viewport, so they match the coordinates you draw with. + +## Controllers + +`ControllerLibrary` reads gamepads with the browser Gamepad API, in the standard layout. Buttons are members of `ControllerButton` (`A`, `B`, `X`, `Y`, `LeftBumper`, `Start`, `DPadUp`...), axes of `ControllerAxis`. + +```ts +if (ctx.controller.isButtonJustPressed(ControllerButton.A)) { + // jump, once per press +} +const stick = ctx.controller.getStick("left"); // x and y, from -1 to 1 +``` + +- Each method takes an optional controller index, `0` by default. +- `isButtonJustPressed` and `isButtonJustReleased` are true for one tick only. +- Small stick movements are reported as `0`. Change the threshold with `new ControllerLibrary({ deadzone: 0.2 })` (default `0.15`). +- `onConnect(listener)` and `onDisconnect(listener)` tell you when a controller is plugged in or out. `vibrate(effect)` makes it rumble where the browser supports it. diff --git a/docs/docs/navigation.json b/docs/docs/navigation.json index 953dc22..45dee5d 100644 --- a/docs/docs/navigation.json +++ b/docs/docs/navigation.json @@ -4,12 +4,22 @@ "pages": [ "getting-started/index", "getting-started/how-to-use", + "getting-started/quickstart", + "getting-started/concepts", "getting-started/documentation" ] }, { - "group": "Registry", - "pages": ["registry/index", "registry/writing-web-assembly"] + "group": "Building a game", + "pages": [ + "ecs/index", + "graphics-2d/index", + "input/index", + "audio/index", + "assets/index", + "scene/index", + "env/index" + ] }, { "group": "Network", @@ -32,20 +42,7 @@ "pages": ["editor/protocol"] }, { - "group": "Design notes", - "pages": [ - "graphics-3d/editor-proposal", - { - "group": "3D graphics library benchmark", - "pages": [ - "lib-graphic-3d/index", - "lib-graphic-3d/three-js", - "lib-graphic-3d/babylon-js", - "lib-graphic-3d/playcanvas", - "lib-graphic-3d/luma-gl", - "lib-graphic-3d/poc" - ] - } - ] + "group": "ECS internals", + "pages": ["registry/index", "registry/writing-web-assembly"] } ] diff --git a/docs/docs/network/index.mdx b/docs/docs/network/index.mdx index a3ea091..944c8b5 100644 --- a/docs/docs/network/index.mdx +++ b/docs/docs/network/index.mdx @@ -1,22 +1,114 @@ --- -title: "Network Overview" -icon: "book" -description: "Overview of the engine networking docs" +title: "Network" +icon: "network-wired" +description: "Add multiplayer to a game: set up the network libraries and their environment variables" --- -This page describes the engine's networking libraries: `network-server` and `network-client`. Together they provide a small, pragmatic networking layer used by the example `pong-network` game. The same apps can also run without a game server, hosted by one of the players. +`@nanoforge-dev/network` connects game clients to a game server. It has one library per side: -## Goals +| Library | Import from | Runs on | +| ---------------------- | ------------------------------- | -------------------- | +| `NetworkClientLibrary` | `@nanoforge-dev/network/client` | the client (browser) | +| `NetworkServerLibrary` | `@nanoforge-dev/network/server` | the server (Bun) | -- Keep the protocol minimal and predictable for multiplayer games. -- Let each packet pick its delivery guarantees through four channels: reliable or unreliable, ordered or unordered. -- Use well-understood transports: TCP for the reliable channels and UDP (WebRTC) for low-latency, best-effort ones. +Shared definitions, such as `Channel` and `definePacket`, come from `@nanoforge-dev/network`. Both libraries are reached through `ctx.network`. -## Related Pages +Each packet goes on one of four [channels](./packet-framing): reliable or unreliable, ordered or unordered. Reliable channels use a TCP WebSocket; unreliable ones use WebRTC data channels, for low-latency updates such as positions. -- [Network Client](./network-client) -- [Network Server](./network-server) -- [Packet Channels](./packet-framing) -- [Network Server API](./network-server-api) -- [Network Client API](./network-client-api) -- [Peer-to-peer Networking](./network-peer) +A game can also run without a dedicated server: one player's browser hosts the game. See [Peer-to-peer](./network-peer). + +## Set up a client and a server + +Create the project with a server: `nf new` and answer **yes** to the server prompt. It generates `apps/client` and `apps/server`, each with its network library registered. Put the packet definitions both sides use in a shared file: + +```ts shared/protocol.ts +import { Channel, definePacket } from "@nanoforge-dev/network"; + +export const Input = definePacket<{ key: "up" | "down" }>("input"); +export const Move = definePacket<{ id: number; x: number; y: number }>("move", { + channel: Channel.UnreliableOrdered, +}); +``` + +Register the client library: + +```ts apps/client/src/main.ts +import { NetworkClientLibrary } from "@nanoforge-dev/network/client"; + +const network = new NetworkClientLibrary(); +app.use(network); +await app.init(options); // connects to the server +``` + +And the server library, with the server ECS: + +```ts apps/server/src/main.ts +import { EcsLibrary } from "@nanoforge-dev/ecs/server"; +import { NetworkServerLibrary } from "@nanoforge-dev/network/server"; + +const app = NanoforgeFactory.createServer({ tickRate: 60 }); +const network = new NetworkServerLibrary(); +app.use(new EcsLibrary()); +app.use(network); +await app.init(options); // starts listening +``` + +- The client connects during `app.init`, which rejects when the server can't be reached within 10 seconds. +- Each tick, the network library runs before the ECS: the packets received are ready for your systems. +- `NetworkServerLibrary` needs the Bun runtime, which `nf` uses to run servers. +- With pnpm, a bundled server can fail to start with `Cannot load native addon for node-datachannel`. Add this to `pnpm-workspace.yaml`: + + ```yaml + publicHoistPattern: + - "@node-datachannel/*" + ``` + +Then send and receive packets: see [Client networking](./network-client) and [Server networking](./network-server). The [pong-network example](https://github.com/NanoForge-dev/Engine/tree/main/example/pong-network) is a complete game. + +## Environment variables + +Both libraries read their settings from the environment, validated at `app.init`. Set them in the project's `.env` file: prefix a variable with `NANOFORGE_CLIENT_` for the client, `NANOFORGE_SERVER_` for the server, or `NANOFORGE_` for both. See [Environment](../env/index) for where secrets may go. + +```dotenv .env +NANOFORGE_CLIENT_SERVER_ADDRESS=127.0.0.1 +NANOFORGE_CLIENT_SERVER_TCP_PORT=4445 +NANOFORGE_CLIENT_SERVER_UDP_PORT=4444 +NANOFORGE_SERVER_LISTENING_TCP_PORT=4445 +NANOFORGE_SERVER_LISTENING_UDP_PORT=4444 +``` + +Client variables: + +| Variable | Default | Meaning | +| ----------------- | ------- | ------------------------------------------------------------------------------ | +| `SERVER_ADDRESS` | none | **Required.** The server's IP address or URL (`ws`, `wss`, `http` or `https`). | +| `SERVER_TCP_PORT` | none | The server's TCP port. Needed for the reliable channels. | +| `SERVER_UDP_PORT` | none | The server's UDP signaling port. Needed for the unreliable channels. | +| `WSS` | `false` | `true` to connect with secure WebSockets. | + +Server variables: + +| Variable | Default | Meaning | +| --------------------- | --------- | --------------------------------------------------------------------------------------------------- | +| `LISTENING_TCP_PORT` | none | Port of the reliable channels. | +| `LISTENING_UDP_PORT` | none | Port of the unreliable channels' signaling. | +| `LISTENING_INTERFACE` | `0.0.0.0` | Address the server binds to. | +| `WSS_CERT`, `WSS_KEY` | none | Paths to a TLS certificate and its key, for secure WebSockets. Set both or neither. | +| `ICE_PORT` | none | One fixed UDP port for every WebRTC connection, so a firewall or port forward can allow it. | +| `ADVERTISE_IP` | none | Public IP written into the server's WebRTC candidates, when it runs behind a NAT or in a container. | + +Both sides: + +| Variable | Default | Meaning | +| -------------- | ----------------------------- | ------------------------------------------------------------------------------------------ | +| `NETWORK_MODE` | `dedicated` | `dedicated` or `p2p` (see [Peer-to-peer](./network-peer)). | +| `ICE_SERVERS` | a list of public STUN servers | STUN and TURN servers for WebRTC: comma-separated URLs (`stun:host:port`) or a JSON array. | + +The client fails at start-up when it has neither port, and the server when it has neither listening port. A channel whose port is not set throws when used, except on a [peer-to-peer](./network-peer) host, where every channel works. + +## Pages in this section + +- [Client networking](./network-client) and [Server networking](./network-server): send and receive data and typed packets, identify clients. +- [Peer-to-peer](./network-peer): let a player host the game. +- [Packet channels](./packet-framing): what each channel guarantees and how packets are framed. +- [Client API](./network-client-api) and [Server API](./network-server-api): every method and type. diff --git a/docs/docs/network/network-client-api.mdx b/docs/docs/network/network-client-api.mdx index c6739a0..488023b 100644 --- a/docs/docs/network/network-client-api.mdx +++ b/docs/docs/network/network-client-api.mdx @@ -1,10 +1,12 @@ --- -title: "network-client API" +title: "Network client API" icon: "book" -description: "API reference for the client networking package" +description: "Reference of NetworkClientLibrary, from @nanoforge-dev/network/client" --- -`NetworkClientLibrary` is exposed on `ctx.network`. Its methods take an optional +Register `NetworkClientLibrary` from `@nanoforge-dev/network/client`. Systems +reach it through `ctx.network`, which exposes the methods below; the library +instance has them too. They take an optional `{ channel }` to pick one of the four [channels](./packet-framing): `Channel.ReliableOrdered`, `Channel.ReliableUnordered`, `Channel.UnreliableOrdered` or `Channel.UnreliableUnordered`. @@ -17,14 +19,7 @@ TCP connects first, then UDP with the TCP session token, so both share one clien id. `__init` rejects when a transport fails, or when its channels are not open within 10 seconds. -```ts -import { Channel } from "@nanoforge-dev/network/client"; - -ctx.network.sendData({ type: "join" }); // Channel.ReliableOrdered -ctx.network.sendData({ x: 1, y: 2 }, { channel: Channel.UnreliableOrdered }); - -const messages = ctx.network.getReceivedPackets().map((packet) => packet.json()); // every channel -``` +The [client guide](./network-client) has examples. ## sendData(data, options?) @@ -128,6 +123,12 @@ reload gets a new id. Type: `string | undefined` +## roomCode and inviteLink + +In [peer-to-peer](./network-peer) mode, the code of the room the client hosts +or joined, and a link other players open to join it. See the peer-to-peer page +for when they are set. + ## NetworkPayload What `sendData` accepts. Its payload carries no format tag: the receiver reads diff --git a/docs/docs/network/network-client.mdx b/docs/docs/network/network-client.mdx index 8fabfc7..893a780 100644 --- a/docs/docs/network/network-client.mdx +++ b/docs/docs/network/network-client.mdx @@ -1,10 +1,10 @@ --- -title: "Client Networking (network-client)" +title: "Client networking" icon: "book" -description: "How the client-side networking package works" +description: "Connect a client to a server and send and receive packets" --- -This document describes how the `network-client` package connects to a `network-server` instance and the concrete APIs used from client-side code. +`NetworkClientLibrary`, from `@nanoforge-dev/network/client`, connects the game client to a server. See [Network](./index) to register it and set its environment variables. ## Overview diff --git a/docs/docs/network/network-peer.mdx b/docs/docs/network/network-peer.mdx index b6ea18b..9c2c77a 100644 --- a/docs/docs/network/network-peer.mdx +++ b/docs/docs/network/network-peer.mdx @@ -27,7 +27,9 @@ export default defineConfig({ }); ``` -The environment is the same as with a dedicated server: +The environment is the same as with a dedicated server. The `nf` CLI removes the +`NANOFORGE_CLIENT_` and `NANOFORGE_SERVER_` prefixes, so the library reads +`SERVER_ADDRESS`, `LISTENING_TCP_PORT` and so on: ```dotenv NANOFORGE_CLIENT_SERVER_ADDRESS=127.0.0.1 @@ -94,12 +96,13 @@ export const showInvite = (registry: Registry, ctx: Context) => { signaling server reports it gone, a data channel closes, or its connection fails. - **The host leaves.** The game ends: the signaling server closes the room, and - each player's `isConnected()` turns `false` about a second later. + each player's `isConnected()` turns `false` as soon as its signaling socket + closes. ## Limits -- **Message size.** Keep each packet at or below 64 KiB: WebRTC data channels - cap message size. +- **Message size.** The library does not split packets. Keep each one at or + below 64 KiB, a size the data channels of every browser accept. - **`ReliableUnordered` is really unordered**, unlike over a dedicated server's WebSocket. - **NAT.** A direct connection fails for some pairs of players, typically on @@ -118,14 +121,14 @@ export const showInvite = (registry: Registry, ctx: Context) => { JSON text frames, at most 64 KiB each: -| Who | Sends | Server forwards | -| ------ | ------------------------------------ | ------------------------------------- | -| Host | connects without a `room` | `{type:"room", room}` to the host | -| Player | connects with `?room=CODE` | HTTP 404 when the room does not exist | -| Player | any frame (its WebRTC offer and ICE) | `{type:"signal", from, data}` to host | -| Host | `{type:"signal", to, data}` | `data` to that player of its room | -| Player | closes | `{type:"leave", from}` to the host | -| Host | closes | close code `4001` to its players | +| Who | Sends | Server forwards | +| ------ | ------------------------------------------ | ------------------------------------- | +| Host | connects without a `room` | `{type:"room", room}` to the host | +| Player | connects with `?room=CODE` | HTTP 404 when the room does not exist | +| Player | any JSON object (its WebRTC offer and ICE) | `{type:"signal", from, data}` to host | +| Host | `{type:"signal", to, data}` | `data` to that player of its room | +| Player | closes | `{type:"leave", from}` to the host | +| Host | closes | close code `4001` to its players | The host welcomes a player (`{type:"welcome", id, token}`) once its data channels are open, so players speak the same protocol as with a dedicated UDP diff --git a/docs/docs/network/network-server-api.mdx b/docs/docs/network/network-server-api.mdx index 2f16ccb..030d17f 100644 --- a/docs/docs/network/network-server-api.mdx +++ b/docs/docs/network/network-server-api.mdx @@ -1,7 +1,7 @@ --- -title: "network-server API" +title: "Network server API" icon: "book" -description: "API reference for the server networking package" +description: "Reference of NetworkServerLibrary, from @nanoforge-dev/network/server" --- ## ClientId @@ -11,24 +11,18 @@ connected over both TCP and UDP has the same `ClientId` on both servers. ## Methods -`NetworkServerLibrary` is exposed on `ctx.network`. Its methods take an optional +Register `NetworkServerLibrary` from `@nanoforge-dev/network/server`. Systems +reach it through `ctx.network`, which exposes the methods below; the library +instance has them too. They take an optional `{ channel }` to pick one of the four [channels](./packet-framing): `Channel.ReliableOrdered`, `Channel.ReliableUnordered`, `Channel.UnreliableOrdered` or `Channel.UnreliableUnordered`. Reliable channels need `LISTENING_TCP_PORT` and unreliable ones -`LISTENING_UDP_PORT`. Using a channel whose port is not configured throws. +`LISTENING_UDP_PORT`. Using a channel whose port is not configured throws, +except on a peer-to-peer host, where every channel works. -```ts -import { Channel } from "@nanoforge-dev/network/server"; - -ctx.network.sendToAll({ type: "start" }); // Channel.ReliableOrdered -ctx.network.sendToAll({ x: 1, y: 2 }, { channel: Channel.UnreliableUnordered }); - -ctx.network.getReceivedPackets().forEach((packets, clientId) => { - const messages = packets.map((packet) => packet.json()); // every channel -}); -``` +The [server guide](./network-server) has examples. ### sendToAll(data, options?) @@ -47,7 +41,8 @@ Returns: `void` ### sendToClient(clientId, data, options?) Send a payload to one client. Logs an error when the client is not reachable on -the channel. +the channel. Throws a `TypeError` when `data` cannot be encoded as JSON +(`undefined`, a function). Parameter `clientId`: `ClientId` client identifier. @@ -125,31 +120,13 @@ Throws a `TypeError` when `data` cannot be encoded as JSON. Send a packet to one client, like `sendToAll`. -## NetworkPayload - -What `sendToAll` and `sendToClient` accept. Their payload carries no format -tag: the receiver reads a packet the way it was sent. - -| Value | Encoded as | Read back with | -| -------------------------------------------------- | --------------------- | ----------------------------- | -| `Uint8Array`, `ArrayBuffer`, any `ArrayBufferView` | The bytes as they are | `bytes()` or `arrayBuffer()` | -| `string` | UTF-8 text | `text()` | -| `NetworkData` | Its bytes, unchanged | What the original sender used | -| Any other value (object, array, number, …) | `JSON.stringify` text | `json()` | - -Passing a received `NetworkData` relays a client's packet as it is. - -## NetworkData - -One received packet. Its methods are synchronous and return a new value on -every call. +## NetworkPayload and NetworkData -| Method | Returns | -| --------------- | -------------------------------------------------------------------------- | -| `bytes()` | `Uint8Array`: the payload bytes. | -| `arrayBuffer()` | `ArrayBuffer`: the payload bytes. | -| `text()` | `string`: the payload decoded as UTF-8. | -| `json()` | `T`: the payload parsed as JSON. Throws a `SyntaxError` if it is not JSON. | +Payloads are encoded and read back the same way on both sides: see +[NetworkPayload](./network-client-api#networkpayload) and +[NetworkData](./network-client-api#networkdata) in the client API. Passing a +received `NetworkData` to `sendToAll` or `sendToClient` relays a client's packet +as it is. ## clients (`ctx.network.clients`) @@ -185,23 +162,23 @@ Returns: `() => void` that removes the listener. ## ClientInfo -| Field | Type | Description | -| ------------- | ------------------------------------------------ | ------------------------------------------------- | -| `id` | `ClientId` | Session identifier. | -| `connectedAt` | `number` | Timestamp (ms) of the first transport connection. | -| `transports` | `{ tcp?: ConnectionInfo; udp?: ConnectionInfo }` | Transports currently attached (live object). | +| Field | Type | Description | +| ------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | `ClientId` | Session identifier. | +| `connectedAt` | `number` | Timestamp (ms) of the first transport connection. | +| `transports` | `Partial>` | Transports currently attached (live object). `Transport` is `"tcp"`, `"udp"`, `"local"` (a peer-to-peer host's own player) or `"peer"` (a peer-to-peer player). | ## ConnectionInfo -| Field | Type | Description | -| ------------- | ------------------------ | ----------------------------------------------------------- | -| `transport` | `"tcp" \| "udp"` | Transport of this connection. | -| `address` | `string` | Remote address. | -| `port` | `number` | Remote port. | -| `family` | `string` | `"IPv4"` or `"IPv6"`. | -| `userAgent` | `string \| undefined` | `User-Agent` header of the upgrade request. | -| `origin` | `string \| undefined` | `Origin` header of the upgrade request. | -| `params` | `Record` | Query parameters of the upgrade request, without the token. | -| `connectedAt` | `number` | Timestamp (ms) of the upgrade request. | +| Field | Type | Description | +| ------------- | ------------------------ | ------------------------------------------------------------------------------------------- | +| `transport` | `Transport` | Transport of this connection. | +| `address` | `string` | Remote address, or `"unknown"` when the runtime can't tell (always on a peer-to-peer host). | +| `port` | `number` | Remote port, or `0` when unknown. | +| `family` | `string` | `"IPv4"`, `"IPv6"` or `"unknown"`. | +| `userAgent` | `string \| undefined` | `User-Agent` header of the upgrade request. | +| `origin` | `string \| undefined` | `Origin` header of the upgrade request. | +| `params` | `Record` | Query parameters of the upgrade request, without the token. | +| `connectedAt` | `number` | Timestamp (ms) of the upgrade request. | `Cookie` and `Authorization` headers are never recorded. diff --git a/docs/docs/network/network-server.mdx b/docs/docs/network/network-server.mdx index b47a89a..cc288cc 100644 --- a/docs/docs/network/network-server.mdx +++ b/docs/docs/network/network-server.mdx @@ -1,10 +1,10 @@ --- -title: "Server Networking (network-server)" +title: "Server networking" icon: "book" -description: "How the server-side networking package works" +description: "Accept clients, identify them, and exchange packets from the game server" --- -This document explains the `network-server` package implementation and the APIs used from server-side code. +`NetworkServerLibrary`, from `@nanoforge-dev/network/server`, accepts client connections in the game server. See [Network](./index) to register it and set its environment variables. ## Overview @@ -81,7 +81,7 @@ file (see [Typed packets](./network-client#typed-packets)). Its listeners and `read` also get the sender. ```ts -import { Input, Move, Play } from "../../shared/protocol"; +import { Input, Move } from "../../shared/protocol"; // listen once, after app.init() network.packets.on(Input, ({ key }, { clientId, ctx }) => { diff --git a/docs/docs/network/packet-framing.mdx b/docs/docs/network/packet-framing.mdx index 2770ac7..905fcba 100644 --- a/docs/docs/network/packet-framing.mdx +++ b/docs/docs/network/packet-framing.mdx @@ -21,7 +21,8 @@ useful once a newer one has arrived. The reliable channels need a TCP port (`SERVER_TCP_PORT` / `LISTENING_TCP_PORT`), the unreliable ones a UDP port (`SERVER_UDP_PORT` / `LISTENING_UDP_PORT`). -Using a channel whose port is not configured throws. +Using a channel whose port is not configured throws, except on a +[peer-to-peer](./network-peer) host, where every channel works. Over TCP, `ReliableUnordered` is delivered in order in practice: it only promises that nothing is lost. diff --git a/docs/docs/registry/index.mdx b/docs/docs/registry/index.mdx index 17d61f9..ec541ea 100644 --- a/docs/docs/registry/index.mdx +++ b/docs/docs/registry/index.mdx @@ -1,9 +1,11 @@ --- -title: "Registry" +title: "Registry internals" icon: "book" -description: "Registry and WebAssembly notes" +description: "How the C++ ECS registry is exposed to JavaScript through WebAssembly" --- +This page is for contributors to the engine. To use the ECS in a game, see [ECS](../ecs/index). + The registry class is written in C++ and exposed to WebAssembly using Emscripten. That choice keeps the performance benefits of C++ for entity and component management while still making the code available to web applications. ## Design Choices diff --git a/docs/docs/registry/writing-web-assembly.mdx b/docs/docs/registry/writing-web-assembly.mdx index c9a4f76..7c27c16 100644 --- a/docs/docs/registry/writing-web-assembly.mdx +++ b/docs/docs/registry/writing-web-assembly.mdx @@ -1,9 +1,11 @@ --- -title: "Writing Web Assembly" +title: "Writing WebAssembly" icon: "book" -description: "Guidance for WebAssembly modules" +description: "Conventions for writing the engine's C++ WebAssembly modules" --- +This page is for contributors to the engine's C++ code. To use the ECS in a game, see [ECS](../ecs/index). + ## Code Splitting When writing WebAssembly modules, it is important to consider code splitting for readability and maintainability. We try to split binding and logic into separate files wherever possible. That keeps the codebase organized and makes it easier to navigate. diff --git a/docs/docs/scene/index.mdx b/docs/docs/scene/index.mdx new file mode 100644 index 0000000..948b67a --- /dev/null +++ b/docs/docs/scene/index.mdx @@ -0,0 +1,73 @@ +--- +title: "Scenes" +icon: "clapperboard" +description: "Split your game into menus, levels and overlays, and share values between them" +--- + +`@nanoforge-dev/scene` splits a game into scenes: a menu, each level, a pause screen. A scene creates what it needs when it is loaded and removes it when it is unloaded. + +## Write scenes + +A scene extends `Scene` and overrides `load(ctx, scene)` and `unload(ctx)`. A scene that only spawns entities and adds systems can extend `EcsScene` from `@nanoforge-dev/ecs/scene` instead: write its `setup(registry, ctx)` like your `main`, and everything it spawns or adds is removed when the scene is unloaded. + +```ts +export class Menu extends Scene { + override load(ctx: Context) { + ctx.scenes.vars.init("score", 0, { persistent: true }); + } +} + +export class Level1 extends EcsScene { + override setup(registry: Registry) { + const enemy = registry.spawnEntity(); + registry.addComponent(enemy, new Position(400, 100)); + registry.addSystem(enemyAi); + } +} + +export class Pause extends Scene { + static override parent = Level1; +} +``` + +A static `parent` loads a scene under another one: here `Pause` keeps `Level1` loaded under it. + +## Register the library + +Give `SceneLibrary` the first scene, and every scene of the game by id: + +```ts +const scenes = new SceneLibrary({ initial: Menu, scenes: { Menu, Level1, Pause } }); +``` + +The keys of `scenes` are the scene ids. Name them yourself: a bundler can rename classes, never these keys. + +## Change scene + +From a system, or anywhere you have the context: + +```ts +void ctx.scenes.load(ctx, Level1); // unloads Menu, loads Level1 +void ctx.scenes.load(ctx, Pause); // Level1 stays loaded under Pause +void ctx.scenes.unload(ctx, Pause); + +ctx.scenes.vars.set("score", (ctx.scenes.vars.get("score") ?? 0) + 1); +``` + +- Only one chain of scenes is loaded at a time, from a root scene to the current one. Loading a scene unloads the scenes it does not share with the new chain, deepest first, then loads the missing ones, root first. +- Pass parameters with `ctx.scenes.load(ctx, Level1, { params })`. The scene reads them in `load(ctx, { params })`. Type them with `Scene<[params type]>`. +- Changes are queued and made when no system is running: right after the systems of the current tick, or before the systems of the next one. In a system, don't wait for the promise `load` returns. + +## Shared values + +`ctx.scenes.vars` holds values shared by scenes and systems: `init`, `get`, `set`, `has` and `remove`. A value belongs to the scene that created it and goes away when that scene is unloaded, unless you create it with `{ persistent: true }`. + +Type your values by augmenting `SceneVars`: + +```ts +declare module "@nanoforge-dev/scene" { + interface SceneVars { + score: number; + } +} +```