# Tide Engine documentation Source revision: 36904d8e07dd044bd665de823e6b8022ed4f4248 (modified working tree). Documentation SHA-256: ea38a553efadfaf8a016c33e947825b8c4d3d2005abcf32eb4f4a64094909e97. Website source checkout; not matched to an installed Tide release. Check tide version and the project toolchain. The language spec is omitted. Read [the spec separately](https://tide-engine.dev/spec.md) or download [the bundle with the spec](https://tide-engine.dev/llms-full-with-spec.txt). - [Tide Engine | Deterministic Multiplayer Game Engine](#doc-index) - [Introduction](#doc-guide) - [Install](#doc-guide--install) - [Editors](#doc-tools--editors) - [Your first game](#doc-guide--first-game) - [Using Tide with AI](#doc-guide--ai) - [Quick reference](#doc-guide--ai-context) - [Playground](#doc-guide--playground) - [Samples](#doc-guide--samples) - [Earth demo](#doc-guide--earth) - [Benchmarks](#doc-benchmarks) - [Components and entities](#doc-game--entities) - [Systems](#doc-game--systems) - [The schedule](#doc-game--schedule) - [Events](#doc-game--events) - [Commands](#doc-game--commands) - [Assets](#doc-game--assets) - [Build code](#doc-game--build-code) - [Scenes](#doc-game--scenes) - [State visibility](#doc-game--visibility) - [Endless worlds](#doc-game--endless-worlds) - [Async and tasks](#doc-game--tasks) - [Input](#doc-game--input) - [Views and drawing](#doc-game--views) - [Views and the match](#doc-game--views-and-the-match) - [Draw settings](#doc-game--draw-settings) - [Meshes and textures](#doc-game--meshes-and-textures) - [Drawing in 3D](#doc-game--3d) - [Skinned meshes and animation](#doc-game--animation) - [Cameras and coordinates](#doc-game--cameras) - [Render targets and post-processing](#doc-game--render-targets) - [Frags and verts](#doc-game--shaders) - [Audio](#doc-game--audio) - [Local state](#doc-game--local-state) - [Files and directories](#doc-game--files) - [GUI](#doc-game--gui) - [Good-looking UI](#doc-game--ui-style) - [Packages](#doc-packages) - [Using and writing packages](#doc-packages--using-and-writing) - [Render2D](#doc-packages--render2d) - [Render3D](#doc-packages--render3d) - [Corner Culling](#doc-packages--cornerculling) - [Geometry](#doc-packages--geometry) - [Particles](#doc-packages--particles) - [Box2D: 2D physics](#doc-packages--box2d) - [Box3D: 3D physics](#doc-packages--box3d) - [Rooms](#doc-packages--rooms) - [Lobby: lobbies and matchmaking](#doc-packages--lobby) - [Steam](#doc-packages--steam) - [Voice chat](#doc-packages--voice) - [Matches](#doc-multiplayer--matches) - [Managed hosting](#doc-multiplayer--hosting) - [Shards](#doc-multiplayer--shards) - [Your own network and service](#doc-multiplayer--own-network) - [Networking](#doc-multiplayer--networking) - [Determinism](#doc-multiplayer--determinism) - [Basics](#doc-language--basics) - [Structs and functions](#doc-language--functions) - [Generic functions](#doc-language--generics) - [Errors](#doc-language--errors) - [Math](#doc-language--math) - [Text and lists](#doc-language--text-and-lists) - [JSON](#doc-language--json) - [Grids](#doc-language--grids) - [Namespaces and files](#doc-language--namespaces) - [Virtual and override](#doc-language--overrides) - [The tide command](#doc-tools--cli) - [Tide Motion](#doc-tools--motion) - [Debugging](#doc-tools--debugging) - [Debug views](#doc-tools--debug-views) - [Dev tools](#doc-tools--dev-tools) - [Usage data](#doc-tools--telemetry) - [Calling C](#doc-c--functions) - [C hosts](#doc-c--hosts) - [A game's own network](#doc-c--network) --- Source: https://tide-engine.dev/index.md Build multiplayer games with Tide Engine: deterministic simulation, rollback netcode and an ECS language that compiles to native code or WebAssembly. # Tide Engine A networking-first game engine. One deterministic simulation that every player shares, on desktop or in the browser, written in a language made for it. [Get started](#doc-guide) · [Browse samples](#doc-guide--samples) · [Install](#doc-guide--install) **Multiplayer by default**: Rollback netcode with full server authority. Clients have no input delay, and single-player is a match too, so there's only one path to get right. **Deterministic floats**: The same build and the same inputs give the same bits on every platform, the web included. Plain floats, no fixed point. **A language for the ECS**: Games are written in Tide, a language of its own, built around the ECS. Systems say what they read and write, and the compiler works out the rest. It compiles to C, then to native code or WebAssembly. **A schedule you can read**: The compiler knows every system's data, so it plans which ones can run at the same time, and tells you why the others wait. **The web is a real platform**: Every game also builds as one self-contained web page on WebGPU, running the same simulation as desktop. **Nothing to set up**: One tide command, with clang built in. Write a .tide file and run tide run. Editor support for VS Code and JetBrains IDEs. Explore the [ECS benchmarks](#doc-benchmarks) for measured workloads, implementation details and comparison methodology. ## A whole game A game is a folder of `.tide` files, and needs no other code. This one bounces a ball: ```csharp component Ball { float2 position; float2 velocity = float2(160, 120); } scene Main { } event(Spawned) Setup(with Main) { Spawn(Ball); } system Move(mut Ball ball, Time time) { ball.position += ball.velocity * time.dt; if (Math.Abs(ball.position.x) > 300) ball.velocity.x = -ball.velocity.x; if (Math.Abs(ball.position.y) > 200) ball.velocity.y = -ball.velocity.y; } view DrawBalls(Ball ball) { Draw.Circle(ball.position, 20, Color.red); } ``` Save it as `game.tide`, then run `tide run --stats` in its folder. [Install tide](#doc-guide--install) to get started, or see [your first game](#doc-guide--first-game) for a longer tour. --- Source: https://tide-engine.dev/guide.md Learn how Tide Engine combines deterministic multiplayer, an ECS and its own language to build games for desktop, Android and the web. # Introduction Tide is a game engine built for multiplayer first. Its simulation is deterministic: given the same inputs and commands, it gives the same results on every machine, down to the last bit of every float. Players on desktop, Android and the web share one world, with their inputs and commands driving it. Games are written in **Tide**, a language of its own, built around an ECS. It compiles to C, and the C to native code or WebAssembly, together with the engine, so calls between your code and the engine's cost nothing. **Warning: Early days** Tide is young, and its language changes freely until 1.0. The [language spec](https://tide-engine.dev/spec.md) says which parts are decided and which are still provisional. ## The big ideas **A game is data and systems.** Entities are made of components, which are plain data. Systems are code that runs every tick, once for each entity that has the components it asks for. Singletons hold what there's one of per world, like the score or the rules. ```csharp component Health { int value = 100; } component Poisoned { } system Poison(mut Health health, with Poisoned) { health.value -= 1; } ``` **Systems say what they touch.** `mut` means a system writes a component, and a plain parameter means it only reads it. `with` and `without` pick entities without reading anything. From that, the compiler plans which systems can run at the same time and which have to wait, and shows you why (see [the schedule](#doc-game--schedule)). **Everything is a match.** The simulation, called the match, is what every machine runs the same way. It runs on a server, and even single-player is a match on a server this machine runs itself. The engine has rollback netcode built in: clients predict ahead and correct themselves when the server disagrees. See [Matches](#doc-multiplayer--matches). **Local state is everything else.** Menus, settings, particles and the camera belong to one machine and are never sent. **Views** read the match and draw it once per frame, and they can change local state but never the match. The compiler enforces that boundary, so a view can't break the simulation by accident. **Players act through inputs and commands.** Movement and held buttons reach the match as [input](#doc-game--input), sampled once per tick and sent over the network. One-off actions, like choosing a team or sending a chat message, use [commands](#doc-game--commands), which the server puts into a tick. Both enter the simulation through match code; views draw the result. ## A tick and a frame The match advances in fixed **ticks**, 60 per second by default: 1. Systems run, in a fixed order that's the same on every machine. 2. Structural changes (spawning, adding and removing components, destroying) and events apply at the end of the tick, in the order they were made. The screen updates every **frame**, as fast as the display allows: 1. Views run, drawing the match blended between its last two ticks, so motion is smooth at any tick rate. 2. The GUI draws over the world. ## Where to go next - [Install tide](#doc-guide--install), then make [your first game](#doc-guide--first-game). - Give an AI coding agent the [Tide overview, starter prompt and optional skill](#doc-guide--ai). - Edit and hot reload a running game in the [Playground](#doc-guide--playground). - Read what a game is made of, a topic at a time, starting with [components and entities](#doc-game--entities). - See how machines share a match, and how the engine keeps them in step: [matches](#doc-multiplayer--matches), [networking](#doc-multiplayer--networking) and [determinism](#doc-multiplayer--determinism). - Find optional physics, menus and Steam integration in [Packages](#doc-packages), with setup and API docs for each bundled package. - Look things up in [the language](#doc-language--basics) and the [tide command](#doc-tools--cli). - Browse the [samples](#doc-guide--samples) to play complete games in your browser, alone or with friends. --- Source: https://tide-engine.dev/guide/install.md Install the tide command on Windows, Linux or macOS, with built-in clang for native and web games, and learn how to update it. # Install Tide comes as one command, `tide`, which builds and runs games. It has its C compiler built in (clang), for native and web games alike. ## Windows In PowerShell: ```powershell Invoke-RestMethod https://tide-engine.dev/install.ps1 | Invoke-Expression ``` Windows needs nothing else: `tide` brings the headers and libraries games build with. ## Linux and macOS ```sh curl -fsSL https://tide-engine.dev/install.sh | sh ``` The installer uses `curl`, `tar` and `python3`. Native games also need the system's own headers and libraries: - **Linux** (x64): your distribution's C development files, which come with gcc: `sudo apt install build-essential` on Debian and Ubuntu, `sudo dnf install gcc` on Fedora. Playing in [rooms](#doc-multiplayer--matches--rooms) needs OpenSSL's `libssl` too, which nearly every distribution has, and so do the players of your game. - **macOS** (Apple Silicon): Apple's command-line tools, `xcode-select --install`. Install them before tide: they bring the `python3` the installer uses. ## What the installer does It installs `tide` for your user, in `%LOCALAPPDATA%\Tide` on Windows or `~/.tide` elsewhere, and puts its `bin` folder on your `PATH`: the user's `PATH` on Windows, and elsewhere a line in your shell's profiles (`~/.zshrc`, `~/.bashrc`, `~/.profile` and the like, or fish's `conf.d`). It needs no admin rights. Open a new terminal afterwards so the `PATH` change applies, then check it worked: ```sh tide version ``` This shows tide's version and channel, where it's installed, and which compilers it found. The installer also adds Tide to VS Code, Cursor, VSCodium and Windsurf when it finds them, and to existing JetBrains IDE profiles (2024.2+). JetBrains gets the plugin bundled with your Tide version, including LSP4IJ when missing; restart the IDE to load it. Open a new JetBrains IDE once before running `tide editors`. If you run the installer again when `tide` is already there, it upgrades it instead, on the channel it's on unless you set `TIDE_CHANNEL`, and adds Tide to editors installed since. ## Set up your editor See [Editor setup](#doc-tools--editors) for VS Code, JetBrains, Emacs, Vim and Neovim. Tide includes the Emacs and Vim/Neovim modes. Run the command for your editor, then copy its output into your init file: ```sh tide ide emacs tide ide vim tide ide neovim ``` Prefer your existing package manager? Install the MIT plugins through [Emacs's built-in package-vc](#doc-tools--editors--emacs) or [vim-plug/lazy.nvim](#doc-tools--editors--vim-and-neovim). Those instructions link the official public repositories and explain how to connect to Tide's language server. The Emacs mode installs directly from GitHub; it is not on MELPA yet. ## Nightly versions Stable versions come out now and then. Nightly versions are previews published when ready. For a nightly version, set `TIDE_CHANNEL` before running the installer: ```powershell [Windows] $env:TIDE_CHANNEL = 'nightly' Invoke-RestMethod https://tide-engine.dev/install.ps1 | Invoke-Expression ``` ```sh [Linux and macOS] curl -fsSL https://tide-engine.dev/install.sh | TIDE_CHANNEL=nightly sh ``` **Tip** This site follows development, so it describes the nightly version. Some of what it shows may not be in the stable version yet. ## Stay up to date ```sh tide upgrade # the newest version of your channel tide upgrade --nightly # switch to nightly versions tide upgrade --stable # back to stable ones ``` `tide` also tells you, at most once a day, when a new version is out. Upgrades check every download against the release's checksums. `tide upgrade` only ever moves forward. Switching channels, or `tide upgrade --version `, installs what you ask for, even an older version. An upgrade replaces tide while your editor and your games keep running. When it can't replace a file, because another program is reading it, it stops and says which one. Until it's finished, `tide` builds no games and says the installation isn't whole: close what had the file open and run `tide upgrade` again, which installs the version again even when it's the newest already. ## Uninstall Delete the folder tide is in (`tide version` says where), and the line that puts its `bin` folder on your `PATH`: on Windows, in **Edit environment variables for your account**; elsewhere, the lines after `# tide` in your shell's profiles, or fish's `conf.d/tide.fish`. Remove the Tide extension from your editors as you would any other. If you opted into Windows prefab registration, remove `HKEY_CURRENT_USER\Software\Classes\Tide.Prefab` and the `Tide.Prefab` value under `HKEY_CURRENT_USER\Software\Classes\.tprefab\OpenWithProgids` in Registry Editor. Keep any other applications' values. --- Source: https://tide-engine.dev/tools/editors.md Set up Tide in VS Code, JetBrains, Emacs, Vim or Neovim with highlighting and language server support. # Editors Local worker declarations share normal function navigation and diagnostics. Hovers and symbol outlines identify them as `local worker`; syntax highlighting recognizes the modifier without reserving `worker` as an ordinary variable name. ## Choose your editor [Install Tide](#doc-guide--install) first, then choose your setup: | Editor | Setup with Tide | Install through your editor's package manager | |---|---|---| | [VS Code, Cursor, VSCodium and Windsurf](#doc-tools--editors--vs-code-cursor-vscodium-and-windsurf) | `tide editors` | Installed by Tide | | [JetBrains IDEs](#doc-tools--editors--jetbrains-ides) | Installed with Tide; run `tide editors` for a new IDE | Bundled plugin; Marketplace also available | | [Emacs 29.1+](#doc-tools--editors--emacs) | `tide ide emacs` | [tide-emacs](https://github.com/Tide-Engine/tide-emacs) with built-in `package-vc` | | [Vim 8+](#doc-tools--editors--vim-and-neovim) | `tide ide vim` | [tide-vim](https://github.com/Tide-Engine/tide-vim) with vim-plug | | [Neovim 0.11+](#doc-tools--editors--vim-and-neovim) | `tide ide neovim` | [tide-vim](https://github.com/Tide-Engine/tide-vim) with lazy.nvim | For Emacs, Vim and Neovim, the `tide ide` commands print configuration to copy into your init file; the modes and matching language server already come with Tide. If you prefer your existing package manager, follow the install examples in [Emacs](#doc-tools--editors--emacs) or [Vim and Neovim](#doc-tools--editors--vim-and-neovim) below instead. Choose one installation method per editor. VS Code and JetBrains select a trusted project's pinned Tide version for both the compiler and language server. Standalone games use `tide = ` in `tide.packages`; Unity projects use their locked Tide package and the installation Unity selected. Open Unity once to resolve and install that version. Installations selected with Unity's `-tide-command ` are used only while that editor process is alive; closing it or a crash returns the IDE to the pin. Installations are shared in `TIDE_VERSIONS` (by default `%LOCALAPPDATA%/Tide/versions` or `~/.tide/versions`). A missing pinned version is reported rather than silently using another. Package/lock changes restart the language server; separate VS Code workspace folders and separate JetBrains projects can use different versions. Explicit executable settings and a trusted engine checkout's built server take precedence. In VS Code, `tide.path` also selects its sibling language server unless `tide.server.path` is set. Emacs/Vim/Neovim retain their configured server command. The standalone Emacs and Vim/Neovim plugins are MIT-licensed. **Emacs users: the mode is available directly from GitHub now, but is not listed on MELPA yet.** The plugins need Tide installed separately for its `tidels` language server. ## Language server features Tide's language server, `tidels`, comes with `tide`. Open your game's folder, the one you run `tide run` in, and every `.tide` file in it is one game, with its [packages](#doc-packages--using-and-writing). The server provides these features across the game; which appear depends on your editor's language server client: - Image attribute completion offers `[Linear]` for assets and fields; hover explains sRGB sampling, alpha, valid formats and source-preserving GPU helpers. `Math.ToLinear` and `Math.ToDisplay` offer scalar, float3 and Color signatures. - Completion, and errors as you type, with quick fixes: a name spelled wrong, a missing `mut`, a missing or stray `out`, an error nothing handles, a name from another namespace, a local that's never read (which is faded), and a parameter that's never used (removed, or a component's made a `with` filter). - Enum assignments prioritize and preselect the expected enum type: after `zombie.state =`, `ZombieState` comes first, followed by its qualified members. With [enum shorthand](#doc-language--basics--enums-and-switch), `zombie.state = .` offers just that enum's members. A leading dot also completes members in typed declarations, returns, comparisons, enum switch cases and arguments whose parameter type is unambiguous. - Hovers, go to definition or to a value's type, find usages, the uses of a name highlighted, and rename. A prefab's hover is the prefab as its file writes it, its components and entities (a big one's first lines), and for one made in Unity, the Unity asset it's of. - Go to implementation, from an event to its handlers, from the input to its `Sample`, `Sanitize` and `Predict` and from a `virtual` declaration to its [override](#doc-language--overrides), and the call hierarchy: what calls a function, and what it calls. - Formatting, of a file or a selection, parameter hints and inlay hints. Parameter hints list every function that shares the name being called, with every parameter and its default, and follow an argument written by name; where an argument starts, completion offers the names the other parameters go by. Inlay parameter hints label written literal arguments; omitted defaults and arguments already written by name have no label. - The outline, symbols across the workspace's games, folding, growing a selection, and semantic highlighting. A shared package contributes the declarations active in each game that uses it, with identical symbols listed once. - After `asset`, completion offers the supported asset types as you start typing, with forms such as `Mesh`, `Grid2` and `Map`. Inside a list or map, it offers the supported element types; mesh vertex and contract arguments offer structs. Assets also complete by name, with their type's methods and parameter hints, including `Texture.Sample` in a frag or vert. They highlight as ordinary read-only variables; fields use the editor's property styling. The editor's theme chooses their colors. - A known [skinned model or animation asset](#doc-game--animation) exposes its clip names in completion: `hero.animations.idle` or `movement.run`. Hover shows each clip's original source name, and a model exposes its bone names, `defaultPose`, `blendShapes` and `Shaped` too. The editor reads the glTF JSON or FBX catalog without importing geometry or animation samples; invalid or unavailable metadata is diagnosed separately from an absent clip. Their asset paths complete `.glb`, `.gltf` and `.fbx` files. - Moving a declaration to a file of its own. - In a [Unity project](#doc-tools--cli--unity), a rename also edits the prefabs and scenes that use the name and the project's C#: a component, field, singleton, event, command, struct, enum, enum member or namespace renamed in Tide is renamed in the scripts of `Assets` and of the project's embedded and local packages, as the C# twins in `Packages/com.tide.game` name it (`_` added where C# needs it). Only references known to be the game's are edited: a member of a value known to be of the game's type (declared as it, a cast, `as`, a pattern, a generic call, or a field, property or method of the project's own classes, partial ones too), a type or namespace the file's usings make the game's, and doc comments' `cref`s. Other comment text, strings, other types' members of the same name and names a type of the project's own also has are left alone. - Enum completion includes `EnumType.Count()` and `EnumType.Values()`; hover and signature help explain the compile-time member count and the array of every member, with its length. A cast written as `(int)value` reports the Tide spelling, `int(value)`. - [Assets](#doc-game--assets) kept in step with their files: renaming a file an `asset` names, or a folder above it, in the editor rewrites every path to it, in every file of the game and its packages, each relative to its own file (a glob isn't rewritten: a file it stops matching gets an error instead). Changes to watched asset files refresh their diagnostics, including external glTF buffers and replacement files that keep the same size and timestamp. A file moved outside the editor is found again by its bytes, which `tidels` and `tide` keep the SHA-256 of in the game's `.tide/`: the error says where it is now, with a quick fix that writes the path, or else lists the files of that name, a fix each. Inside an `asset`'s path, completion offers the folders and files it can lead to, the type's own files (`.png`, `.psd`, `.jpg`, `.jpeg`, `.tga` and `.bmp` for a `Grid2`, `Texture`, `Cubemap` or `TextureArray`; `.wav`, `.ogg`, `.mp3` and `.flac` for a `Clip`; `.glb`, `.gltf`, `.fbx` and `.obj` for a `Mesh`; `.glb`, `.gltf` and `.fbx` for a `SkinnedMesh`, `Animation` or `AnimationCatalog`), and `*` and `**/*` with each accepted format for a list, map, cubemap, texture array or combined `AnimationCatalog` catalog. Each literal in an animation file list supports the same path completion and rename edits; checked clip completion cleans exporter names and shows original names and source filenames on hover. Hovering a [`Mesh`](#doc-game--assets--meshes) asset says what its file has: how many vertices and triangles, and whether it has normals, uvs, colors and tangents for the vertex struct to take. - Each system's place in [the schedule](#doc-game--schedule) above it: its stage, what it reaches through its `World`, each system it waits for and why, what runs alongside it, and for a system that runs for each entity, whether its entities go across threads or what keeps them on one (clicking that goes to the place in its code). A part that names a system goes to it when clicked. - Above a declaration a package replaced, which package did, and above an [override](#doc-language--overrides), what it replaces. A click goes to the other. - Above a declaration, how many places name it ("3 references"), which a click lists: types, functions, methods, constants, assets, frags and verts, where "0 references" is code nothing uses. A system, view or handler has the line only when a `[Before]` or `[After]` names it. - Above functions and methods, an **entry points** lens traces callers through helpers to the systems, views, event or command handlers that can reach them. Input `Sample`, `Sanitize` and `Predict`, custom `Interpolate` methods and audio callbacks are entry points too. Clicking a single entry point goes to its declaration; several open a list to choose from. Each entry point counts once, even through several paths or recursive calls. This is static call reachability, independent of runtime branches; tracing stops at handlers rather than following event sends or command submissions. A helper with no known root says **0 entry points**. The call hierarchy lets you inspect the intermediate calls. ## VS Code, Cursor, VSCodium and Windsurf VS Code and JetBrains recognize `.tprefab` files as Tide. They use the same game/package context as scripts, report invalid authored components and references, and include prefab files when renaming components, fields and named prefabs. Language-server rename/completion for authored entity names and paths remains limited. See [Authored prefabs](#doc-game--scenes--authored-prefabs) for the text format. The installer adds Tide to the ones it finds, and `tide upgrade` keeps it up to date. Installed one later? Run: ```sh tide editors ``` An editor window that's open gets a newer extension once it's reloaded: **Developer: Reload Window**. Renaming a file or a folder in the Explorer asks `tidels` first, so the paths of the assets it holds follow it; the extension asks only about the files assets name, and the folders above them. Moving several files together updates all their asset paths in the same edit, across the games and shared packages affected by the move. A shared package's assets update every consuming game in the workspace. CMake games that list individual files with `SOURCES` work the same way. The extension runs `tidels` from your `PATH`, or from where `tide` is installed; in a folder with a `build/tools/tidels`, like Tide's own repo once it's built, it runs that one. The `tide.server.path` setting runs another one: in it, `~` is your home folder, and `${workspaceFolder}` and relative paths are the folder whose settings set it. After updating the server, run **Tide: Restart Language Server**. The `tide.trace.server` setting shows what the editor and the server say to each other, in the **Tide Trace** output. In a folder you haven't trusted (VS Code's Restricted Mode), nothing from it runs: the server is the `tidels` that comes with `tide`, or one your user settings name outside the workspace. Servers on `PATH` inside the workspace are skipped too, including paths through symlinks or junctions. Games don't run, since running one runs its code. Trusting the folder restarts the server. ### Running the game The play button above a `.tide` file runs its game, which is the folder you opened, or the folder of the game it's in when that has a `tide.packages` of its own; a [package](#doc-packages--using-and-writing)'s file runs the open game that lists it: - **Tide: Run** plays it in a window of its own, as `tide run` does. - **Tide: Run on the Web** plays it in a browser tab beside your code: VS Code's integrated browser, or the Simple Browser in editors without it. A game only gets keys while its tab has focus, and the editor may pause it while its tab is hidden, so keep it in a group of its own. - **Tide: Run on Android** plays it on the Android phone or emulator that's connected, as `tide run --android` does (see [Android](#doc-tools--cli--android)). Each runs `tide run` in a terminal of its own, so saving a file reloads the game (on Android, builds it again and starts it over), and typing `r` and Enter in that terminal starts it over. Running it again starts the game over. The first run on Android may ask to download Android's tools from Google: type `y` and Enter in that terminal to accept. The `tide.path` setting runs another `tide`. Starting a replacement waits for the preceding run's processes to stop. Closing its terminal stops the run too. If the editor cannot confirm cleanup, it explains how to stop the remaining processes before running again. On the web, each reload says what it did in the page's console: **Tide: Game Developer Tools** shows it. ### Debugging Breakpoints go in `.tide` files, and the **Tide** debug configurations (**Run and Debug**, then add a configuration) stop at them, with your values shown as Tide's: **Attach to Unity (Tide)**, **Debug Tide game**, which builds the game to debug and starts it, and **Attach to Tide game (tide run)**, for the game **Tide: Run** plays. They use Microsoft's C/C++ extension on Windows, and LLVM's LLDB DAP or CodeLLDB on macOS and Linux. In Restricted Mode they don't start. See [Debugging](#doc-tools--debugging). ## JetBrains IDEs CLion, Rider, IntelliJ and the others, 2024.2 or later: Tide's installer adds the bundled plugin to existing IDE profiles. It includes LSP4IJ when that dependency isn't installed, without a Marketplace download. `tide upgrade` updates Tide in profiles that already have it, using the plugin from the same Tide release. For an IDE installed later, open it once to create its profile, then run: ```sh tide editors ``` Restart the IDE after installation or an upgrade. If it holds the plugin's files open, close it and run `tide editors` again. Other plugins, settings and an existing LSP4IJ installation are preserved. A disabled Tide plugin stays disabled. Discovery uses the standard JetBrains profile locations on Windows, macOS and Linux (including Linux's `XDG_CONFIG_HOME` and `XDG_DATA_HOME`). Custom `idea.config.path` or `idea.plugins.path` locations need manual installation. You can also install Tide through **Settings > Plugins > Marketplace**; Marketplace updates follow its chosen channel independently of your CLI. The plugin runs the `tidels` chosen under **Settings > Languages & Frameworks > Tide**, if any; else the project's own `build/tools/tidels`, like Tide's repo once it's built, once you trust the project; else the one on your `PATH`, or where `tide` is installed. When there's none, `.tide` files say so above the code, with links to install `tide`, choose a `tidels`, or try again. The **Language Servers** tool window restarts the server, after an update, and shows what it and the IDE say to each other. Renaming a file or a folder (Refactor > Rename, or in the Project view) asks `tidels` first, so the paths of the assets it holds follow it. LSP4IJ asks about every file, and `tidels` answers from the game's assets. JetBrains' dark color schemes draw type names like plain text, so Tide's types stay uncolored until you pick colors. Each kind of type has its own color under **Settings > Editor > Color Scheme > Language Server**: - **Struct type**: components - **Classes > Class reference** and **Class declaration**: singletons - **Interface**: inputs - **Type**: built-in types such as `Color`, `Entity` and `Devices` ### Running the game Right-click a `.tide` file and pick **Run**, or press Ctrl+Shift+F10 in it (Ctrl+Shift+R on macOS), to run its game, which is the project's folder, or the folder of the game it's in when that has a `tide.packages` of its own; a [package](#doc-packages--using-and-writing)'s file runs the project's game when it lists the package. The run is named after the folder, like `mygame`: - **mygame** plays it in a window of its own, as `tide run` does. - **mygame (web)** plays it on the web, in the **Tide Game** tool window. Its **Open DevTools** button shows the page's console, where each reload says what it did. The game only gets keys while the tool window has focus. - **mygame (Android)** plays it on the Android phone or emulator that's connected, as `tide run --android` does (see [Android](#doc-tools--cli--android)). They're Tide run configurations, which you can also make and edit under **Run > Edit Configurations**, where **Play it** picks among the three. They use `tide run`. `tide`'s output is in the Run tool window, where an error's place links to the file: saving a file reloads the game (on Android, builds it again and starts it over), and typing `r` and Enter there starts it over. The first run on Android may ask to download Android's tools from Google: type `y` and Enter there to accept. A run configuration can run another `tide`. ### Debugging In CLion, breakpoints go in `.tide` files. **Run > Debug Tide Game** (also in a `.tide` file's context menu) plays the game as its run configuration does and attaches the debugger; **Run > Attach to Unity (Tide)** attaches to the Unity editor running the project. Both stop at your breakpoints and show your values as Tide's. On Windows, put the **Visual Studio** toolchain first, whose debugger reads the game's `.pdb`. See [Debugging](#doc-tools--debugging). ## Emacs ### Install with a package manager The official [tide-emacs repository](https://github.com/Tide-Engine/tide-emacs) can be installed directly with Emacs 29.1+'s package manager. Evaluate this once: ```elisp (require 'package-vc) (package-vc-install '(tide-lang-mode :url "https://github.com/Tide-Engine/tide-emacs")) ``` Add this to your init file: ```elisp (require 'tide-lang-mode) (add-hook 'tide-lang-mode-hook #'eglot-ensure) ``` Install Tide separately and put `tidels` on Emacs's `exec-path`. The package manager updates the mode; `tide upgrade` updates the compiler and server. Use **M-x package-vc-upgrade** to update the mode. A MELPA recipe is prepared, but the package is not listed there yet: its submission rules require a month of public maintenance and human review. ### Use Tide's bundled mode Tide bundles [tide-lang-mode](https://github.com/Tide-Engine/tide-emacs) for Emacs 29.1 or later. Run: ```sh tide ide emacs ``` Copy the result into your Emacs init file (usually `~/.emacs.d/init.el`), then restart Emacs. It loads the bundled mode, selects this installation's `tidels` by its full path and connects through Eglot when you open a Tide file. Emacs does not need `tidels` on its `exec-path` with this configuration. It detects `.tide` and `.tprefab`, with basic highlighting, four-space C-style indentation and comment editing. The name is separate from the TypeScript package called `tide`. To connect manually instead, omit the generated hook below and use **M-x eglot** in a Tide buffer. To select another server, change `tide-lang-server-command`: ```elisp (setq tide-lang-server-command '("/path/to/tide/bin/tidels")) ;; The helper includes this for automatic connection: (add-hook 'tide-lang-mode-hook #'eglot-ensure) ``` Use **M-.** for definitions, **M-?** for references, **C-M-i** for completion, **M-x eglot-rename** and **M-x eglot-format-buffer**. See [Eglot's setup guide](https://www.gnu.org/software/emacs/manual/html_node/eglot/Setting-Up-LSP-Servers.html) for client configuration. ## Vim and Neovim ### Install with a plugin manager The official [tide-vim repository](https://github.com/Tide-Engine/tide-vim) works directly with Git-based plugin managers. In an existing vim-plug setup, add this between `plug#begin()` and `plug#end()`, then run **:PlugInstall**: ```vim Plug 'Tide-Engine/tide-vim' ``` For lazy.nvim on Neovim 0.11+, add this plugin specification: ```lua { 'Tide-Engine/tide-vim', lazy = false, config = function() vim.lsp.enable('tidels') end, } ``` Install Tide separately and put `tidels` on `PATH`. Use your plugin manager to update the runtime and `tide upgrade` to update the compiler and server. Plain Vim still needs a separately configured LSP client. ### Use Tide's bundled runtime Tide bundles the [Tide Vim runtime](https://github.com/Tide-Engine/tide-vim) for Vim 8+ and Neovim. Print the configuration for your editor: ```sh tide ide vim tide ide neovim ``` Copy the Vim output into your vimrc (`~/.vimrc`, or `~/_vimrc` on Windows), or the Neovim output into `init.lua` (usually `~/.config/nvim/init.lua`, or `%LOCALAPPDATA%/nvim/init.lua` on Windows). Custom configurations can use the same output in their own init file. Restart the editor after adding it. Both `.tide` and `.tprefab` get highlighting, four-space C-style indentation and comment settings. Interpolated strings have string highlighting throughout. The Neovim configuration requires 0.11 or later and enables the supplied language server configuration automatically, using this installation's full `tidels` path. No `nvim-lspconfig` plugin or server lookup on `PATH` is needed. To select another executable, call `vim.lsp.config('tidels', { cmd = { '/path/to/tide/bin/tidels' } })` before enabling it. The configuration selects the nearest `tide.packages`, then a CMake/Git root, then the source file's folder. Use **K** for hover, `:lua vim.lsp.buf.definition()`, `:lua vim.lsp.buf.rename()` and `:lua vim.lsp.buf.format()`. Neovim's **:help lsp** describes completion and other client features; see its [LSP guide](https://neovim.io/doc/user/lsp/). Plain Vim needs a language server client of your choice. Register filetype `tide` with the server command printed in the snippet's comments, over stdio. The runtime does not install a client. These [setup helpers](#doc-tools--cli--ide) print configuration; they do not change your init files. If you move Tide, generate the configuration again and replace the old paths. `tide editors` installs the VS Code extension. Enable automatic server startup only for projects you trust. Choose either the package-manager copy or Tide's bundled copy of each mode; loading both can make it unclear which version your editor is using. Use `tide run` in a terminal for games. The terminal integrations do not adapt the VS Code-specific clickable code-lens commands. ## Other editors `tide`'s `editors` folder holds the TextMate grammar (`tide-syntax`), a VS Code-style bundle, for highlighting in editors that load those. Any editor with a language server client can run `tidels`, from `tide`'s `bin` folder, for everything else. It talks over stdin and stdout. --- Source: https://tide-engine.dev/guide/first-game.md Build your first Tide game with components, systems, input and drawing, then host a multiplayer match and invite another player. # Your first game This page builds a small game: a ball bouncing around, and a player for everyone who joins, which they steer with the keyboard. It takes a few minutes, and shows most of what a Tide game is made of. You'll need `tide` [installed](#doc-guide--install). [Set up your editor](#doc-tools--editors) for highlighting, completion and diagnostics before writing your first file. Working with an AI coding agent? Use the [Tide overview and starter prompt](#doc-guide--ai) to give it the language context and validation commands. ## A folder of files A game is a folder of `.tide` files: every `.tide` file in it and its subfolders, but for hidden ones, whose names start with a dot. Every declaration is visible from every file, with no imports. Make a new folder, and a file in it called `game.tide`. ## Data: components Entities are made of **components**, plain data with fields. Fields can have defaults, and start at zero otherwise. ```csharp component Body { float2 position; float2 velocity; float radius = 20; } component Ball { } ``` `Ball` has no fields: it marks which bodies are balls. ## Where it starts: the Main scene The game starts in the scene called `Main`. When it loads, it gets the built-in `Spawned` event, and a handler of that event sets it up: ```csharp scene Main { } event(Spawned) Setup(with Main) { Spawn(Body { velocity = float2(160, 120) }, Ball); } ``` `Spawn` makes an entity from a list of components. `Body { velocity = ... }` sets one field and leaves the others at their defaults, and a bare `Ball` has all of them at their defaults. ## Behavior: systems A **system** runs every tick, once for every entity that has the components it takes. Parameters are read-only, unless they're `mut`. `with Ball` only picks entities that have a `Ball`, without reading it. ```csharp system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } system Bounce(mut Body body, with Ball) { if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x; if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y; } ``` `Time` is a built-in singleton: there's one per world, and `time.dt` is the length of a tick in seconds. Systems run in the order they're written, and always in the same order on every machine. ## Drawing: views A **view** looks like a system, but it runs once per frame instead of once per tick, and it can only read the match. `Draw` functions only work in views. ```csharp view DrawBalls(Body body, with Ball) { Draw.Circle(body.position, body.radius, Color.red); } ``` The camera starts at the origin, one world unit per pixel, with `y` up. ## Run it In the folder: ```sh tide run --stats ``` `tide` compiles the game and opens a window with the ball bouncing. It keeps its work in a hidden `.tide` folder, which you can delete any time. Whenever you save, `tide` rebuilds the game and the window picks up the new code (see [hot reload](#doc-tools--cli--hot-reload)). This is the game so far, built for the web and running in the page: **The game so far** ([Run example](https://tide-engine.dev/examples/first-ball/?stats)) ```tide component Body { float2 position; float2 velocity; float radius = 20; } component Ball { } scene Main { } event(Spawned) Setup(with Main) { Spawn(Body { velocity = float2(160, 120) }, Ball); } system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } system Bounce(mut Body body, with Ball) { if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x; if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y; } view DrawBalls(Body body, with Ball) { Draw.Circle(body.position, body.radius, Color.red); } ``` The next part adds players. ## Players and input Each player's **input** is what the network sends of them, once per tick. It's declared once per game, and its `Sample` method fills it on the player's own machine, from this machine's `Devices`: ```csharp input Controls { float2 move; Sample(Devices devices) { var keys = devices.keyboard; if (keys.d.pressed) move.x += 1; if (keys.a.pressed) move.x -= 1; if (keys.w.pressed) move.y += 1; if (keys.s.pressed) move.y -= 1; } } ``` Keys are named by their position on a US keyboard, so `WASD` is in the same place on every layout. When a player joins, the world gets the built-in `PlayerJoined` event. This handler gives them a body, with an `Owner`, a built-in component that ties an entity to a player: ```csharp event(PlayerJoined joined) AddPlayer() { Spawn(Body { radius = 16 }, Owner { player = joined.player }); } ``` A system that takes the input gets the input of the player who owns the entity it's running for: ```csharp system Steer(Controls input, mut Body body, with Owner) { body.velocity = Math.Normalize(input.move) * 250; } ``` Put `Steer` before `Move`, so bodies move the tick they're steered. Last, draw the players. Views can read `Session`, where this machine stands, so yours can be yellow and the others gray: ```csharp view DrawPlayers(Body body, Owner owner, Session session) { var color = owner.player == session.player ? Color.yellow : Color.gray; Draw.Circle(body.position, body.radius, color); } ``` A view that's only for your own player, like a camera that follows them, picks them with a filter instead: `with ownership` (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)). Save, then type `r` and press Enter in `tide`'s terminal, and steer with `WASD`. The game carried over to the new code when you saved, but your player had joined before `AddPlayer` existed, so they had no body yet. Starting over makes them join again. ## Play together Single-player was already a match, on a server this machine ran for itself. So the same game plays with others. In one terminal: ```sh tide run --host --stats ``` And in another, on this machine or another one on the network: ```sh tide run --connect localhost --stats ``` Use the host's address instead of `localhost` from another machine, like `tide run --connect 192.168.1.5 --stats`. The host takes players on UDP port 7777; `--host 8000` picks another. Each player steers their own yellow body, with no input delay. Where nobody is there to steer (a test, a build server, an agent), `tide run --players 2 --frames 300 --capture match.png --stats` plays both at once with no window, and writes a picture from each machine: `match-1.png` and `match-2.png` (see [Several players](#doc-tools--cli--several-players)). No input delay means a machine doesn't wait to hear what the other players did: it guesses, by repeating their last input for a moment, and puts the match right when the server's answer arrives. That moves their body in one frame, each time they start or stop, by up to what they move in 0.15 seconds (see [What other machines guess](#doc-game--input--what-other-machines-guess)). Mark the position, and views draw the correction over a few frames instead: ```csharp component Body { [Position] float2 position; float2 velocity; float radius = 20; } ``` Only what's drawn changes: the match is put right at once, the same on every machine (see [correction smoothing](#doc-game--views--provisional-correction-smoothing)). Here are two machines in one match, each running [the whole game](#doc-guide--first-game--the-whole-game): the first hosts it, and the second joined its room, as `tide run --join` does with a room's code (see [Matches](#doc-multiplayer--matches--rooms)). Click a frame so it has the keyboard, and steer with `WASD`: its player is yellow there, and gray in the other frame. **Two players, in one match** ([Run example](https://tide-engine.dev/examples/first-game/?stats)) ## Build it for the web ```sh tide run --web --stats ``` This builds the game as a web page, which draws with WebGPU, and opens it in your browser. `tide` serves the page on your machine and keeps running until you stop it with Ctrl+C. Saving a file reloads the game in the page. For a page to put online: ```sh tide build --release --web ``` It goes in `.build/web/`, a folder to put online as it is: `index.html`, which shows the game downloading, and the game's files beside it, which browsers keep between visits. To try that page on your own machine, serve the folder (`npx serve .build/web`): a page opened from disk can't download its files. `tide build --release --web --single-file` makes one `.html` file with the game inside instead, which opens straight from disk. Web and desktop players play together in rooms, which they join by a code (see [Matches](#doc-multiplayer--matches--rooms)). ## The whole game Click the game so it has the keyboard, and steer with `WASD`. **game.tide** ([Run example](https://tide-engine.dev/examples/first-game/?stats)) ```tide component Body { [Position] float2 position; float2 velocity; float radius = 20; } component Ball { } input Controls { float2 move; Sample(Devices devices) { var keys = devices.keyboard; if (keys.d.pressed) move.x += 1; if (keys.a.pressed) move.x -= 1; if (keys.w.pressed) move.y += 1; if (keys.s.pressed) move.y -= 1; } } scene Main { } event(Spawned) Setup(with Main) { Spawn(Body { velocity = float2(160, 120) }, Ball); } event(PlayerJoined joined) AddPlayer() { Spawn(Body { radius = 16 }, Owner { player = joined.player }); } system Steer(Controls input, mut Body body, with Owner) { body.velocity = Math.Normalize(input.move) * 250; } system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } system Bounce(mut Body body, with Ball) { if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x; if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y; } view DrawBalls(Body body, with Ball) { Draw.Circle(body.position, body.radius, Color.red); } view DrawPlayers(Body body, Owner owner, Session session) { var color = owner.player == session.player ? Color.yellow : Color.gray; Draw.Circle(body.position, body.radius, color); } ``` ## Next - `tide schedule` shows which of these systems could run at the same time, and why the others wait. See [the schedule](#doc-game--schedule). - Read what a game is made of, a topic at a time, starting with [components and entities](#doc-game--entities). The language itself starts with [the basics](#doc-language--basics). - Browse the [samples](#doc-guide--samples) for complete games to play in your browser, with links to their source. --- Source: https://tide-engine.dev/guide/ai.md Give your AI coding agent a Tide overview, persistent project instructions and an optional portable skill, with downloadable Markdown documentation. # Using Tide with AI An AI agent can work with Tide without knowing it beforehand. Give it the [quick reference](#doc-guide--ai-context), access to the relevant references, and a compiler it can use to check its work. Start with the guide; add project instructions or the skill when you want the setup to carry across conversations. ## Start a conversation Copy the starter prompt above and add what you want to build. It points the agent to the compact overview and asks it to validate its changes. If your chat cannot fetch links, download the guide and attach it instead. For work needing more APIs without internet access, also attach the [full documentation bundle](https://tide-engine.dev/llms-full.txt); ask the agent to search the relevant topic rather than read it all at once. The starter prompt is also plain text: ```text This project uses Tide. Before writing code, read the project's instructions and https://tide-engine.dev/guide/ai-context.md (or the attached Tide overview). Use its linked topic references for exact APIs; https://tide-engine.dev/llms.txt is the documentation index. Inspect the existing project and run tide version. The website can be newer than the installed compiler; use project-pinned documentation when available and do not silently upgrade the toolchain. Build early, fix diagnostics, and validate the requested behavior with bounded hidden runs and captures when execution tools are available. Report what you actually tested and any unavailable coverage. Task: ``` Tell the agent the gameplay you want, the intended platforms and any existing project conventions. An agent with a terminal can compile and inspect captures. A chat without filesystem or execution tools can suggest code, but you will need to build and test it yourself. ## Play a game interactively An agent with process input/output and image tools can play the same running game dynamically: `tide run --interactive play.txt` draws its first frame and waits. Send `capture menu.png`, inspect the PNG, queue future-frame script lines such as `2 mouse 640 353` and `3 button left`, then send `step 30`. Wait for `tide: interactive ready 31`, inspect another capture and choose the next actions. The game waits while the agent thinks; `quit` or closing input ends it. Executed actions are saved to `play.txt` for normal scripted replay. For GUI widgets, `controls` lists each one with its label and position, and `click "Play"` (or `click 1`) clicks it. This works whatever size the picture is, with no guessing of pixels. For an agent's terminal tools, use a persistent terminal session (a PTY when needed) and retain its session handle. Launch the command without waiting for the game to exit. Write subsequent control lines to that same session. After `capture`, use the agent's image-viewing tool to actually inspect the picture, then choose the next input from what it shows. Keep repeating this loop in the same process; `play.txt` is the automatic recording, not a command inbox. The agent needs terminal-session input and image viewing, with no additional file control channel or game-specific integration. See [Interactive play](#doc-tools--cli--interactive-play) for the protocol, multiple players and limits. This uses ordinary player input and rendered pictures; it does not require game-specific agent code. ## Profile a game An agent can collect a structured report from the standard host without opening the profiler panel or writing a custom C host: ```sh tide run --release --script play.txt --frames 360 --profile profile.json --profile-warmup 60 ``` Set `TIDE_HIDDEN=1` in the agent's shell before native runs. Use a script that reaches the situation being investigated; interactive play can record it first. Keep the same seed, resolution, player count and saves for comparisons. The report is written when the run ends and identifies measured frames, CPU work, system/view source locations, GPU totals and per-pass timings with shader membership, and engine draw counters. For GPU optimization, rank `gpu_passes.rows` and inspect its coverage counters before changing rendering work. It measures actual work rather than treating the hidden run's fixed simulation step as a frame-time result. Capture is currently native desktop only. Check the schema version, measured-frame count, build metadata and dropped-row counters before ranking costs. Source locations identify declarations; worker rows are aggregate categories, and helpers remain inside their caller's time. Ask the agent to connect cost to useful work: for example, how many mesh instances were tested and rejected while recording an expensive view. A low culling rejection rate suggests inspecting earlier visibility selection; it does not prove culling can be removed, especially for another camera or shadow pass. Make one change, replay the same scenario in an optimized build, compare the report and inspect captures. Include simulation checks when the change could affect the match, and repeat measurements when noise could explain the difference. See [Profile captures](#doc-tools--debug-views--profile-captures) for timing meanings, limits and the culling example. ## Keep project context between conversations Put the [starter AGENTS.md](https://tide-engine.dev/ai/AGENTS.md) in your **game folder** and keep it in source control. Merge it into existing instructions rather than overwriting them. It points to the overview and contains game build/run guidance. Add your own project's important decisions and validation commands as they become established. This is separate from the Tide engine repository's contributor guide. [Codex reads AGENTS.md](https://learn.chatgpt.com/docs/agent-configuration/agents-md) as project instructions. Current [Claude Code versions can read AGENTS.md](https://code.claude.com/docs/en/memory#agentsmd), subject to their instruction-file settings. For a Claude setup that does not load it, put the [starter CLAUDE.md](https://tide-engine.dev/ai/CLAUDE.md) beside it; the file imports `AGENTS.md` rather than duplicating its rules. If you already have `CLAUDE.md`, add the import to it: ```text @AGENTS.md ``` Other agents have their own discovery rules. Explicitly ask your agent to read the project instructions if its client does not load them automatically. A web link alone is not guaranteed to be fetched or remembered in a new chat. For an offline project, save the overview as `TIDE.md` next to `AGENTS.md`; the starter instructions prefer that local copy. Keep its source-revision header when updating it. ## Install the optional Tide skill Download [tide-skill.zip](https://tide-engine.dev/ai/tide-skill.zip). It contains one `tide` folder with `SKILL.md` and a generated `references/overview.md`, the same overview shown in the docs. The skill guides an agent through version checks, topic lookup, implementation and bounded validation. It does not install Tide or grant the agent additional permissions. Extract the `tide` folder into your agent's project skill directory: - **Codex:** `.agents/skills/tide/`, with `SKILL.md` directly inside it. Invoke it as `$tide`, or let the agent select it for a matching task. See the [OpenAI skill documentation](https://learn.chatgpt.com/docs/build-skills). - **Claude Code:** `.claude/skills/tide/`, with `SKILL.md` directly inside it. Invoke it as `/tide`, or let Claude select it. See [Claude's skill documentation](https://code.claude.com/docs/en/skills). - **Other compatible agents:** install the folder using the client's [Agent Skills](https://agentskills.io/home) support. The format is portable; discovery and installation paths depend on the client. The skill and `AGENTS.md` serve different purposes: project instructions retain this game's rules, while the skill supplies a reusable Tide workflow. Either can use the same overview. No MCP server is required to read the docs or use the local compiler. ## Match the documentation to your tools Run `tide version` when starting a project or diagnosing a compiler error. The website and its downloads identify their documentation source revision; they are not a release archive and may describe features newer than your installed Tide. Keep a known-working compiler version and the downloaded guide together when pinning a project. Prefer that project's versioned references when supplied, and verify unfamiliar syntax with the compiler. Updating the guide or skill is an explicit download; existing project copies are not silently replaced. Do not solve a docs/compiler mismatch by upgrading the user's toolchain without their agreement. ## Reference downloads Every documentation page has a clean Markdown export at its page URL plus `.md`, for example `/game/commands.md`; the introduction is `/guide.md`. Exports include source examples as code, without needing the website's embedded game controls. - [Quick reference](#doc-guide--ai-context): the first attachment for a new conversation. Use the download button above for the Markdown file. - [Documentation index](https://tide-engine.dev/llms.txt): a small list of topics and Markdown links for agents with web access. - [Full documentation bundle](https://tide-engine.dev/llms-full.txt): an optional single file for offline search. - [Project instructions](https://tide-engine.dev/ai/AGENTS.md), [Claude import](https://tide-engine.dev/ai/CLAUDE.md), and [starter prompt](https://tide-engine.dev/ai/starter-prompt.txt): editable starting points for your game. Keep descriptions of your game's intent and decisions in the project. When the agent repeatedly misunderstands a Tide feature, retain the failing request and compiler diagnostic so the guide can be corrected against a real example. --- Source: https://tide-engine.dev/guide/ai-context.md Tide on one page: a complete game, the essential rules of the language and engine, and links to each topic's full reference. # Quick reference Tide on one page: a complete game, the rules most games rely on, and links to each topic's full reference. It covers the common path; follow the links when a task needs more. It's also the page to give an AI agent: [Using Tide with AI](#doc-guide--ai) explains how. ## Find the project and version A Tide game is a folder of `.tide` files, including its subfolders. Declarations are visible across files without imports. An ordinary new game needs no project generator, CMake project or C host: create a folder and a `game.tide`. Optional packages are listed in `tide.packages`; [authored scenes and prefabs](#doc-game--scenes) also use `.tprefab` files. Every `.tide` file under the folder is compiled, except in hidden folders, whose names start with a dot: `tide build` writes to `.build/`, and scratch or probe copies of the game belong in a hidden folder or outside the game folder. Inspect the existing game and its instructions before changing it. Run `tide version` to identify the installed compiler and `tide help build` or `tide help run` for its actual CLI. These docs describe the website's source revision, which can be newer than an installed release. Prefer documentation supplied with the project's pinned toolchain when available. On a mismatch, report the versions and use compiler diagnostics to check the relevant feature; do not silently upgrade the user's installation. ## A complete game Save the following as `game.tide` in an otherwise empty game folder. It is the same source used by [Your first game](#doc-guide--first-game): a bouncing ball and a WASD-controlled player for each joining player. The built-in host starts the match and joins a player even in single-player. ```tide component Body { [Position] float2 position; float2 velocity; float radius = 20; } component Ball { } input Controls { float2 move; Sample(Devices devices) { var keys = devices.keyboard; if (keys.d.pressed) move.x += 1; if (keys.a.pressed) move.x -= 1; if (keys.w.pressed) move.y += 1; if (keys.s.pressed) move.y -= 1; } } scene Main { } event(Spawned) Setup(with Main) { Spawn(Body { velocity = float2(160, 120) }, Ball); } event(PlayerJoined joined) AddPlayer() { Spawn(Body { radius = 16 }, Owner { player = joined.player }); } system Steer(Controls input, mut Body body, with Owner) { body.velocity = Math.Normalize(input.move) * 250; } system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } system Bounce(mut Body body, with Ball) { if (Math.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x; if (Math.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y; } view DrawBalls(Body body, with Ball) { Draw.Circle(body.position, body.radius, Color.red); } view DrawPlayers(Body body, Owner owner, Session session) { var color = owner.player == session.player ? Color.yellow : Color.gray; Draw.Circle(body.position, body.radius, color); } ``` Build with `tide build`. For a human's interactive session, `tide run --stats` watches files and reloads when they change. Automated checks (a script, CI or an AI agent) use a bounded hidden run instead, as shown below. ## The model - **Components** hold each entity's data. A component with no fields is a tag. **Singletons** hold one value per world; declare one with `singleton Score { int value; }` and request it as a parameter. - **Systems** run each fixed tick for every entity matching their component parameters. `mut Body body` writes data, `Body body` reads it, and `with Ball` or `without Ball` filters without reading data. Repeat the modifier for each filter: `with Ball, without Frozen`. A system with only singleton/input parameters runs once per tick. Use `this` for its current entity, not an invented entity parameter. - **Views** run each rendered frame, in declaration order, and later views draw on top. They read the presented match and draw; they can change local state, but cannot change match state. `Time` is a singleton: a system takes a `Time time` parameter and moves by `time.dt`, the fixed tick interval. Views animate local effects by `Frame.dt`, the frame interval. `Frame` and `Screen` are not parameters: views read `Frame.dt`, `Screen.width` and `Screen.height` directly. [Views](#doc-game--views) explains interpolation and drawing order. - **Events** notify code inside the game. `scene Main;` is the initial scene; `event(Spawned) Setup(with Main)` initializes it once. `event(PlayerJoined joined) ...` initializes a joining player's entities. [Events](#doc-game--events) explains handlers and their data parameters. - Every game is a networked **match**, including single-player. Keep gameplay state in match components and singletons. Menus, camera preferences and presentation-only effects belong in `local singleton`, `local` fields or local entities. [Local state](#doc-game--local-state) explains their lifetimes and access. Systems declare access so the compiler can schedule them. Component filters create no data dependency. Conflicting systems follow deterministic declaration order unless explicit ordering changes it; put a system that sets velocity before one that integrates it. See [Systems](#doc-game--systems) and [The schedule](#doc-game--schedule). ## Syntax that matters Values are read-only unless declared `mut`, including locals. `var value = ...;` infers a read-only type; use `mut var value = ...;` for an accumulator that changes. A `for (var i = 0; i < n; i++)` loop permits its step to change `i`; changing it inside the body requires `mut var`. Fields are writable through a mutable component or singleton binding. Pass singletons explicitly through helper parameters instead of looking them up by type. Construct components with `Body { radius = 12 }`, without `new`. Fields not specified use defaults or zero. `float2(x, y)` constructs a vector; arithmetic is component-wise, and `==`/`!=` compare two vectors whole, giving one bool (`if (cell == target)`), so no `Same(a, b)` helper is needed. `Math` supplies deterministic operations such as `Math.Normalize`, `Math.Length`, `Math.Clamp` and `Math.Sin`. Angles are radians; `90deg` is a radians literal. String interpolation is `$"Score: {score.value}"`. Fixed tables of plain values (no text) are constants: `const float[3] SPEEDS = [1, 2.5, 4];` or `const List QUAD = [0, 1, 2, 0, 2, 3];`, up to 4096 values written out, read as `SPEEDS[int(kind)]` anywhere, GPU code included; `Kind.Values()` is every member of an enum, for `foreach`, and two values of one enum order with `<`. Read [Basics](#doc-language--basics), [Functions](#doc-language--functions), [Math](#doc-language--math) and [Text and lists](#doc-language--text-and-lists) for signatures, collections and copy/borrow rules. `Spawn(Body { position = at }, Ball)` returns an `Entity` handle. `entity.Add(Component { ... })`, `entity.Remove(Component)` and `entity.Destroy()` record structural changes. Those changes apply at the end of the tick, not immediately: a spawned entity cannot be queried yet, and recording a destroy does not remove a row from a running query. Guard against counting the same pending removal twice. Entity changes in local code apply to local entities at the local frame boundary. See [Entities](#doc-game--entities). For a second set of entities, declare a query parameter: ```csharp system CountBalls(query (with Ball) balls, mut Score score) { mut var count = 0; foreach (var ball in balls) count += 1; score.value = count; } ``` This fragment assumes the `Ball` tag and `Score` singleton above. Query bindings are read-only match data; a row exposes its bound values and `.entity`. An ordinary explicit `World world` parameter supports handle lookups, for example `world.Get(entity)` (a copy) and `world.Has(entity)`. A `mut World world` parameter permits `world.Set(entity, replacement)`, and changing another entity's component in place with `world.Edit(entity, body) { body.velocity.y = 5; }`: in the block, `body` is that entity's component, put back when the block ends, even on `return` or `continue`; an entity without one skips the block. Prefer `Edit` to a `Get`, a change and a `Set`. Look up the [query and World rules](#doc-game--systems--another-set-of-entities) before building cross-entity changes; do not invent `world.Entities`, `GetComponent` or writable query bindings. ## Input and submitted actions Use a declared `input` for per-tick controls, as in the complete game. `Sample(Devices devices)` reads this machine's devices; gameplay systems receive the input of the entity's `Owner`. `Owner.player` is a `PlayerID`. The input sampler starts from field defaults each tick. Keys are named as in Unity's Input System: `a`, `space`, `r`, `leftArrow`, `upArrow`, `digit1`, `leftShift`. Input carries whether keys are **held**: a late player's input is guessed by repeating it, and a repeated "just pressed" would press twice. In `Sample`, record `.pressed`, not a key's `.down`. Match code gets one-shot edges from the input's own `bool` fields, which have `.down` and `.up`: ```csharp input Controls { bool restart; Sample(Devices devices) { restart = devices.keyboard.space.pressed; } } system Restart(Controls input, mut Score score, with Owner) { if (input.restart.down) score.value = 0; } ``` A view can read local devices, including `.down` edges, but its device reads cannot directly alter the match: a view turns a press into a command, below. See [Input](#doc-game--input). Use typed **commands** for submitted actions from local UI. A minimal entity-targeted action is: ```csharp component Ready { bool value; } command SetReady { bool value; } view ReadyButton(Ready ready, with ownership) { if (GUILayout.Button(ready.value ? "Unready" : "Ready")) this.Send(SetReady { value = !ready.value }); } command(SetReady action) ApplyReady(mut Ready ready, with ownership) { ready.value = action.value; } ``` Spawn `Ready` alongside each player's `Owner` to use this fragment. In a command handler, `with ownership` runs it only for an entity the command's sender owns (`without ownership`, only for others'); a handler without it names the sender, `command(SetReady action, PlayerID sender)`, and checks it, such as `if (sender != owner.player) return;`. The connection supplies the sender; never trust a sender ID in the payload. Validate ownership and game rules before writing state. Handlers return void, with ordinary guard clauses. They have no acceptance method or transaction. A global command uses `Send(...)`; an entity-targeted command uses `entity.Send(...)`. See [Commands](#doc-game--commands) and [GUI](#doc-game--gui). Initialize multiplayer entities in `PlayerJoined`, and clean up their entities/state in `PlayerLeft` when the game needs it. **Treat `PlayerID` as an opaque identity, not a display index:** retain `joined.player` or read an entity's `Owner.player`; do not assume the players are `PlayerID(1)` and `PlayerID(2)`. When the game needs ordered seats (left and right paddle, wallet slots), assign them in the `PlayerJoined` handler from a singleton, such as `mut Seats seats` holding each seat's `PlayerID`, and free them in `PlayerLeft`. Do not count the entities spawned for earlier players instead: spawns apply at the end of the tick, and two players can join in the same tick. `with ownership` selects this machine's entities in local code, and the command sender's in a command handler; match systems use `with Owner`. Write separate filters as `with Wallet, with ownership`. All machines in a match must execute identical simulation rules. Read [Matches](#doc-multiplayer--matches) before implementing room setup, admission or migration. Optional [Rooms](#doc-packages--rooms) supplies a Play/Host/Join menu; it is not automatically included in a new folder. ## Draw and validate The default 2D view uses world coordinates centered on the window, with Y up and one world unit per pixel. **`Draw.SetScreen()` changes subsequent drawing to logical pixels from the top left, with X right and Y down**, the same coordinates as GUI rectangles and script `mouse x y`. It also affects later views in that frame until another camera is selected; `Draw.Screen() { ... }` limits the change to a block. For a grid whose row 0 is at the top, screen Y increases with the row. `Draw.Circle(position, radius, color)` and `Draw.Rect(center, size, color)` use the shape's center; a GUI `Rect(x, y, width, height)` uses its top-left corner. `Draw.Text(text, position, size, color)` accepts an `Anchor` to align text. There is no window-size setting: players resize the window, which opens at 960×540 on desktop. For a game designed at a fixed size such as 640×360, draw the play area in world units and set the camera in the first view, so it scales with the window: `Draw.SetCamera(float2(0, 0), 180)` shows 360 units of height (its size is half the visible height), and `Math.Max(180, 320 * Screen.height / Screen.width)` instead also keeps all 640 units of width visible. The camera stays for later views in that frame. Device pointer positions use bottom-left, Y-up coordinates even when drawing in screen mode; use `Screen.Flip(devices.pointer.position)` before screen-space hit tests. Read [Views and drawing](#doc-game--views), [Cameras](#doc-game--cameras) and [GUI](#doc-game--gui) for signatures and layout. Do not assume the default world camera and GUI use the same axes. For 3D, read [Drawing in 3D](#doc-game--3d) before choosing meshes, depth or lighting. Compile early, then check behavior. These are game commands; building the engine repository is a different workflow. ```sh tide version tide build tide build --web ``` For automated native runs, set `TIDE_HIDDEN=1` in that shell before running the game. PowerShell: ```powershell $env:TIDE_HIDDEN = '1' tide run --frames 120 --capture smoke.png --stats ``` POSIX: ```sh TIDE_HIDDEN=1 tide run --frames 120 --capture smoke.png --stats ``` This finishes after 120 frames and captures the final picture. Add `--size 640 360` to test a particular logical window size; use `Screen.width` and `Screen.height` for responsive layout. For dynamic play in the same session, use `tide run --interactive play.txt`: send `capture menu.png`, inspect it, queue future-frame input lines, then send `step 30` and wait for `tide: interactive ready ` ([protocol](#doc-tools--cli--interactive-play)). To press a GUI widget, send `controls` to list the widgets with their labels and positions, then `click "Play"` or `click `, rather than estimating pixels from the picture. Open the PNG and inspect it; a successful build alone does not establish that the game draws or behaves correctly. If inspection is inconclusive, take a later capture or check simulation values with `Debug.Log`/`Debug.Assert` before concluding the game is blank or broken. For input, use `tide run --script smoke.txt --frames 180 --capture smoke.png --stats`, with a script such as: ```text 1 key d down 60 key d up 120 capture after-move.png 150 quit ``` Script times are frames, and lines go in frame order; key actions use `down`/`up`, or neither for a one-frame tap. A `capture` path in a script is relative to the script's folder. `--players 2` runs two game processes in one match over a simulated network on this machine, with `player 2` after a frame number to target the second player; each capture name gains the player's number, `after-move-1.png` and `after-move-2.png`. `300 player 2 leave`, `drop`, `sleep` and `rejoin` test what happens when a player goes and comes back. `--latency 80`, `--jitter 10` and `--loss 5` put every joining player that far from the match's server (`--latency 2:120` for one player), and the run still repeats exactly. It does not exercise real network transports. Read [CLI capture and scripts](#doc-tools--cli--without-a-window) for the supported actions, output naming and exit codes. A web build still needs a browser test; native captures do not verify WebGPU. Launch automated Chrome/Edge with `--mute-audio` and a bounded test, not an unbounded `tide run --web`. For numerical behavior, supplement pictures with `Debug.Log` of state changes or `Debug.Assert` of invariants. A multiplayer money transfer can assert that balances never go negative and that the pool plus all balances stays constant; a collector can log cell and score after each move. With several players, a client runs a tick again after a wrong guess about another player's input, and logs in it print again: include `time.tick` in the line. Check the actual log as well as the captures. A failed or unclear image inspection is not evidence of a replication bug. For performance work, capture a representative scripted run in an optimized build: ```sh tide run --release --script play.txt --frames 360 --profile profile.json --profile-warmup 60 ``` For GPU bottlenecks, inspect `gpu_passes.rows`: target, pass order, shader membership and mean/p95/max GPU time. Check missing-sample counters; a mixed pass's time cannot be assigned to one shader. See the [GPU pass reference](#doc-tools--debug-views--finding-expensive-gpu-passes). This native desktop report is written when the run ends, independently of the panels; it measures frames after warmup and includes source locations and engine draw counters. Read actual CPU work and GPU availability, not the hidden run's fixed-step FPS. Follow expensive views into their draw diagnostics: many frustum tests with few rejections are a candidate for investigation, not proof that culling is redundant. Compare one change at a time using the same script, seed, resolution, saves and build mode, and inspect captures and relevant simulation checks before claiming an improvement. CPU, concurrent worker and asynchronous GPU intervals overlap. See [Profile captures](#doc-tools--debug-views--profile-captures) for the report's measurement meanings and limits. Fix diagnostics using the current compiler and relevant reference rather than guessing APIs. Report the builds, behavior checks and platforms actually tested. If a tool or backend is unavailable, say which check remains unverified. ## References on demand The [documentation index](https://tide-engine.dev/llms.txt) links to clean Markdown pages. The optional [full documentation download](https://tide-engine.dev/llms-full.txt) is for offline searching, not required reading on every task. The [language spec](https://tide-engine.dev/spec.md) separates decided behavior from provisional implementation and open proposals; an open design is not an available API. Use [Assets](#doc-game--assets) for imports, [Packages](#doc-packages) for optional dependencies and their pinned documentation, [Determinism](#doc-multiplayer--determinism) for simulation constraints, and [Visibility](#doc-game--visibility) for secrets and recipient state. Keep gameplay state deterministic and use Tide's math/random APIs; C reached through `extern` is trusted and can violate those guarantees. --- Source: https://tide-engine.dev/guide/playground.md Edit a running Tide game in your browser. Compile real Tide code locally and hot reload while keeping the game's state. # Playground Change the code and watch the running game pick it up. Compilation happens in your browser; there is nothing to install and your source is not sent to a build server. ```tide // Change the color or speed below. The ball keeps its position on reload. const float SPEED = 1; const float RADIUS = 18; const Color INK = Color(0.98, 0.75, 0.14); component Ball { [Position] float2 position; float2 velocity = float2(130, 95); int bounces; } scene Main { } event(Spawned) Setup(with Main) { Spawn(Ball); } system Move(mut Ball ball, Time time) { ball.position += ball.velocity * time.dt * SPEED; if (Math.Abs(ball.position.x) > 145) { ball.position.x = Math.Sign(ball.position.x) * 145; ball.velocity.x = -ball.velocity.x; ball.bounces += 1; } if (Math.Abs(ball.position.y) > 105) { ball.position.y = Math.Sign(ball.position.y) * 105; ball.velocity.y = -ball.velocity.y; ball.bounces += 1; } } view Backdrop() { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), Math.Max(185, 185 * Screen.height / Screen.width)); Draw.Rect(float2(0), float2(330, 250), Color(0.15, 0.15, 0.17)); } view Show(Ball ball) { Draw.Circle(ball.position, RADIUS, INK); Draw.Text($"{ball.bounces} bounces", float2(-145, -155), 15, Color(0.64, 0.64, 0.68)); } ``` ## Try a live change - Change `INK` to `Color(0.18, 0.83, 0.75)` to turn the ball teal. - Change `SPEED` to `2` to make it move faster, or `0` to hold it still. - Change `RADIUS` to `30` to make it bigger. The bounce count and position carry over. **Restart** starts the last successful build from the beginning. **Reset code** restores the original example and starts it again. **Auto reload** compiles after you stop typing. With it off, press **Compile & reload** or Ctrl+Enter (Cmd+Enter on macOS). If the code has an error, diagnostics appear below the editor and the last successful game keeps running. Try removing a semicolon, then putting it back. ## The editor The editor runs the same language server as the [editor extensions](#doc-tools--editors), so it already knows your code before you compile it: - Type `.` after a value, or press Ctrl+Space, for completions. Hover a name to see its type and documentation. Parameter hints appear as you type a call. - Mistakes are underlined as you type and listed under the editor; click one to jump to it. - F12 goes to a definition in this file, F2 renames, and Shift+Alt+F formats the code. Ctrl+/ comments lines, and Ctrl+F finds text. Drag the divider between the code and the game to give either more room, or press **Expand** to fill the window. Esc or **Exit** brings back the page. ## What runs here This is the real Tide compiler and engine: Tide is transpiled to C, compiled to WebAssembly and loaded into the running preview. The first compilation downloads about 25 MiB of compiler tools, which your browser can cache. Later edits reuse them. The first build also initializes the tools and can take longer than later edits; progress appears below the editor. The compiler runs in a worker so you can keep editing while it builds. The editor's language server is a separate download of under 2 MiB, so suggestions work before the first build. This demo edits one `.tide` file with no external assets or packages. The engine's normal component, system and view features work here, including procedural drawing and shaders. Files named by an `asset` declaration must exist in the compiler's virtual filesystem; this page has no file upload or package manager. Native-only integrations are unavailable. [Build code](#doc-game--build-code) requires the installed tools; use `tide run --web` to build and preview a project that makes assets or constants during its build. [Hot reload](#doc-tools--cli--hot-reload) carries fields over by name. New fields use their defaults; changing a default does not overwrite an existing field. Renaming or removing state can reset it. Web reload currently closes connections to other players, so this playground demonstrates a solo match. For a complete project, [install Tide](#doc-guide--install) and follow [Your first game](#doc-guide--first-game). Use `tide run --web --stats` for the same browser preview with local project files and watched rebuilds. --- Source: https://tide-engine.dev/guide/samples.md Play Tide Engine sample games in your browser, from falling sand and arena combat to 2D and 3D physics, and invite friends to a room. # Samples Choose a game to play in your browser. Each thumbnail opens the full game in a new tab. Use **Source** to browse its code on GitHub. Explore a shared planet in the [Earth demo](#doc-guide--earth), with walking, driving and biome-specific scenery. It starts only when you choose **Play Earth**. To play together, open a room with the game's **Host** or **Invite** button and send its code to a friend. They open the same game and choose **Join**. - [Falling sand (opens in a new tab)](https://tide-engine.dev/sand/?stats): 2D · Simulation. Paint sand, water and walls together, and watch them flow. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/bench/sand). - [Duel (opens in a new tab)](https://tide-engine.dev/duel/?stats): 2D · Arena. Jump, shoot and block, then pick upgrades between rounds. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/duel). - [Towers (opens in a new tab)](https://tide-engine.dev/towers/?stats): 2D · Physics. Race to stack falling bricks into the tallest tower. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/towers). - [Sumo arena (opens in a new tab)](https://tide-engine.dev/sumo/?stats): 3D · Physics. Ram heavy balls through crates and off a collapsing arena. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/sumo). - [Tag (opens in a new tab)](https://tide-engine.dev/samples/tag/?stats): 3D · Party. Playground tag for up to eight: whoever's it the least by the bell wins. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tag). - [Pong (opens in a new tab)](https://tide-engine.dev/samples/pong/?stats): 2D · Arcade. Keep the ball in play and send it past your opponent's paddle. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/pong). - [Snake (opens in a new tab)](https://tide-engine.dev/samples/snake/?stats): 2D · Survival. Share one board and outlast the other snakes. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/snake). - [Tanks (opens in a new tab)](https://tide-engine.dev/samples/tanks/?stats): 2D · Arena. Drive, aim and fire bouncing bullets around a walled arena. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tanks). - [Bomberman (opens in a new tab)](https://tide-engine.dev/samples/bomberman/?stats): 2D · Arcade. Lay bombs, break crates and collect power-ups. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/bomberman). - [Connect four (opens in a new tab)](https://tide-engine.dev/samples/connect-four/?stats): 2D · Board game. Take turns dropping pieces and line up four of your color. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/connect-four). - [Asteroids (opens in a new tab)](https://tide-engine.dev/samples/asteroids/?stats): 2D · Co-op. Break asteroids, share a score and rescue stranded ships. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/asteroids). - [Sumo ring (opens in a new tab)](https://tide-engine.dev/samples/sumo/?stats): 2D · Arena. Bump and dash to push the other players out of the ring. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/sumo). - [Tower defense (opens in a new tab)](https://tide-engine.dev/samples/tower-defense/?stats): 2D · Co-op. Build and upgrade towers together, with shared gold and lives. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/tower-defense). - [Marbles (opens in a new tab)](https://tide-engine.dev/samples/marbles/?stats): 3D · Arcade. Roll around the platform, collect coins and stay away from the edge. [Source](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/samples/marbles). --- Source: https://tide-engine.dev/guide/earth.md Explore a shared little planet in Tide Engine: walk, drive, visit towns and inspect the live performance stats. # Earth demo Walk or drive around a little planet with everyone else playing. Visit its towns, roads, gentle hills and different biomes. The demo loads only when you choose **Play Earth**. [Play Earth](https://tide-engine.dev/earth/?stats) ## Controls Click or tap the planet to land. Drag to turn the globe or camera. On the ground, use **WASD** to move, **C** to switch between walking and driving, **Space** to jump and **E** to wave. Tap the ground to go there; touch buttons provide the other actions. Use **Esc** or **Globe** to return to space. Tap the **FPS line** at bottom right, or press **F8**, to open the engine's performance stats. **Expand** gives the game the whole page without restarting it. **Stop** leaves the match and releases the demo's resources. The demo joins the shared hosted world when available; otherwise it starts a local world. Its [source is on GitHub](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/earth). --- Source: https://tide-engine.dev/benchmarks.md Measured ECS performance for Tide and other ECS implementations, with workload details, methodology, variation and the limits of each comparison. # Benchmarks How much work can Tide's ECS do in a tick? These small CPU workloads give a baseline for comparing ECS performance. This measures **ECS updates**, including deferred structural changes where used. It excludes setup, world hashing, snapshots, networking and rendering. It does not measure the cost of a complete Tide multiplayer tick or predict a game's frame rate. **Tide, Bevy, Flecs and EnTT: one thread** 2026-10-29 · AMD Ryzen 9 7900X · Windows 11 x86-64. 4 processes per implementation and workload; 200 warmup ticks and 400 measured ticks per process. Tide revision: [fe5e96be1c61c7372590e7466dc26810a910bb14](https://github.com/Tide-Engine/tide-engine/commit/fe5e96be1c61c7372590e7466dc26810a910bb14). - Tide fe5e96be1: Generated C storage and scheduled systems; moving Frozen tags. Clang 23.1.2, -O2, baseline x86-64. - Bevy 0.20.0: Table storage and scheduled systems; Rust 1.95.0, opt-level 2, baseline x86-64. - Flecs 4.1.6: Cached archetype systems and pipeline; Clang 23.1.2, -O2, baseline x86-64. - EnTT 4.0.0: Views and an owning filtered group with explicit dispatch, without an integrated scheduler; Clang 23.1.2, -O2, baseline x86-64. | Workload | Threads | Tide, ms (min–max) | Bevy, ms (min–max) | Flecs, ms (min–max) | EnTT, ms (min–max) | | --- | --- | --- | --- | --- | --- | | 1M particles | 1 | 0.44648 (0.43545–0.57870) | 1.15563 (1.14835–1.26580) | 1.66710 (1.66455–1.73415) | 1.88397 (1.84365–1.91285) | | 1M wide components, all active | 1 | 1.29137 (1.22825–1.34430) | 2.40837 (2.38005–2.60395) | 2.25955 (2.24280–2.28730) | 2.85360 (2.82575–2.88020) | | 1M wide components, 50% frozen | 1 | 0.44522 (0.42905–0.46295) | 1.14358 (1.10590–1.20100) | 1.10347 (1.09495–1.12315) | 1.46560 (1.43635–1.46895) | | 1M wide components, 95% frozen | 1 | 0.02925 (0.02890–0.02930) | 0.10120 (0.10000–0.10690) | 0.10963 (0.10910–0.11205) | 0.13195 (0.13005–0.13720) | | 1M wide components, 99% frozen | 1 | 0.00575 (0.00570–0.00580) | 0.02022 (0.02010–0.02060) | 0.02187 (0.02165–0.02250) | 0.02903 (0.02670–0.02970) | | 2k bullets, churn | 1 | 0.34695 (0.33555–0.38910) | 0.52038 (0.46550–0.68610) | 0.56875 (0.45420–0.73950) | 0.26267 (0.25980–0.27045) | Tide has the lowest sampled median for particles, dense wide components and the three frozen densities. EnTT has the lowest churn median. Bevy and Flecs churn ranges are wide; these observations describe this run, not a universal ranking. The 96 accepted processes use four cyclic rounds: each implementation occupies every launch position once per workload. One complete attempt that overlapped a build was excluded; its raw evidence and the accepted replacement are both retained. Attempts were not selected by their timing. Before timing, 75 validation cases matched across the four native implementations, an independent C reference and Tide WASI; the harness passed 26 checks. The raw report records source and binary hashes, correctness evidence and the attempt ledger. Bevy, Flecs and EnTT WebAssembly were not measured or validated in this report. **Tide and Bevy: one and four threads** 2026-10-29 · AMD Ryzen 9 7900X · Windows x86-64. 3 processes per implementation and workload; 200 warmup ticks and 400 measured ticks per process. Tide revision: [fe5e96be1c61c7372590e7466dc26810a910bb14](https://github.com/Tide-Engine/tide-engine/commit/fe5e96be1c61c7372590e7466dc26810a910bb14). - Tide fe5e96be1: Generated C storage and scheduled systems; Clang 23.1.2, -O2, baseline x86-64. - Bevy 0.20.0: Table storage and scheduled systems; Rust 1.95.0, opt-level 2, baseline x86-64. | Workload | Threads | Tide, ms (min–max) | Bevy, ms (min–max) | | --- | --- | --- | --- | | 1M particles | 1 | 0.45830 (0.44730–0.48030) | 1.15210 (1.15060–1.17375) | | 1M particles | 4 | 0.12650 (0.12480–0.12740) | 0.43015 (0.42965–0.43565) | | 1M wide components, all active | 1 | 1.33280 (1.32535–1.40350) | 2.49640 (2.38615–2.59715) | | 1M wide components, all active | 4 | 0.67165 (0.67150–0.82120) | 1.17735 (1.14365–1.19100) | | 1M wide components, 50% frozen | 1 | 0.43605 (0.41605–0.48060) | 1.13585 (1.08350–1.14465) | | 1M wide components, 50% frozen | 4 | 0.41065 (0.40415–0.41980) | 0.41150 (0.41115–0.41365) | | 1M wide components, 95% frozen | 1 | 0.02940 (0.02920–0.02940) | 0.10050 (0.10025–0.10110) | | 1M wide components, 99% frozen | 1 | 0.00570 (0.00570–0.00580) | 0.01995 (0.01990–0.02000) | | 1M wide components, 99% frozen | 4 | 0.00570 (0.00570–0.00580) | 0.02210 (0.02130–0.02330) | | 2k bullets, churn | 1 | 0.33850 (0.33725–0.34030) | 0.32020 (0.29680–0.35150) | | 2k bullets, churn | 4 | 0.35025 (0.33120–0.36550) | 0.30455 (0.26305–0.51825) | The four-thread 50%-frozen workload is effectively tied. Churn measurements overlap and vary substantially, especially with four threads; these runs do not establish a reliable winner for churn. Three alternating Tide/Bevy process pairs were run independently for each workload. Two earlier full batches affected by contention were excluded; the raw archive records both the accepted and discarded runs. ## Reading the results Lower is faster. Each cell is the median of separate process medians, in milliseconds per tick. The smaller numbers underneath give the minimum and maximum of those process medians. These ranges show run-to-run variation; they are **not confidence intervals**. Close or overlapping results need more measurements before calling a winner. Every workload stays visible, including cases where another implementation is faster. There is no overall score: moving particles, filtering wide components and changing entity structure exercise different costs. Reports from different runs remain separate. ## What the workloads do | Workload | Work measured | | --- | --- | | 1M particles | Update position and velocity for one million particles. | | 1M wide components | Update one million entities with wider component data. | | 50%, 95% or 99% frozen | Update only the remaining active entities. Frozen membership is fixed during the run; this does not measure changing filter membership. | | 2k bullets, churn | Repeated spawning and destruction alongside movement. Deferred changes are applied inside the timed tick. | The implementations use the same initial values and update arithmetic. The runner checks final state digests across implementations before accepting a result. That checks these workloads; it does not establish cross-platform determinism for the other ECS libraries. ## What is being compared Tide generates specialized C storage and systems for each game. Bevy uses its Table component storage and schedule. The broader serial comparison also uses Flecs cached archetype systems and EnTT views and an owning filtered group with explicit dispatch. EnTT does not supply an integrated scheduler in this comparison, so these paths do not provide identical engine services. Each report names its exact implementations, versions and thread count. Compiler settings preserve the update's floating-point operation order: no fast math or fused multiply-add contraction. Tide keeps its determinism requirements; the harness does not disable them to improve a result. These are selected synthetic workloads on one machine, maintained by the Tide project. Cache layout, entity count, query shape, structural changes, scheduling and hardware can change the outcome. Use them as a starting point for a workload that resembles your game. --- Source: https://tide-engine.dev/game/entities.md Define components, entities and singletons in Tide's ECS, then spawn, add, remove and destroy data to build your game's world. # Components and entities Tide is an ECS: the world is made of **entities**, entities are made of **components**, and **systems** run code over them. This page is about the data; [Systems](#doc-game--systems) is about the code. ## Components A component is plain data, declared with `component`: ```csharp component Health { int value = 100; int max = 2 * 2 * 25; } component Poisoned { } ``` A component with no fields, like `Poisoned`, is still useful: systems can pick the entities that have it, or don't. ### Defaults Fields can have a default. It must be a constant: literals, constructors of built-in types, struct values of constants, `Math` functions, built-in constants like `quaternion.identity`, and operators on those. It can name an [asset](#doc-game--assets--a-field-s-default) too, like `Texture face = logo;`. A default can't read other fields, singletons or `Time`. ```csharp component Turret { float angle = Math.Radians(45); float3 offset = float3(0, 1.5, 0); Color tint = Color.red; } ``` Fields without a written default take their type's default: zero for numbers, `false` for bools, empty text and collections, and a struct's own field defaults for a struct. `Entity` fields always start as the null entity, and can't have another default. [Default values](#doc-language--basics--default-values) explains the `default` expression. ## Singletons A singleton holds state there's one of per world, like the rules, the score or a random seed. Other ECSs call them resources. ```csharp singleton Physics { float3 gravity = float3(0, -9.81, 0); int collisionCount; } ``` Singletons start with their defaults when the world is created. Systems take them as parameters, like components (see [Systems](#doc-game--systems)). `Time` is a built-in singleton. Systems can read it, but not write it: | Field | What it is | |---|---| | `float dt` | The length of a tick in seconds | | `int tick` | The tick, which counts from 0 | | `float t` | The seconds since the match started: `tick * dt` | | `int tickRate` | The ticks in a second: 1 / `dt` to the nearest whole number | | `float maxRewind` | Configured collider history in seconds, from `settings`; 0 disables it | `t` is worked out from the tick each time, so it never drifts, and [views](#doc-game--views--smooth-at-any-tick-rate) see it move every frame. A float holds about 7 digits, so it gets coarser as the match goes on (after a day, its steps are about 8 milliseconds): a timer that has to be exact counts in `tick`. What makes one match unlike another is its seed, [`Random.seed`](#doc-language--math--the-match-s-seed), which the match's [random numbers](#doc-language--math--random-numbers) come from. ## Spawning entities `Spawn` makes an entity from a list of component values: ```csharp var e = Spawn(Transform { localScale = float3(1, 1, 1) }, Player); ``` A component value is written like `Health { max = 200 }`, without `new`. Fields left out take their defaults, and a bare type name, like `Player`, takes every default. An existing value or a helper's result works too: `Spawn(savedHealth, MakeInventory())` and `e.Add(savedHealth)`. Each argument is evaluated once in written order and copied when the change is recorded, including owned lists and maps. Editing the source afterward leaves that recorded copy intact. A component copy carries ordinary fields; each new entity gets fresh local-field defaults. An entity has at most one component of each type. When it needs several of something, use a list inside one component, one entity per item that points back at its owner, or separate component types. ## Changing entities ```csharp e.Add(Stunned { duration = 2 }); e.Remove(Stunned); e.Destroy(); ``` - `Add` of a component the entity already has replaces its value. - `Remove` of a component the entity doesn't have does nothing. - `Add`, `Remove` and `Destroy` on an entity that's already gone do nothing. These are **structural changes**, and they don't happen right away. They're recorded, and applied together at the end of the tick, in the order they were made. The handle `Spawn` returns can be used at once, for example to store in a component, but the entity's data can only be read once the changes apply. `Spawn` returns its final opaque logical identity immediately. It stays the same across rollback and recipient projection loading for the same causal spawn, independently of physical slots, row order or hidden allocations. Helpers, query rows, events and waiting tasks retain that causal origin. Authority correcting the initializer values alone does not reset the entity's local fields. The components still become readable only when the recorded spawn applies. Code that depends on hidden state can still need authority corrections: stable identities do not simulate missing private entities. C uses the same identity; see [Calling C](#doc-c--functions). That's what lets systems run side by side: nothing they do changes which entities exist until they're all done. A [function](#doc-language--functions--sending-and-spawning) can `Spawn`, `Add`, `Remove` and `Destroy` too, for the code that calls it. It takes the entity it changes as a parameter: ```csharp Entity Drop(float3 at) { return Spawn(Transform { localPosition = at }, Crate); } void Stun(Entity target) { target.Add(Stunned { duration = 2 }); } ``` Each ball below is an entity with a `Ball` and a `Health`. Tap one to `Add` a `Poisoned` to it: a system that takes `with Poisoned` then drains its health, and destroys it when none is left. Tap it again to `Remove` the component, and it recovers. Tapping the ground spawns a ball. A view can't change the match itself, so each tap goes in as a [command](#doc-game--commands). **Spawn, Add, Remove and Destroy** ([Run example](https://tide-engine.dev/examples/entities/?stats)) ```tide settings { title = "Entities"; tickRate = 30; maxPlayers = 1; } component Ball { float2 position; float radius = 0.3; } component Health { int value = 100; } component Poisoned { } // No fields: it only marks an entity scene Main { } event(Spawned) Setup(with Main) { Spawn(Ball { position = float2(-1.2, 0.4) }, Health); Spawn(Ball { position = float2(0, -0.3) }, Health, Poisoned); Spawn(Ball { position = float2(1.2, 0.5) }, Health); } // What a tap asks of the match. Views can't change it themselves. command Drop { float2 at; } command Poison { } command Cure { } command(Drop drop, PlayerID sender) DropBall() { Spawn(Ball { position = drop.at }, Health { value = 40 }); } // `this` is the entity the command was sent to. Add and Remove wait for the // end of the tick, and so does Destroy. command(Poison poison, PlayerID sender) PoisonBall(with Ball) { this.Add(Poisoned); } command(Cure cure, PlayerID sender) CureBall(with Ball) { this.Remove(Poisoned); } system Sicken(mut Health health, with Poisoned) { health.value -= 1; if (health.value <= 0) this.Destroy(); } system Recover(mut Health health, without Poisoned) { health.value = Math.Min(health.value + 1, 100); } // This machine's side: what the pointer is on, and the counts to show. local singleton Pointing { float2 world; bool down; bool onBall; int balls; int poisoned; } view Begin(Devices devices, mut Pointing pointing) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), 2.2); pointing.world = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position)); pointing.down = devices.pointer.press.down; pointing.onBall = false; pointing.balls = 0; pointing.poisoned = 0; } view Healthy(Ball ball, Health health, mut Pointing pointing, without Poisoned) { var size = ball.radius * (0.4 + health.value * 0.006); Draw.Circle(ball.position, size, Color(0.98, 0.75, 0.14)); pointing.balls += 1; if (Math.Distance(pointing.world, ball.position) > ball.radius) return; pointing.onBall = true; if (pointing.down) this.Send(Poison { }); } view Sick(Ball ball, Health health, mut Pointing pointing, with Poisoned) { var size = ball.radius * (0.4 + health.value * 0.006); Draw.Circle(ball.position, size, Color(0.18, 0.83, 0.75)); Draw.WireCircle(ball.position, ball.radius, 0.03, Color(0.18, 0.83, 0.75)); pointing.balls += 1; pointing.poisoned += 1; if (Math.Distance(pointing.world, ball.position) > ball.radius) return; pointing.onBall = true; if (pointing.down) this.Send(Cure { }); } view Ground(Pointing pointing) { if (pointing.down && !pointing.onBall) Send(Drop { at = pointing.world }); Draw.SetScreen(); Draw.Text($"{pointing.balls} entities, {pointing.poisoned} with Poisoned", float2(16, 14), 18, Color.white); Draw.Text("Tap a ball to poison or cure it. Tap the ground to spawn one.", float2(16, Screen.height - 30), 13, Color(0.64, 0.64, 0.68)); } ``` ## Transform and parenting `Transform` is built in, with `float3 localPosition` (zero), `quaternion localRotation` (identity), and `float3 localScale` (one). Each is relative to the entity's parent; a root's values are its world placement. Add it like any other component. Match `Transform` fields have [correction smoothing](#doc-game--views--provisional-correction-smoothing) built in: `localPosition` behaves as `[Position]`, and `localRotation` as `[Rotation]`. Views preserve their displayed values across prediction corrections and let the error decay. Scale keeps ordinary tick interpolation; local entities use their current values. Use `entity.Snap()` for an intentional jump. This smooths view bindings; `World` queries and the ancestors read by `position` still use stored state. Its computed `float3 position` property reads world position. Setting it converts the requested position into parent space and changes `localPosition`; it needs a mutable Transform and leaves the parent unchanged: ```csharp system Move(mut Transform transform) { transform.position += float3(1, 0, 0); } view Mark(Transform transform) { var screen = Draw.WorldToScreen(transform.position); Draw.Screen() { Draw.Circle(screen.xy, 10, Color.red); } } ``` The getter uses the binding's current `localPosition` and stored ancestors, including after changing that local value in the same routine. Helpers retain the attached binding when it is passed directly. An explicit copy is detached, so use `localPosition` on copies. Singular parent transforms and nonfinite setter results leave the local position unchanged. Properties are also [user-definable](#doc-language--functions--properties). `world.ParentToWorld(entity)` gives the matrix from parent space into world space. It includes retained placement when visibility hides a parent, and gives identity for an ordinary root or dead entity. Thus `Math.Transform(world.ParentToWorld(entity), localPosition)` is the same computation available to a component's own property. `world.LocalToWorld(entity)` includes the entity's own stored transform as well; its `c3.xyz` is the stored world position. ```csharp event(Spawned) Assemble(with Main) { var parent = Spawn(Transform { localPosition = float3(10, 0, 0) }); var child = Spawn(Transform { localPosition = float3(2, 0, 0) }); child.SetParent(parent, worldPositionStays: false); } ``` After those changes apply, the child's world position is `(12, 0, 0)`. `SetParent(parent)` preserves its world placement by adjusting its local values; `false` keeps its local values. `SetParent(null)` detaches it. These changes apply at the end of the tick or local frame, in recorded order. Read `world.LocalToWorld(entity)` for its composed `float4x4`, and `world.Parent(entity)` for its parent's handle. They read the latest stored state, as other `World` methods do. An entity without a Transform contributes identity; a missing entity gives identity or a null parent. With [state visibility](#doc-game--visibility--spatial-parents), a hidden spatial parent does not hide its public child. The projected hierarchy cuts private links and preserves placement only for subtrees containing permitted `Transform` state; a parent can therefore read as null on a client. Destroying a parent destroys its descendants, children before their parent. A cycle, a dead handle or a parent from the other world is rejected. Runtime rejections print their reason and leave the hierarchy unchanged. Preserving world placement requires a Transform on the child and an invertible parent transform. Nonuniform scales combined with rotation can create shear; three local TRS values cannot preserve that matrix exactly. The same `Transform` works on local entities: use `local Spawn(Transform)` and `local Transform transform` in a view's parameters. `Entity` and `LocalEntity` still prevent crossing the match/local boundary. Loaded scene entities remain independent roots. Reparenting ordinary entities into a different scene transfers their descendants into that scene; detaching retains scene ownership. ## Entity handles `Entity` is a handle to an entity. Components can hold them, to point at each other: ```csharp component Weapon { Entity owner; } ``` `default` is the null entity, so `weapon.owner == default` tells whether it points anywhere, and `weapon.owner = default;` clears it. A handle leads to the other entity's components through the `World`: `world.Get(weapon.owner)` (see [Other entities](#doc-game--systems--other-entities-the-world)). In a system, view or event handler that runs for an entity, `this` is that entity: ```csharp system Expire(mut Lifetime life) { life.ticks -= 1; if (life.ticks <= 0) this.Destroy(); } ``` In local code that runs for a local entity, like a view of local components, `this` is a `LocalEntity`. Code that runs once per tick, frame or event runs for no entity, so it has no `this`, and neither do functions. In a [frag](#doc-game--shaders--where-the-pixel-is), `this` is the pixel it runs for. A component's methods have `this` too: the entity whose component they're called on. Methods are specialized for the placement used by the caller, so `this` is an `Entity` for a match component and a `LocalEntity` for a local component. Explicit parameter and return types keep their meaning. ```csharp component Health { int value; bool IsMine(Entity attacker) { return attacker == this; } } ``` So a method that uses `this` can only be called on a component the code runs for, like a system's `Health health`. A copy of one, in a local variable or a function's parameter, belongs to no entity. ## Archetypes An archetype is a set of components that entities share, and entities with the same set are stored together. There are no archetype declarations: the compiler finds every one from the code, from what each `Spawn` makes and what `Add` and `Remove` can turn it into. It follows the code as written: `this.Add(Stunned)` in a system only reaches the entities that system runs for, and `e.Add(Stunned)` on an `e` a `Spawn` in the same code made reaches that one, so toggling a component on a few kinds of entity makes a few archetypes. An `Add` on an entity read from a field or a parameter could be on any entity, so it reaches every archetype. ## Limits Adding or removing a component moves the entity to the archetype of its new set, tags (components with no fields) included, at the end of the tick. That's what makes `without Sleeping` cheap: the system runs through the archetypes of awake entities and never looks at a sleeping one. Each move copies the entity's row, so a status that flickers, gained and lost every few ticks by many entities, is better kept in the row. Mark it `[Sparse]`: it's kept as a presence bit and its value in every archetype it can reach, so `Add` and `Remove` of it move no entity, and systems that take or filter on it skip the rows that haven't got it. ```csharp [Sparse] component Stunned { float left; } system Recover(Time time, mut Stunned stunned) { stunned.left -= time.dt; if (stunned.left <= 0) this.Remove(Stunned); } ``` Every component an entity can gain or lose doubles the archetypes it can reach. When tags would take a game past the limit below, the compiler keeps some of them in the row as if they were `[Sparse]`, starting with the tags added to entities read from fields or parameters, until the archetypes fit. A component with fields isn't chosen that way: past the limit it's an error, which marking the ones entities gain and lose most `[Sparse]` fixes. For now, a game has at most 256 components and 1024 archetypes. Entities, the rows of each archetype, and the structural changes and events in a tick grow as they need, with no limit but memory (see [C hosts](#doc-c--hosts--memory)). --- Source: https://tide-engine.dev/game/systems.md Write Tide ECS systems that query entities each tick, declare data access and control execution order in a deterministic simulation. # Systems A system is code that runs every tick. Its parameters say which entities it runs for, and what it does with their data. ```csharp system ClampPlayer(mut Transform trs, with Player) { if (trs.position.y < 0) trs.position.y = 0; } ``` ## Parameters are the query A system's component parameters describe the entities it runs for. Each parameter's modifier says how the system relates to that component or singleton: | Modifier | Meaning | |---|---| | none | Reads it | | `mut` | Writes it | | `with` | The entity must have it. No data, so no data dependency. | | `without` | The entity must not have it. | So `ClampPlayer` runs for every entity that has a `Transform` and a `Player`, and changes its `Transform`. Keeping what a system touches (its access) apart from which entities it picks (its filters) is what lets the engine run systems side by side safely: two systems that only filter on the same component never wait for each other. Only the amber row has `Moving` without `Frozen`, so only those entities match `Move`. Their positions change by `time.dt` in the match, and views draw the result. The button sends a command to pause or resume the match's movement. **Component filters in motion** ([Run example](https://tide-engine.dev/examples/systems/?stats)) ```tide settings { title = "System queries"; tickRate = 30; maxPlayers = 1; } component Body { float2 position; float speed = 1; } component Moving { } component Frozen { } singleton Demo { bool running = true; } command SetRunning { bool value; } scene Main { } event(Spawned) Setup(with Main) { for (var i = 0; i < 3; i++) { Spawn(Body { position = float2(i * 1.2 - 1.2, 1) }, Moving); Spawn(Body { position = float2(i * 1.2 - 1.2, 0) }, Moving, Frozen); Spawn(Body { position = float2(i * 1.2 - 1.2, -1) }); } } // Only the first row matches both filters. system Move(mut Body body, Time time, Demo demo, with Moving, without Frozen) { if (!demo.running) return; body.position.x += body.speed * time.dt; if (body.position.x > 2) { body.position.x -= 4; this.Snap(); // Wrap immediately instead of interpolating across the lane. } } // The button sends a match command instead of changing state in a view. command(SetRunning change, PlayerID sender) Run(mut Demo demo) { demo.running = change.value; } view Background() { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), 3); for (var i = -1; i <= 1; i++) Draw.Line(float2(-2.1, i), float2(2.1, i), 0.025, Color(0.24, 0.25, 0.27)); } view Active(Body body, with Moving, without Frozen) { Draw.Circle(body.position, 0.19, Color(0.98, 0.75, 0.14)); } view Blocked(Body body, with Moving, with Frozen) { Draw.Circle(body.position, 0.19, Color(0.98, 0.44, 0.52)); } view Excluded(Body body, without Moving) { Draw.Circle(body.position, 0.19, Color(0.64, 0.64, 0.68)); } view Labels(Demo demo) { var first = Draw.WorldToScreen(float2(0, 1)); var second = Draw.WorldToScreen(float2(0, 0)); var third = Draw.WorldToScreen(float2(0, -1)); Draw.SetScreen(); Draw.Text("Systems run every tick", float2(16, 14), 18, Color.white); Draw.Text("with Moving, without Frozen", float2(16, first.y - 34), 14, Color(0.98, 0.75, 0.14)); Draw.Text("Moving + Frozen: excluded", float2(16, second.y - 34), 14, Color(0.98, 0.44, 0.52)); Draw.Text("No Moving: excluded", float2(16, third.y - 34), 14, Color(0.64, 0.64, 0.68)); GUI.SetTheme(GUITheme { radius = 6 }); if (GUI.Button(Rect(16, Screen.height - 48, Screen.width - 32, 32), demo.running ? "Pause the match" : "Resume the match")) Send(SetRunning { value = !demo.running }); } ``` Other parameters: - **Singletons**, read or `mut`, like components: `system Score(mut Stats stats, Rules rules)`. - **The input**, or **`Devices`**: what the player who owns the entity does (see [Input](#doc-game--input)). - **The `World`**: any other entity's components (below). - **A `query`**: another set of entities to inspect (below). Match data stays read-only; [local code](#doc-game--views-and-the-match--other-entities) can also read and write attached local fields. Views take the same parameters, and one filter more: `with ownership` and `without ownership`, the entities this machine's player owns, or doesn't (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)). It's for views only: a system runs the same on every machine, so there it's an error, which points to `with Owner`, the entities any player owns. The entity itself isn't a parameter: it's `this` (see [Entity handles](#doc-game--entities--entity-handles)). ## Another set of entities A bullet system runs for bullets, but needs to inspect fighters too. A `query` parameter selects that second set: ```csharp system BulletHits(Body shot, Bullet bullet, query (Body body, with Fighter) fighters) { foreach (var fighter in fighters) { if (Intersects(shot, fighter.body)) fighter.entity.Send(Hit { damage = bullet.damage }); } } ``` `Intersects` is a function the game defines. The outer `Body` and `Bullet` parameters select each bullet; `Body` and `with Fighter` inside the query select the candidates it inspects. The query never requires a bullet to be a fighter. Inside `foreach`, `fighter.body` is read-only component data and `fighter.entity` is that fighter's entity handle. Add more component bindings when their values are needed, and `with` or `without` filters when only presence matters: ```csharp query (Body body, Health health, with Fighter, without Invulnerable) fighters ``` Sparse components and tags are checked for each candidate, and an empty query runs no iterations. A system with only query parameters runs once per tick. Queries use normal deterministic ECS traversal. They do not sort by entity ID, distance or hit time. For a swept projectile, calculate each candidate's intersection and keep the earliest one before sending a hit. Query data reads the current world and participates in [the schedule](#doc-game--schedule). A system that also changes a queried component runs on one thread, following the same rule as reading its own writes through `World`: it sees rows changed earlier in that run. A binding marked [`previous`](#doc-game--systems--as-the-tick-started) reads the tick's start instead, and does neither. Events and structural changes still wait for the end of the tick, so sending a hit or recording a destroy through `fighter.entity` does not change what this iteration reads. Queries have read-only component bindings and component filters. Queries are used directly in `foreach`, or [borrowed by synchronous helpers](#doc-language--functions--borrowing-a-query) with the same `query (...)` parameter syntax. The caller's selection and data timing stay intact. Queries and whole rows cannot be stored or returned; whole rows cannot be passed to functions. Keep iteration and forwarding outside parallel loops (other than the query's own, below) and callback blocks. A component value such as `fighter.body` can be copied or passed to a function. It follows the usual component copy rules, so a method that uses `this` needs the entity's own component parameter. Systems, views and synchronous event and command handlers take queries. A match handler reads the current world at its turn in the tick-end queue: see [Events](#doc-game--events--querying-other-entities). A view's rows are the match as it draws it, blended between ticks, or [`verified`](#doc-game--views-and-the-match--confirmed-state): see [Views and the match](#doc-game--views-and-the-match--other-entities). A local handler's are the match as the tick that sent its event left it: see [Events](#doc-game--events--other-entities). Async handlers and tasks take none yet. ### As the tick started Write `previous` before a binding to read every entity's component as it was when this tick started, whatever has run since: ```csharp system Flock(mut Bird bird, query (previous Bird other) others) { mut var center = float3(0, 0, 0); mut var seen = 0; foreach (var o in others) { if (Math.Distance(o.other.position, bird.position) > 2) continue; center += o.other.position; seen++; } if (seen > 0) bird.velocity += (center / float(seen) - bird.position) * 0.001; bird.position += bird.velocity; } ``` Every bird steers by where the others were when the tick began, not by where the birds before it in the loop have already moved to. That is usually what such code means, and it is what lets it run fast: - **It waits for nothing.** Nothing in a tick can change what a `previous` binding reads, so the system doesn't wait for the systems that change `Bird` this tick, and they don't wait for it. See [the schedule](#doc-game--schedule--when-systems-wait). - **Its entities go across threads.** A system that changes a component and reads everyone's through an unmarked query runs its entities one after another on one thread, as each sees what the ones before it wrote. With `previous` there is nothing of the others' to see, so the birds are shared out over every core, with the same results as on one. - **Its search is made once.** A loop that [starts by skipping rows](#doc-game--systems--only-the-rows-that-can-pass) by a number of a `previous` binding goes through an index of the tick's start. It's made at most once a tick, for every system that searches the same way, and the system may change the very field it searches by (`bird.position` above), which an unmarked query's loop can't. `previous` goes on a binding of a system's query (or a [match handler's](#doc-game--events--querying-other-entities)), and reads the component's values: its text, lists, maps, sets and grids as they were too. The query has the same entities either way, as entities and their components come and go at the tick's end: one spawned this tick is in no query yet, and one destroyed this tick is still there with the values it started the tick with. Other bindings of the same query read the world as it is, and a [function handed the query](#doc-language--functions--borrowing-a-query) reads what the query reads. Filters, a system's own parameters, views and local handlers don't take it. To compare a component now with what it was, take two queries, one with the word and one without. For one entity by its handle, the World has the same: [`world.GetPrevious(target)`](#doc-game--systems--as-the-tick-started-by-handle). Only what code reads of the tick's start is kept, and only for the tick. This is provisional but for the word and what it reads. ### Going through the rows at once A `parallel` loop goes through a query's rows at once, on threads, where each row's work doesn't depend on the others: ```csharp system Hits(query (Body body, with Fighter) fighters, Arena arena) { parallel (var f in fighters) { if (Math.Distance(f.body.position, arena.center) > arena.radius) continue; f.entity.Send(Hit { damage = 1 }); } } ``` The row is a foreach's: `f.entity` and the bindings, read-only. Steps follow a [parallel loop's rules](#doc-language--grids--going-through-every-cell): they change only the variables they declare, and can't spawn, add, remove, destroy or draw. Unlike a list's or a grid's steps, they can send the match's events, to the world or to an entity, and those arrive in the order the `foreach` would have sent them, so the results are the same on any number of threads. An event that holds text or lists can't be sent from a step. In a view, a step also reads its row's [local fields](#doc-game--views), and writes them through a `mut` binding: each row is one entity's, so each step's local fields are its own. That is how a view works something costly out for every row on all the threads, then draws from the results in order: ```tide view Crowd(query (mut Fighter fighter) fighters) { // `shown` is a local field of Fighter: where to draw him, worked out for every row at once parallel (var f in fighters) f.fighter.shown = Stance(f.fighter.position, f.fighter.yaw); foreach (var f in fighters) Draw.Circle(f.fighter.shown, 0.5, Color.white); } ``` A local field that holds text or lists can be read in a step but not changed there, and a step can't read the local fields of the view's own entity where the rows write the same component's. A frame's loops take the threads whenever a host hands them its pool, as the standard one does. This is provisional. ## Only the rows that can pass A loop that starts by skipping rows is read by the compiler. When the condition bounds a number of the row by values the loop doesn't change, the loop visits only the rows within those bounds, found through an index, instead of every row: ```csharp system Separate(mut Body body, Sight sight, query (Body other, with Boid) boids) { foreach (var b in boids) { if (Math.Distance(b.other.position, body.position) > sight.range) continue; body.velocity += Push(body, b.other); } } ``` Each boid looks at the boids near it, not at all of them. Nothing changes about what the loop does: the condition still runs for every row the index gives, and the rows come in the loop's normal order. The condition can be a distance (`Math.Distance`, `DistanceSq`, `Length` or `LengthSq` of a difference, or `dx * dx + dy * dy`), a box written axis by axis, a comparison of one of the row's numbers (`b.unit.health < 10`), or an equality (`b.unit.team == myTeam`), combined with `&&`, `||` and `!`, written in the loop or in a function that returns it. Read-only locals can come first. The same goes for lists: `foreach (var wall in level.walls)`. Equalities of whole numbers are found exactly, all of them at once, unless the condition also bounds a `float` place both ways (a distance or a box), which is searched instead. A world of chunks finds one by its place, an `int3`, and its dimension: ```csharp foreach (var row in chunks) { if (row.chunk.at.x != at.x || row.chunk.at.y != at.y || row.chunk.at.z != at.z) continue; if (row.chunk.dimension != dimension) continue; found = row.entity; } ``` The loop visits the chunks at that place in that dimension and no others, however many share its `x`. Any of the row's `int`, `long`, `byte` and `char` numbers, enums and bools count, and an `int2`'s or `int3`'s components: a `long` a place is packed into (`row.chunk.key == key`) is found the same way. A whole number compared as a `float` or a `double` (`double d = row.chunk.key;`) is not exact, and is searched as the number it's compared as. Other bounds in the same condition, like `row.chunk.heat < limit`, narrow those further. Write `indexed` before a loop that has to be indexed: ```csharp indexed foreach (var b in boids) { ... } ``` `indexed` changes nothing about the loop. It turns a loop that can't be indexed into an error that says why, instead of a loop that quietly looks at every row. Common reasons: - Something happens before the condition, such as a `Send`. Move the condition first. - The value compared with changes inside the loop. - The system changes the same field of its own entity, such as `body.position += body.velocity` in a system whose loop finds boids by `position`. The index is kept while the rows it was made from don't change, so read the others as [the tick started](#doc-game--systems--as-the-tick-started) (`query (previous Body other, with Boid) boids`), or move that change into a system of its own. Handing the component as `mut` to a function or a task counts where that changes its match fields; a view handing its own to a [local task](#doc-game--tasks--local-fields) changes only its local fields, which no loop finds rows by. Handing it to C as `mut` (an `extern` function, or one that passes it on to one) counts as changing all of it. `tidec --schedule` lists every loop that skips rows, and whether an index finds the rest or why not. An index of rows that don't change, like walls, is made once and kept across ticks. An index pays when the condition leaves most rows out. A condition most rows pass, such as `if (b.unit.down) continue;` in a battle where few are down, gains nothing from one, so when a search of a query's rows finds more than about one row in six, the loop goes through every row instead, which costs less for each. The results are the same either way, and nothing needs writing differently. ## Other entities: the World A system often needs another entity's component in the same tick: the target it attacks, the leader it follows. A `World` parameter gives it, by the entity's handle: ```csharp system Attack(Attacker attacker, World world, mut Stats stats) { if (!world.Has(attacker.target)) return; var target = world.Get(attacker.target); if (target.value <= attacker.damage) stats.kills += 1; } ``` - `world.Get(e)` is a copy of that entity's `Health`, or its zero value when it has none. - `world.Has(e)` tells whether it has one. - `world.TryGet(e, out var health)` is both in one: whether it has one, and the copy, or the component's default when it has none (see [Out parameters](#doc-language--functions--out-parameters)). - `world.Set(e, value)` puts one back, and needs `mut World`. It does nothing for an entity without one. - A read-only `Health` parameter keeps the value captured on entering that entity's invocation, including preceding invocations' writes. `Set` updates the world immediately: a following `Get` or query sees the new value. - With `mut Health`, setting the current entity also replaces that active parameter immediately, including through helpers. Setting another entity leaves the parameter unchanged. Whole-value replacement discards unfinished edits; later edits are written back normally. ```csharp system Reset(mut Health health, mut World world) { world.Set(this, Health { value = 20 }); health.value++; // Finishes at 21. } ``` Between the `Set` and the final write-back, `Get` and queries read the published value of 20. An explicit copy made before `Set` keeps its old value. What `Get` gives is a copy, as a list's element is. To change another entity's component, `Edit` it where it is: the block after the call names the component, and what the block changes is put back on the entity as the block ends. ```csharp system Heal(Healer healer, mut World world) { world.Edit(healer.patient, health) { if (health.value >= 100) return; health.value += 1; health.lastHealer = this; } } ``` - In the block, `health` is the entity's `Health` itself, as a `mut` parameter is the component of the entity a system runs for: its fields change where they are, its lists and text too, with nothing copied, and a function's `mut` parameter can take it. The name is new, and only the block has it. - It's put back however the block is left: at its end, or by a `return`, or a `break` or `continue` of a loop the `Edit` is in, or a `try` or `fail` in a function that can fail, in an async handler as anywhere. There's no `Set` to forget on an early `return`. - An entity that's gone, or has no `Health`, skips the block, as `Set` does nothing then. Check `world.Has(e)` first for what to do instead. - It needs `mut World`, like `Set`, and the schedule counts it as `Set`: it reads and writes every entity's `Health`, and keeps the system on one thread. So an `Edit` whose block never changes its name is a warning: read with `TryGet` instead. - `this` can be edited beside a read-only parameter of the same component, as it can be `Set`: the stored component changes, and the parameter keeps what it read. Beside a `mut` parameter of it, change the parameter. - Inside the block, read and change `health`, not `world.Get` of the same entity: the compiler says so where it can tell they're the same, and a task can't `await` there. - `world.Edit(from, a), world.Edit(to, b) { ... }` edits two entities in one block, as other calls that take a block are listed. If they turn out to be one entity, `a` and `b` are the same component, and both changes land. Taking it out, changing it and putting it back is what `Edit` does for you, and still works: ```csharp mut var health = world.Get(healer.patient); health.value += 1; world.Set(healer.patient, health); ``` ### As the tick started, by handle `GetPrevious`, `HasPrevious` and `TryGetPrevious` are `Get`, `Has` and `TryGet` of the entity as it was when the tick started, whatever has run since: ```csharp system Chase(mut Body body, Bot bot, World world) { if (world.TryGetPrevious(bot.target, out var was)) body.velocity = Math.Normalize(was.position - body.position) * bot.speed; } ``` Like a [`previous` binding](#doc-game--systems--as-the-tick-started), they read nothing the tick can change: the system waits for no system that changes `Body`, none waits for it, and its entities go across threads though it changes `Body` itself, where `world.Get` would keep them on one. An entity that wasn't there when the tick started (spawned this tick) has no `Body` then: `HasPrevious` is false and `GetPrevious` gives the zero value. Systems, match handlers and the functions they hand their World to can call them; views and tasks can't. The signature doesn't say which components a system reaches this way: the engine reads it off the calls. Each counts as access to every entity's component, so the system is scheduled like one that touches them all, and one that calls `Set` or `Edit` runs on one thread. [The schedule](#doc-game--schedule--through-the-world) and your editor show what each system reads and writes through its `World`. Where the change can wait for the end of the tick, an event (`e.Send(Hit { ... })`) keeps systems running side by side; see [Events](#doc-game--events). A function or method can take the `World` too, and the system passes its own: ```csharp bool TryFind(Entity target, World world, out Health health) { return world.TryGet(target, out health); } system Aim(mut Attacker attacker, World world) { if (TryFind(attacker.target, world, out var health)) attacker.threat = health.value; } ``` What the function reaches through it counts as the system's own, through however many functions it's passed, so nothing about the schedule changes: `Aim` reads every entity's `Health`. A function that calls `Set` or `Edit` takes `mut World`, and so does the system that passes it. The parameter rules above apply through helpers too, and a view can't call one that changes the match. Views and event handlers take a `World` too; a view only reads the match through it, and can change local entities with `mut World`. A [local handler](#doc-game--events--local-handlers) of one of the match's events takes none: it hears the match as the event left it, and the `World` is the match as it is now. ## Once per entity, or once per tick A system with component parameters runs once for every matching entity, and `this` is the entity it's running for. One without them runs once per tick, for no entity, so it has no `this`: ```csharp system CountDown(mut Round round, Time time) { round.timeLeft -= time.dt; } ``` `return;` ends the system for the current entity, and it goes on with the next one. ## Order Systems run in one order, the same on every machine. By default, it follows the files, sorted by path, then the order of the systems in each file. A game's [packages](#doc-packages--using-and-writing) come first, each after the packages it needs. `[Before]` and `[After]` change that. They take any number of systems: ```csharp [After(Gravity, Collisions)] system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } ``` Of the systems whose constraints are met, the earliest in the default order runs next. Constraints that form a loop are an error that names the loop. Hover a system in your editor to see its place in the order. Systems can share a name when their parameters differ, as [functions can](#doc-language--functions--default-values-names-and-overloads). Nothing calls a system, so where one of them is named, it's written with its parameters' types, in order, with its filters and without names or `mut`: ```csharp system Move(mut Body body, Speed speed, with Player) { ... } system Move(mut Body body, Speed speed, with Enemy) { ... } [After(Move(Body, Speed, with Player)), Before(Move(Body, Speed, with Enemy))] system Aim(mut Turret turret, Body body) { ... } ``` A name alone is fine while only one system has it. When several share it, `[After(Move)]` is an error that lists them as they're written, and so is a parameter list that isn't exactly one's. Views and event handlers work the same way, and the schedule and the profiler show a shared name with its parameters. A system marked `virtual` can be replaced by another package's `override`, which runs where it would have: at its place in this order, with its attributes, and under its name where others name it (see [Virtual and override](#doc-language--overrides)). ### Named phases An enum gives shared names to parts of the tick. Assign systems to its phases with `Stage`: ```csharp enum TickStages { Input, Simulation, Late } [Stage(TickStages.Simulation)] system Move(mut Body body, Time time) { body.position += body.velocity * time.dt; } [Stage(TickStages.Simulation, 10)] system Collisions(...) { ... } [After(TickStages.Simulation)] system Finish(...) { ... } ``` Phases follow the enum members' declaration order. The optional comma-separated offset orders systems within a phase: lower first, with 0 as the default. Negative offsets work too, and the enum needs no numeric spacing. Equal offsets keep the usual order and can use `Before` or `After` on particular systems. `After(TickStages.Simulation)` follows every system in that phase, including its offsets; `Before` precedes all of them. Empty phases keep their position. A system in a later phase waits for the earlier phases to finish, while systems at the same offset can still run alongside each other. Unassigned systems keep their default order wherever the constraints allow. Separate enums have independent phase orders. The same attributes order views among views and event handlers among the handlers of one event. They don't move code between the tick, the frame and event handling. ## Running side by side Two systems that write the same component isn't a mistake: it's normal. Such systems run one after the other, in the order above. Systems that share nothing they write can run at the same time. The compiler works this out from the parameters, and can tell you why each system waits (see [The schedule](#doc-game--schedule)): ``` stage 2 Move (per entity) after Steer: both write Body ``` Declaring more than a system uses makes others wait for nothing, so it's a warning: a parameter that's never used, or a `mut` one that's never written (a `mut World` that never calls `Set` or `Edit` too). A component that's only there to pick entities belongs in `with`. The editors offer quick fixes for these. ## Written in C A system's code can be C's: a library's, or a loop over every entity's numbers that's worth writing by hand. `extern system Move(mut Position position, Velocity velocity);` declares one, with no body, and C is handed the components as the arrays the match keeps them in, rather than an entity at a time. It's a system like the others to everything on this page: its parameters pick its entities, and it's ordered and scheduled by them. See [Systems written in C](#doc-c--functions--systems-written-in-c). ## What systems can't do Systems run the match, so they can't read this machine's local state, and they can't draw: drawing happens every frame, in [views](#doc-game--views). --- Source: https://tide-engine.dev/game/schedule.md Read Tide's system schedule and see how the compiler uses data dependencies to run ECS systems across threads without changing results. # The schedule Every system declares what it reads and writes, so the compiler knows, before the game runs, which systems can run at the same time and which have to wait. That plan is the **schedule**. The tick follows it on every core: a system starts as soon as what it waits for is done, and big systems split their entities across threads too. Running in parallel never changes results, so every machine still gets the same match. A small tick, where waking the other threads would cost more than they'd save, runs on one thread: under about half a millisecond of work, by the time its systems took in the ticks before. On the web, ticks run on threads when the page is cross-origin isolated (see [The tide command](#doc-tools--cli--threads-on-the-web)), and on one thread elsewhere. ## Reading it `tide schedule` prints systems grouped by stage, keeping their tick order within each stage. This example is from a demo where balls bounce around an arena: ``` demo: 5 systems each tick, 4 stages deep; 5 can run alongside others. A system starts once everything it runs after is done. stage 1 Steer (per entity) writes Body, Aim alongside Expire stage 1 Expire (per entity) writes Lifetime alongside Steer, Fire, Move, Bounce stage 2 Fire (per entity) reads Body, Aim after Steer: it writes Aim, which this reads alongside Expire stage 3 Move (per entity) reads Time writes Body after Steer: it writes Body.velocity, which this reads (and through Fire) after Fire: it reads Body.position, which this writes alongside Expire stage 4 Bounce (per entity) reads Arena writes Body after Steer: both write Body.velocity (and through Fire) after Fire: it reads Body.position, which this writes (and through Move) after Move: both write Body.position alongside Expire Views, every frame in this order (they only read, so nothing waits): DrawArena DrawBalls DrawPlayers Options Event handlers, at the end of the tick, as their events are sent: Spawned: Setup ``` `Steer` and `Expire` are both stage 1: neither waits for another system. `Expire` only touches `Lifetime`, so it can run alongside everything else. The others work on the same fields of `Body`, so they wait for each other, in the order they're written, and each wait says which field it's over: `Fire` reads a ball's position, which `Steer` doesn't write, so it's the `Aim` it waits for. Stages show dependency depth; `Fire` can start when `Steer` finishes, even if `Expire` is still running. In the editors, each system shows its stage and why it waits right above it, like `stage 2 · after Move: both write Body`, and on hover. A system that runs for each entity also says whether its entities go across threads, or [what keeps them on one](#doc-game--schedule--splitting-across-threads). Each event's handlers are listed in the order they run. A game with [local handlers](#doc-game--events--local-handlers) of the match's events has those listed after the match's, apart, since they run on each machine at the start of a frame and not in the tick. The ones that wait for the server say `(verified)`: ``` Event handlers, at the end of the tick, as their events are sent: Spawned: Setup Hit: TakeHit Local handlers of the match's events, at the start of a frame, for what the ticks since the last one sent: Destroyed: Mourn (verified) Hit: Count (verified), Flash Glanced: Spark ``` ### Through the World A system's parameters say what it reads and writes of the entities it runs for. What it reaches through a [`World`](#doc-game--systems--other-entities-the-world) parameter is any entity's, and its signature doesn't name those components, so the schedule does, on lines of their own: ``` stage 1 Heal (per entity) reads Healer reads any entity's Armor, through World writes any entity's Health, through World alongside Aim, Chase stage 2 Drain (per entity) writes Health after Heal: both write Health ``` The editors show it above the system too, `stage 1 · World: reads Armor; writes Health`, and when you hover the system or its `World` parameter. A system that passes its `World` to a function reaches what the function does, and it's listed the same way: the schedule doesn't tell the two apart. [Read-only query parameters](#doc-game--systems--another-set-of-entities) also read components of a separate entity set. Those bindings count as reads of any entity's component and appear in the schedule and editor hints, so `query (Body body, with Fighter) fighters` waits for earlier systems that write `Body`, even when their outer entity filters differ. The query's `with` and `without` filters access no component data. In a big game, the long lists are cut short. Every wait that's a system's own is there, but the ones that go through another system (`and through Fire`) and the systems it runs alongside are named up to 32 each and counted past that: `after 412 more, through those`, `alongside Expire, Fade and 168 more`. ## When systems wait Two systems **conflict** when one writes a field of a component or singleton that the other reads or writes. It goes by field: a system that writes `Party.money` and one that reads `Party.at` don't wait for each other, on the same parties at the same time, and `tide schedule` and the editors name the field a wait is over (`it writes Party.money, which this reads`, with `and 2 more of its fields` where there are several). What counts as a system's is what its code does with the value, through the functions it hands it to: reading or copying it whole, calling one of its own methods on it, or handing it to C is every field. A field is as far as it goes (two elements of one array are one field), and small fields kept side by side in a component (four `bool`s, say) count as one. What a system reaches through its `World` is the whole component; a query's rows are the fields its loops read of them, where the system does nothing else with the query. Conflicting systems keep their order in the tick; `[Before]` and `[After]` order systems too. A system starts as soon as everything it waits for is done, with no barriers between stages: a system's stage is only how deep it is in that chain. [Named phases](#doc-game--systems--named-phases), assigned with `[Stage(MyStages.Simulation)]`, add explicit ordering requirements to that plan. Later phases wait for earlier ones, and higher offsets wait for lower offsets within a phase. These names are separate from the numbered dependency stages printed above: systems at one phase and offset can share a dependency stage and run together. The schedule explains these waits as requirements of the stage order. Some things never make systems wait: - **Filters.** `with` and `without` read nothing. - **Entities that can't overlap.** Two systems that write the same component don't conflict if they can never touch the same entity, which the compiler proves from the archetypes: `with Player` against `with Enemy`, when nothing is both. A [sparse component](#doc-game--entities--limits) doesn't count for this: entities with it and without it are one archetype, kept side by side, so `with Stunned` and `without Stunned` still wait for each other. A component a system reaches through its `World` or a read-only query is any entity's, so this doesn't hold for it: `world.Get(e)` and `query (Health health) targets` wait for every earlier system that writes `Health`. - **What code reads as the tick started.** A binding marked [`previous`](#doc-game--systems--as-the-tick-started), `query (previous Body other) others`, and the World's [`GetPrevious`, `HasPrevious` and `TryGetPrevious`](#doc-game--systems--as-the-tick-started-by-handle) read an entity's `Body` as it was when the tick began, which nothing in the tick changes. The system waits for no writer of `Body` over it, and none waits for it. `tide schedule` lists it apart: `reads any entity's Body as the tick started: no wait over it`. - **Structural changes and events.** `Add`, `Remove`, `Destroy` and `Send` are recorded and applied at the end of the tick, in order. Event handlers run then too, so they aren't part of the tick's schedule. - **Input and `Time`**, which systems only read. An entity's input is its owner's, though, so a system that reads its entities' input reads their `Owner`: it waits for an earlier system that changes it. - **C.** Calls to C are trusted: they make no system wait, and a system that calls C splits across threads like any other. What C does when it's called from several threads at once is the game's to get right. A [system written in C](#doc-c--functions--systems-written-in-c) is scheduled by what it declares, as its code can't be read, and shows as `(per entity, in C)`. Some things systems wait for each other over whatever entities they run for: - **Text, lists, maps, sets and grids.** Each component, singleton and event keeps what its fields hold of these in memory of its own, which one system changes at a time. So two systems that change the same component's text or lists wait for each other even when they run for different entities (`with Player` against `with Enemy`), and two that change different components' or singletons' don't. A `Spawn`, `Add` or `Send` whose values hold text or a list changes that component's or event's. `tide schedule` says whose: `both change the text, lists or grids of Party`. Reading them alongside is fine. What C can write is the exception: a component or singleton your code hands to a C function that may change it shares one such memory with every other one handed to C, so systems that change any of those wait for each other. - **Spawns and queued effects.** Spawning makes no system wait: a spawn's identity comes from the entity and the place in the code that made it, and each system's entities are registered once it's done, in the tick's order. Structural and event effects keep system order, then the order of the entities that made them. - **Tasks.** A system that starts [tasks](#doc-game--tasks) runs their code until they first wait, which can spawn and change text, and the match keeps its tasks in the order they start. So it runs on one thread, and waits for the systems before it that start tasks, spawn or change text. Tasks that go on later do so after the tick's changes, one at a time, in the order they started: `tide schedule` says so at its end. ## Keeping it wide - Take a component as `with` when a system only needs it to pick entities. - Don't declare `mut` for what a system only reads. Unused access is a warning, and the editors offer a quick fix for it. - Read and write the fields a system needs where it needs them (`party.money`), rather than copying a component or singleton whole into a variable: a copy reads every field. Systems that use different fields of a big component run side by side without it being split up. - Reach other entities through the `World` only where the answer is needed this tick. An event sent to the other entity makes no system wait. - Where a system looks at other entities and last tick's values will do (who is near, who to chase), read them as the tick started: `query (previous Body other) others`, or `world.GetPrevious(target)` for one by its handle. It then waits for nobody, and goes across threads even when it changes `Body` itself. - Do the costly work new entities need (a chunk made from its seed) in a system that records nothing. One that changes its own entities' text, lists or grids and records nothing shares them out over the threads whatever order they were made in, so those spawned the tick before are spread too. One that also spawns, sends or destroys gives each thread a run of the entities in the order they were made, and the newest, the ones with the work, are all in the last. ## Splitting across threads The other kind of parallelism is a system splitting its entities across threads: each thread takes a run of them, 2,048 at most. How small the runs get depends on what the entities cost: the engine times each system as the match runs, so a few hundred entities that each take a lot of work are shared out over every core, down to a few dozen a thread, while a few hundred cheap ones stay on one thread, where they're done sooner than another thread would wake. It doesn't change results either, and needs nothing from you, but a system only splits when no entity's turn depends on another's. One that changes a singleton and reads it back runs on one thread, alongside the others (below). One that changes its own entities' text, lists, maps, sets or grids (`party.path.Add(next)`, `unit.name = "..."`, `chunk.blocks[x, y, z] = Block.Stone`, `chunk.blocks = Grid3(16, 16, 16)`) splits like any other: the result is the same as on one thread, on every machine. So a system that makes each new chunk of a world from its seed makes them on every core, and one that steps every chunk's cells does too. Two things keep such a system on one thread, and `tide schedule` says which: a component your code hands to a C function that may change it, and a game split across [shards](#doc-multiplayer--shards), whose components keep all of these in the match's one memory. A game with [hidden state](#doc-game--visibility) splits them as any other does, and a system whose entities set their groups' audiences (`Visibility.Set(group, audience)`, as a chunk made from its seed is shown to the players waiting for it) does too: the audiences are set after its entities, in their order, as one thread sets them. What else of visibility it does keeps it on one thread: making or ending a group (`Visibility.CreateGroup`, `DestroyGroup`) in the system, a `Set` in a function it calls rather than in its own code, and a `Visibility` component's own `Set`. Writing an element of a fixed array in the entity's own component (`bot.seen[i] = x`) is a write to that component like any other, and splits. So does one that calls its `World`'s `Set` or `Edit`, which may change any entity, or that reads through its `World` or a query a component it also changes: it then sees the entities it already ran for as it left them, the same on every machine. Reading the component as the tick started (a `previous` binding, `world.GetPrevious`) isn't such a read: the system splits. Everything a system records (spawns, adds, removes, destroys, events) is applied in the order one thread would have recorded it: a system that records anything goes through its entities in the order of their identities, and threads take runs of that order. For a per-entity system that stays on one thread, `tide schedule` says what keeps it there, and where in the code it first does: ``` stage 3 Tally (per entity) reads Body writes Score on one thread: it changes the singleton Score (game.tide:42) ``` The editors say it above the system as well: `on one thread: it changes the singleton Score`, which goes to that place when clicked, or `its entities go across threads` beside its stage. Hovering the system says the same. ### Adding to a singleton A system that runs for each entity and takes a singleton `mut` usually only adds to it: it counts, sums, keeps a least or a most, adds to a list, or hands the singleton to a function that does. No entity's turn then reads what another's wrote, and the system's entities go across threads like any other's. Each thread works out what its entities add, and once they're all done the singleton is changed with those values in the entities' order, on one thread: the count, the list and its order, and a `float` sum to its last bit are what one thread would have made. `tide schedule` says so: ``` stage 2 Enlist (per entity) reads Trooper writes Crowd across threads: what its entities change of Crowd is changed after them, in their order ``` ```tide system Enlist(Trooper t, mut Crowd crowd) { if (t.down) return; crowd.standing[t.team] += 1; crowd.sum += t.position.xz; crowd.spots.Add(Spot { id = this, at = t.position }); } ``` What makes a system one: every statement that names the singleton is an assignment into it or a call that changes it (a list's or a map's method, a function handed it `mut`), and what that statement takes from the entity is plain values: fields, variables, constants, operators, `Math` and constructors of those, or text written out or interpolated from them. A system stays in order on one thread when a row reads what rows write (`if (score.total > 10)`, `unit.rank = score.total`), when what a statement takes from the entity is a call of the game's own or a list, when the function handed the singleton sends, spawns, rolls or starts a task, or when the system calls C. Reading a field of the singleton that the system never writes (`if (unit.id < score.limit)`) is fine anywhere. It only pays where the entities have work of their own, since the adding itself still happens on one thread. A system whose entities do little else than add stays in order as it was, and says so: `on one thread: it changes the singleton Score, and adding to it is most of what its rows do`. Working something out for each entity in the same system as it's added (a path, a score, a nearest enemy) is what the threads take. ## Which waits cost time A wait only costs a tick time when it's on the longest run of systems that each wait for the one before. `tide schedule --measured ` takes the report a [profiled run](#doc-tools--debug-views--profile-captures) wrote (`tide run --release --frames 600 --profile report.json`) and adds, after the schedule: ``` Measured (report.json, 100 ticks, 4 of 4 systems ran): 6.500 ms a tick, the systems one after another 3.500 ms, the longest chain of systems that wait for each other: no tick is shorter, on any number of threads That chain, last to first (a wait that isn't on it costs the tick nothing): 0.500 ms Settle (across threads) after Count: it writes Score, which this reads 2.000 ms Count (on one thread: it changes the singleton Score (game.tide:10)) after Move: it writes Body.position, which this reads 1.000 ms Move (across threads) The costliest systems: 3.000 ms 46% Think (across threads) 2.000 ms 31% Count (on one thread: it changes the singleton Score (game.tide:10)), on the chain ``` The first number is the tick on one thread. The second is what the waits alone leave of it: more threads can't go under it, so a tick gets shorter by making a system on the chain cheaper, by getting its entities across threads, or by removing one of the chain's waits. `Think` costs the most here and isn't on the chain: nothing waits for it, so it runs beside the other three. A system's time is from its start to its end, with its entities on whatever threads they went to, so one that already goes across threads counts as it ran. Systems that didn't run in the profiled ticks count as nothing. A second part does the same for the frame's views, from the same report: what they took one after another, as they run today, and the longest chain of views that wait for each other, by what their parameters read and write and the order `[After]` and `[Before]` give them. A spawn returns its final logical identity immediately; there is no temporary handle or later identity rewrite. Structural installation remains deferred. Queries executed by match/simulation code traverse ascending logical entity identity across archetypes. Presentation/view queries retain their existing traversal order. Extern systems receive contiguous runs in that same global order, while ordinary C function calls from otherwise independent parallel rows retain the game's existing determinism and thread-safety responsibility. ## Parallel loops The third kind is inside a system: a `parallel` loop goes through a grid's cells, or blocks of them, all at once (see [Grids](#doc-language--grids)). It can also go through a [list's elements by index](#doc-language--text-and-lists--going-through-every-element-at-once). Its steps spread across the threads that are free, even while other systems run, and the system goes on once they're all done. Each step reads the collection as the loop found it and changes only its own cell, element or block, so the result is the same as on one thread. A foreach over a grid whose steps only touch their own cell runs the same way. The system itself waits for others as any system that writes the collection's component or singleton would, and the schedule shows its loops: `Fall (once, 1 parallel loop)`. `tide schedule` ends with every parallel loop: what one step of it is reckoned to cost, and from how many steps the loop is worth the threads, or what keeps its steps on one: ``` Parallel loops, and when their steps go to the threads: Crowd, line 107: a query's rows, a step reckoned at 4843: on the threads from 413 steps a frame Weigh, line 72: a list's elements, on one thread: its steps read 'scale', which lives on the thread that made it, as text, lists, maps, sets and grids in variables do ``` The reckoning is of the code as written: a step that returns on its first line counts as much as one that runs it all. A loop under its number runs in order on the thread that reached it, with the same results. The numbers are where a loop starts: as the game runs, the engine times each loop, and one whose steps take longer than their code looks goes to the threads from fewer. A view that runs for each entity and starts with `if (...) return;` tests of this machine's own state (the entity's [local fields](#doc-game--views), a local singleton's fields), or of the entity's `bool`, `int`, enum and `Entity` fields, has those tests run before anything else of the entity is copied, so a view that goes through a thousand entities to draw six costs little for the rest. `tide schedule` lists them: ``` Views that test an entity before copying anything of it: DrawChosen: 2 tests, down to line 90 PoseChosen, the rows of its loop at line 120: 1 test, down to line 122 ``` The second line is a view's query: a view that runs once and goes through its one query in one loop, whose steps start with `if (...) continue;` tests of the same kind, makes no row for an entity they turn away. The loop may be in a function the view hands its query to. The tests may also read fields of the match's that a frame shows exactly as the tick has them: a `bool`, an `int`, an enum or an `Entity`, as in `if (!row.t.laserOn || row.t.holstered) continue;`. A test that calls a function, or reads a field that's drawn between two ticks (a position, an angle), is run by the view's code as usual, after the entity's components are read. ## In CMake builds In a CMake build of the engine's repo, `_schedule` is a build target that prints it, and `tidec --schedule` prints it for any files. --- Source: https://tide-engine.dev/game/events.md Send and handle Tide events in the match and local presentation, with predicted and verified handlers that work through rollback. # Events An event is something that happened, sent from one part of the game to the rest: a hit, a pickup, a round ending. Events carry their context in fields, like a struct's. ```csharp event Hit { Entity attacker; int damage; } ``` ## Sending `entity.Send(...)` sends an event to an entity, and `Send(...)` sends it to the whole world: ```csharp system Explode(Bomb bomb) { if (bomb.timer > 0) return; bomb.target.Send(Hit { attacker = bomb.owner, damage = 50 }); this.Destroy(); } system EndRound(Round round) { if (round.timeLeft <= 0) Send(RoundOver { winner = round.leader }); } ``` The sender isn't recorded. When handlers need it, put it in a field: the entity that sends is often not the one that matters, like a bomb sending a `Hit` for whoever threw it. An event is a value, so a local can hold one, a handler can send its event on (`other.Send(hit)`), and ordinary functions and methods can take or return the whole payload (`int Damage(Hit hit) { return hit.damage; }`). Factories can return `Hit { damage = amount }`; the caller chooses whether to send it. Command payloads follow the same value rules. Passing one grants no world or sending access and supplies no authenticated sender; handlers pass that separately when needed. Payloads cannot be stored fields. Local handlers still receive only the match data their event journal captures. The engine's own events, below, are only the engine's to send. A [function](#doc-language--functions--sending-and-spawning) can send too, for the code that calls it: ```csharp // Called from a system or a handler, which could send Hit themselves void Splash(Entity target, int damage) { target.Send(Hit { damage = damage }); Send(Splashed { }); } ``` A view that calls it gets an error, as a view can't send the match's events. ## Handling A handler is code that runs when an event is sent. It's declared with `event` too: the first parentheses hold the event that triggers it, and the second hold the same parameters as a system's, including read-only [queries](#doc-game--systems--another-set-of-entities) in synchronous handlers. ```csharp // Health and this come from the entity the Hit was sent to. event(Hit hit) TakeHit(mut Health health) { health.value -= hit.damage; if (health.value <= 0) this.Destroy(); } // Takes nothing from the entity, so it runs once per Hit. event(Hit hit) CountHits(mut Stats stats) { stats.hits += 1; } ``` - A handler's components and `this` come from the entity the event was sent to. If that entity doesn't match its parameters, the handler doesn't run for it. - A handler that takes no components runs once per event, whether it was sent to an entity or not, and has no `this`. - A handler that needs an entity needs every `Send` of its event to name one. The compiler checks: `Send(Hit { ... })` is an error when a `Hit` handler takes components, and says to write `entity.Send(...)`. - A handler that doesn't read the event can leave its name out: `event(Spawned) Arm(...)`. ### Querying other entities A match handler can inspect another set of entities with the same query syntax as a system: ```csharp event(RoundOver) ResetPlayers(query (with Player) players) { foreach (var player in players) player.entity.Send(Reset {}); } ``` This runs once per `RoundOver`. The query selects the players to visit; it does not require the event to target a player. Ordinary component parameters still select the event's target. Each `foreach` reads the current match at the handler's turn in the tick-end queue. Earlier handlers' completed writes and structural changes already applied are visible. Sends, spawns, adds, removes and destroys recorded by the handler remain deferred, including changes recorded inside a query loop. `Spawned` queries include the new entity; `Destroyed` queries include the entity before it goes. Rows are read-only. To act on an entity, send it an event or use an explicit `mut World` with the existing `Set` rules. A `Set` is visible to later query reads. Setting the handler's current entity also replaces its active mutable component parameter immediately. Subsequent parameter edits retain usual write-back timing: queries see the value published by Set until the handler finishes, and following handlers see the written-back value. Async handlers and tasks cannot take queries yet. Local handlers' [recorded query rows](#doc-game--events--other-entities) retain their own timing rules. A handler's query can read the tick's start too: `query (previous Body was) all` gives each entity's `Body` as it was when the tick started, whatever the tick's systems and the handlers before this one did to it, and `world.GetPrevious(entity)` the same for one entity. By a handler's turn entities have come and gone, so such a query has the entities that are in the world now and had the component then: one spawned this tick is no row. See [As the tick started](#doc-game--systems--as-the-tick-started). ## When they run Events are handled at the end of the tick, along with structural changes, in the order they were all recorded. A `Send` before a `Destroy` of the same entity is handled while the entity still exists. An event sent to an entity that's gone by its turn is dropped. Handlers can send events and change entities in turn. Those are handled next, until nothing is left, so everything settles within the tick. Systems later in the same tick don't see an event's effects yet, as with `Spawn`. The handlers of one event run in the order they're declared, and `[Before]` and `[After]` order them as they do systems, among the handlers of the same event. Handlers can also use [named phases](#doc-game--systems--named-phases): `[Stage(MyStages.Apply)]`, optionally with an offset such as `[Stage(MyStages.Apply, 10)]`. `Before` and `After` can name a whole phase. Each event has its own order, even when different events use the same phase enum. A handler of an event nothing sends is a warning: it would never run. So is declared access a handler doesn't use, as for systems (see [Systems](#doc-game--systems)). Events waiting to be handled are part of the world: a snapshot holds them, and running a tick again sends and handles them again the same way. What a machine shows of an event is heard [once](#doc-game--events--once-under-rollback) all the same, by a local handler. ## Built-in events The engine sends these. They cost nothing where no handler takes them. The match's handlers take the first four, and so do [local handlers](#doc-game--events--the-engine-s-events), on each machine. | Event | Sent to | When | |---|---|---| | `Spawned` | The entity | It's spawned, or its scene is loaded | | `Destroyed` | The entity | It's destroyed, while its components can still be read | | `PlayerJoined` | The world | A player joins, with their `PlayerID` in `player` | | `PlayerLeft` | The world | A player leaves, with their `PlayerID` in `player` | | `Shown` | The entity, on this machine | The entity and the components a local handler needs become available | | `Hidden` | The entity, on this machine | The entity or components a local handler needs become unavailable | | `Forgotten` | The entity, on this machine | Its [local fields](#doc-game--local-state--letting-go) go: a local event, for local handlers | ```csharp // Spawned has no fields, so it needs no name. event(Spawned) Arm(with Player) { Spawn(Weapon { owner = this }); } event(PlayerJoined joined) GiveBody() { Spawn(Body, Owner { player = joined.player }); } ``` The server picks the tick a player joins or leaves on, so every machine handles it on the same one. Handlers can't draw: drawing happens every frame, in [views](#doc-game--views). What a machine shows of an event goes through a local handler, which leaves it in local state for the views. ## Local handlers A match handler changes the match. What a machine shows of an event is something else: a flash, a burst of sparks, a line in the chat. That's a **local handler**'s, which hears the match's events on each machine. It's `local` before the same `event(...)`, with no keyword of its own: ```csharp component Fighter { int health = 100; local float flash; // This machine's: how long the hit still shows } struct Spark { float2 position; float2 velocity; float age; } local singleton Fx { List sparks; float shake; } event Hit { int damage; } // The match handles the hit... event(Hit hit) TakeHit(mut Fighter fighter) { fighter.health -= hit.damage; } // ...and each machine shows it. local event(Hit hit) ShowHit(Body body, mut Fighter fighter, mut Fx fx) { fighter.flash = 0.2; // A local field of the fighter that was hit fx.sparks.Add(Spark { position = body.position, velocity = float2(0, hit.damage * 0.1) }); } // Views draw what the handler left. view DrawFighter(Body body, mut Fighter fighter) { fighter.flash = Math.Max(0, fighter.flash - Frame.dt); Draw.Circle(body.position, 0.5, fighter.flash > 0 ? Color.white : Color.red); } ``` A local handler changes [local state](#doc-game--local-state) and never the match. Like every handler it can't draw: it leaves what happened where views find it, in a local singleton, in local entities, or in the [local fields](#doc-game--local-state--local-fields) of the entity the event was sent to. Tap a ball below, three times. Each tap reaches the match as a command, whose handler sends the ball a `Hit`. The match's handler of `Hit` takes a health off, and a local one makes the ball flash, through a local field. A ball that meets a wall sends `Bounced` to the world: nothing in the match handles it, and a local handler makes sparks of it. The third hit destroys the ball, and `Destroyed` has two handlers too: the match's spawns another ball, and a local one bursts where the ball was. **Events, and what a machine shows of them** ([Run example](https://tide-engine.dev/examples/events/?stats)) ```tide settings { title = "Events"; tickRate = 30; maxPlayers = 1; } component Ball { float2 position; float2 velocity; int health = 3; local float flash; // This machine's: how long a hit still shows } event Hit { int damage; } // Sent to a ball event Bounced { float2 at; } // Sent to the world, only for what's shown command Poke { } scene Main { } event(Spawned) Setup(with Main) { Spawn(Ball { position = float2(-1, 0.5), velocity = float2(1.6, 1.1) }); Spawn(Ball { position = float2(0.8, -0.4), velocity = float2(-1.2, 1.5) }); Spawn(Ball { position = float2(0, 1), velocity = float2(0.9, -1.7) }); } system Fly(mut Ball ball, Time time) { ball.position += ball.velocity * time.dt; if (Math.Abs(ball.position.x) > 1.5) { ball.position.x = Math.Sign(ball.position.x) * 1.5; ball.velocity.x = -ball.velocity.x; Send(Bounced { at = ball.position }); } if (Math.Abs(ball.position.y) > 1.5) { ball.position.y = Math.Sign(ball.position.y) * 1.5; ball.velocity.y = -ball.velocity.y; Send(Bounced { at = ball.position }); } } // A tap pokes a ball, and the match answers with an event sent to it. command(Poke poke, PlayerID sender) PokeBall(with Ball) { this.Send(Hit { damage = 1 }); } // The match's handler changes the match, at the end of the tick... event(Hit hit) TakeHit(mut Ball ball) { ball.health -= hit.damage; if (ball.health <= 0) this.Destroy(); } // ...and another ball takes the place of one that's gone. event(Destroyed) Replace(Ball ball) { Spawn(Ball { velocity = float2(-ball.velocity.y, ball.velocity.x) }); } // Local handlers show what happened, on each machine, and never change the match. struct Spark { float2 position; float2 velocity; float age; } local singleton Fx { List sparks; } local event(Hit) ShowHit(mut Ball ball) { ball.flash = 0.25; // A local field of the ball that was hit } local event(Bounced bounced) ShowBounce(mut Fx fx) { for (var i = 0; i < 6; i++) fx.sparks.Add(Spark { position = bounced.at, velocity = float2(Math.Cos(i * 1.05), Math.Sin(i * 1.05)) }); } // The ball as it was when it went, though it's gone by the frame. local event(Destroyed) Burst(Ball ball, mut Fx fx) { for (var i = 0; i < 24; i++) fx.sparks.Add(Spark { position = ball.position, velocity = float2(Math.Cos(i * 0.26), Math.Sin(i * 0.26)) * (1 + i % 3) }); } view Arena() { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, 0.15), 2.3); Draw.WireRect(float2(0), float2(3.8, 3.8), 0.03, Color(0.24, 0.25, 0.27)); } view Balls(mut Ball ball, Devices devices) { ball.flash = Math.Max(0, ball.flash - Frame.dt); var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position)); if (devices.pointer.press.down && Math.Distance(pointer, ball.position) < 0.45) this.Send(Poke { }); Draw.Circle(ball.position, 0.14 + ball.health * 0.07, ball.flash > 0 ? Color.white : Color(0.98, 0.75, 0.14)); } view Sparks(mut Fx fx) { mut var i = 0; while (i < fx.sparks.count) { mut var spark = fx.sparks[i]; spark.age += Frame.dt; if (spark.age >= 0.5) { fx.sparks.RemoveAt(i); continue; } spark.position += spark.velocity * Frame.dt; fx.sparks[i] = spark; Draw.Circle(spark.position, 0.04, Color(1, 0.9, 0.5, 1 - spark.age * 2)); i++; } Draw.SetScreen(); Draw.Text("Tap a ball three times", float2(16, 14), 18, Color.white); } ``` ### What they take - **The event**, as a match handler does. One that doesn't read it leaves its name out. - **The components of the entity the event was sent to**, to read. `mut` on one reaches only its local fields, as in a view: `fighter.flash` above. `with` and `without` filter as they do for a match handler. - **The match's singletons**, to read. `Time` is the tick the event was sent in. - **Local singletons**, which it changes. - **Queries**, to go through other entities than the one the event was sent to ([below](#doc-game--events--other-entities)). A handler that takes no components runs once per event, as a match handler does, and one that takes components needs every `Send` of its event to name an entity. What it takes of the match is a copy from the event's turn: as the match's handlers of that event left it, and for `Destroyed`, before the entity goes. So it's all there even when the entity is gone by the frame, which is what lets `Destroyed` say where something ended: ```csharp // Where a shot ended: its Body as it was when it went local event(Destroyed) ShotEnded(Body body, mut Fx fx, with Bullet) { fx.sparks.Add(Spark { position = body.position }); } ``` An event sent to an entity that's gone by its turn isn't heard, as it isn't handled. Local fields are the entity's whether or not it's still there: what a handler writes for an entity that's gone goes with the rest of its local fields, at that frame. Text, lists, maps, sets and grids follow the same recorded timing. The journal retains the values a handler may read, including through synchronous helpers, so later edits or destruction can't invalidate them. Unread container fields add no capture cost. A conditional read still counts as a possible read; copying a whole value reads its fields. Match values stay read-only. You can copy a list, map, set or text into local state using ordinary assignment; grids keep their existing read-only borrowing and copying restrictions. Attached local fields continue to read and write current local state. ### Other entities A local handler takes `query` parameters, as a [view](#doc-game--views-and-the-match--other-entities) does, to go through entities other than the one its event was sent to: ```csharp event Blast { float2 at; float radius; } // Every fighter the blast reached throws a spark local event(Blast blast) ShowBlast(mut Fx fx, query (Body body, with Fighter) fighters) { foreach (var fighter in fighters) { if (Math.DistanceSq(fighter.body.position, blast.at) > blast.radius * blast.radius) continue; fx.sparks.Add(Spark { position = fighter.body.position, velocity = float2(0, 3) }); } } ``` - **Rows are from the tick that sent the event**, like what the handler takes of the entity the event was sent to: the match as that tick left it, whatever it is by the frame the handler runs in. They aren't blended. A handler of a [`verified`](#doc-game--events--verified-handlers) event gets the confirmed tick's. - **They're the tick's once it's done**, after all its events and changes. An entity the tick destroyed is in no row, the one the event was sent to included, and an entity it spawned is in them. The handler's own components are still as the event's turn left them. - **Nothing in it says `verified`**: the handler's event says which tick. Match fields, including captured text, lists, maps, sets and grids, stay read-only. Attached local fields use the entity's current local state when the handler runs. A binding such as `query (mut Fighter fighter) fighters` can write those local fields, including local containers. Local fields are never recorded in the event journal. - **A query of this machine's entities**, `query (Spark spark) sparks`, is the local world as it is when the handler runs. It's the only kind a handler of a local event takes. - **The entities are recorded once for a tick**, however many of its events have a handler that goes through them, and only for ticks that sent one. ### At the start of a frame Local handlers run at the start of a frame, before the views, for each tick this machine simulated since the last frame, in order. What they spawn, change and send locally is handled at the end of the frame, like a view's, and they send [commands](#doc-game--commands) as views do. [Local state](#doc-game--local-state--a-frame-in-order) has a frame's whole order. An event's local handlers run in the order they're declared, and `[Before]` and `[After]` order them among themselves, apart from the match's handlers of the event. An event has 64 of them at most. A local handler of an event nothing sends is a warning, like a match handler's, and `tide schedule` lists each event's local handlers after the match's (see [the schedule](#doc-game--schedule--reading-it)). ### Once, under rollback In a match with other machines, a client predicts ticks ahead of the server, and runs some of them again when the server turns out to have had them otherwise (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). The match's handlers run again with their tick. A local handler doesn't: it hears each event once. - An event the tick sends again as it runs again **stays silent**. It's the same event when it's of the same tick, with the same fields, sent to the same entity. - An event **only the corrected tick has** is heard then, late. - An event **the correction removed** isn't taken back: the spark it made has been shown. Two events alike in one tick are two, and each is heard once. The same entity is the entity, not only its handle: when running a tick again gives a handle to another entity, an event sent to it is another event, and it's heard (see [After a rollback](#doc-game--local-state--after-a-rollback)). ### `verified` handlers Where what's shown must not be wrong, like a death or a goal, the handler waits for the server. `verified` before the event hears it once the server has confirmed the tick that sent it: ```csharp event Died { Entity killer; } // The spark as it's predicted, the death once it's certain local event(verified Died) ShowDeath(Body body, mut Fx fx) { fx.sparks.Add(Spark { position = body.position, velocity = float2(0, 4) }); fx.shake = 0.3; } ``` - **It's never wrong, and never taken back.** It runs once, for what the tick sent as the server ran it. - **It's late**, by as far as this machine runs ahead of what the server has confirmed. - **What it takes of the match is that confirmed tick's**, as the event's turn left it, so nothing else in it is marked `verified`. - **Both kinds can hear one event**: a handler of `Hit` for the spark, at once, and one of `verified Hit` for the damage number, once it's certain. `verified` is local code's word. On a match handler it's an error, as the match is the same on every machine and has no "confirmed". Views take it on what they read: see [Confirmed state](#doc-game--views-and-the-match--confirmed-state). ### Events only local code handles The match can send an event no match handler takes, purely for what's shown: ```csharp // Nothing in the match handles Impact: it's sent for whoever shows it event Impact { float2 at; float2 normal; } system Fly(mut Body body, Arena arena, Time time, with Bullet) { body.position += body.velocity * time.dt; if (Math.Abs(body.position.x) > arena.halfSize.x) { Send(Impact { at = body.position, normal = float2(body.position.x > 0 ? -1 : 1, 0) }); this.Destroy(); } } local event(Impact impact) ShowImpact(mut Fx fx) { fx.sparks.Add(Spark { position = impact.at, velocity = impact.normal * 3 }); } ``` It costs the match nothing. The world's bytes, its hash, its snapshots and what's sent are what they'd be without the event, and a machine with nobody to show it to does no work for it. ### The engine's events `Spawned`, `Destroyed`, `PlayerJoined` and `PlayerLeft` have local handlers too: ```csharp local event(PlayerJoined joined) Greet(mut Chat chat) { chat.lines.Add($"{joined.player} joined"); } // It takes a component of the match's, so it hears the match's entities local event(Spawned) CrateLanded(Body body, with Crate) { Spawn(Puff { position = body.position }); // A local entity } ``` - **`Spawned` and `Destroyed` are sent in both worlds.** A local handler of one hears the match's when it takes something of the match, a component, a filter or a singleton, or when it's `verified`. One that takes only local state hears this machine's local entities'. One that takes a local component and something of the match is an error. - **A machine hears what's sent from the tick it joins in**: its own `PlayerJoined`, and every later one. Nothing is made up for what happened before: the hits, the joins and the entities that came and went. - **`Shown` initializes what this machine comes to have.** It runs for newly available entities and components: those in the world when a machine joins, those revealed later, and genuine spawns. `Spawned` describes a genuine spawn in a tick; joining or receiving an existing entity doesn't make up another spawn. Initialize [local fields](#doc-game--local-state--local-fields) in `Shown`: ```csharp asset Texture crate = "art/crate.png"; component Box { float3 position; local Texture skin; // This machine's } // For every Box this machine comes to have: spawned in a tick, there as // the match started, or already in the match it joined local event(Shown) Dress(mut Box box) { box.skin = crate; } ``` Keep a puff caused by a genuine spawn in `local event(Spawned)`. That effect doesn't run for crates already present when a player joins. - **`Hidden` distinguishes concealment from destruction.** It runs with the last state this machine was permitted to know, before its local fields are discarded. It can hide a model or move presentation data into a game-owned cache. Concealing an entity doesn't invoke match destruction handlers, and destroying an already hidden entity doesn't automatically disclose its destruction. - **Availability follows each handler's requirements.** Revealing an `Inventory` on an entity that already has a visible `Body` runs `Shown` handlers needing that inventory. It doesn't run a `Shown(Body body)` handler again. Required and excluded components both count, as they do in ordinary queries. A whole visible component includes all its fields. - **Availability is reconciled at presentation delivery boundaries (provisional).** Transient add/remove/re-add changes coalesce to the final state. `Hidden` reads the previously delivered endpoint and its query rows, then `Shown` reads the new endpoint. Predicted and verified endpoints are tracked separately. If a correction restores something that became unavailable, `Shown` prepares it again; unchanged replay emits nothing. A local rebuild starts fresh availability history, so initialization should safely reuse or replace existing local resources. - **These are local notifications of match availability.** Write `local event(Shown)` or `local event(Hidden)`, using match components and read-only match singletons, local fields and local singletons as other local handlers do. They can't take local-world components or change the match. `verified Shown` and `verified Hidden` wait for confirmed availability. `Forgotten` remains the resource-release hook when local fields are discarded. - **Ticks that were skipped say nothing**: when a client's world went wrong and the server sent it again, the ticks in between were never run there. Existing entities that are newly available receive `Shown` as that world arrives; nothing a machine already had is shown again. - **A match that changes hands** goes on from the new host's last confirmed tick (see [Host migration](#doc-multiplayer--matches--host-migration)), so the ticks after it are heard again on a machine that had heard them. The entities it had before aren't new to it, and aren't heard again. ### When a field changes `Changed` hears a field of the match that changed over a tick, with what it was, `old`, and what it is, `value`. Nothing has to send it, and a view needn't keep the last value to compare: ```csharp component Health { int value = 100; local float flash; // This machine's } local event(Changed change) Hurt(Body body, mut Health health, mut Fx fx) { if (change.value < change.old) health.flash = 1; // It went down fx.numbers.Add(DamageNumber { at = body.position, amount = change.old - change.value }); } // A singleton's field: the handler runs once, and takes no components local event(Changed change) Cheer(mut Fx fx) { fx.confetti = change.value - change.old; } ``` - **A change is the tick's.** As a tick ends, after its events and changes are done, the field is compared with what it was as the tick began. Several writes in a tick are one change, from the first value to the last, and a field written back to what it was didn't change. It's compared bit for bit, as the match's hash compares it. - **It's sent to the entity whose field changed**, which its handler takes components of, as the tick left it. A singleton's change is sent to the world. - **Only fields that were there before and after change.** Spawning, destroying, adding or removing the component, and an entity this machine comes to have, change nothing: `Spawned`, `Destroyed`, `Shown` and `Hidden` say those. - **The path goes through structs**: `Changed` watches one field of a struct in a component. A field of text, a list, a map, a set or a grid can't be watched; watch a count or a version kept beside it. - **It's like any match event a local handler hears.** It's heard once under rollback, `verified` hears it once the server has confirmed the tick, and ownership filters work. With only local handlers, only the field is compared, and only on machines with a handler of it, so the match's bytes, hash and traffic are what they'd be without it. Match code can handle a change too. What depends on a field then follows it, whatever code set it: ```csharp singleton Workshop { int level; int board; // The level the board was built for int serial; // Moves sent before the board changed are stale } // Only the number is set... void OpenLevel(mut Workshop workshop, int level) { workshop.level = level; } // ...and the board follows it event(Changed change) Load(mut Workshop workshop) { workshop.board = change.value; workshop.serial += 1; } ``` - **It's taken as the tick ends**, after its events and changes are done, the same tick. - **What a handler changes makes another round.** If a handler changes a field something watches (`serial` above, if a handler watched it), that change is sent in a round of its own, the same tick, with what it was after the round before as `old`. Rounds go on until one finds nothing changed. Handlers that keep changing each other's fields stop the program, as any endless chain of events does. - Every machine compares the fields match code watches on every tick, so the match comes out the same on all of them. ### Ownership filters Use `with ownership` or `without ownership` as in a view: ```csharp // Only this machine's own fighter shakes the screen. local event(Hit) Shake(mut Fx fx, with ownership) { fx.shake = 0.2; } ``` The filter uses the owner recorded at the event's turn, after its match handlers ran. Transferring ownership later, removing `Owner` or destroying the entity before the next frame doesn't redirect the event. No `Owner` or `Session` parameter is needed. `without ownership` includes other players' entities and entities with no permitted `Owner`; `with Owner, without ownership` additionally requires that component. The same filters work on `verified` handlers, using their confirmed recording. Ordinary predicted events retain their once-under-replay rule, including when a correction changes only the captured ownership. `Shown` and `Hidden` use their respective delivered endpoints: gaining or losing ownership changes availability for an ownership-filtered handler. A filter alone targets an entity and makes a `Spawned` or `Destroyed` handler hear the match's events. Local-world events, `Forgotten` and query row filters don't accept ownership. ### What isn't there yet - **Container capture follows possible reads**, including through helpers and borrowed queries. Unread container fields are omitted; explicit whole-value copies read their fields. Captured event-payload containers contribute their contents to replay occurrence identity. Local fields use current local state. - **The `World`**, which is the match as it is now and not as the event left it. Nor `Devices` or the input. - **`async`.** A local handler of one of the match's events starts a [task](#doc-game--tasks) instead, by calling an async function with what the task needs. - **`verified` components beside a predicted event.** A handler that hears a tick as it's predicted takes the match as that tick left it. Local state has events of its own too, `local event`, sent and handled on one machine: see [Local state](#doc-game--local-state--local-scenes-and-events). --- Source: https://tide-engine.dev/game/commands.md Send player actions to a Tide multiplayer match with commands, validate their payloads and control delivery, ticks and ordering channels. # Commands A command is an action a player sends into the match: submit a name, choose a team, equip an item, or press a ready button. Declare its payload like an event: ```csharp command Rename { string name; } ``` ## Sending Views send commands with `entity.Send(...)`, or `Send(...)` for an action on the whole match. The text field and other UI state stay local until the player submits them: ```csharp component Name { string value; } local singleton RenameUI { string draft; } view RenameMenu(Name name, mut RenameUI ui, with ownership) { GUILayout.Label(name.value); GUILayout.TextField("Name", ui.draft); if (GUILayout.Button("Rename")) this.Send(Rename { name = ui.draft }); } ``` The engine copies the payload when it is sent, so editing the field afterwards does not change the queued command. Sending is available while connected to a match. Single-player uses the same queue and handler as multiplayer. ## Handling Declare a handler with `command`, like an event handler. Its first parentheses hold the payload and the sender; the second describe the components and singletons it uses: ```csharp command(Rename rename, PlayerID sender) RenamePlayer( Owner owner, mut Name name) { if (sender != owner.player) return; if (rename.name.length == 0 || rename.name.length > 32) return; name.value = rename.name; } ``` The engine supplies `sender` from the player's connection. It is not a field that the player sends. `Owner` identifies the target's owner; targeting an entity does not grant permission to change it. ### Only the sender's own entities Most handlers that take a target begin by checking that the sender owns it. `with ownership` says that in the signature, and the guard and the `Owner` parameter go: ```csharp command(Rename rename) RenamePlayer(mut Name name, with ownership) { if (rename.name.length == 0 || rename.name.length > 32) return; name.value = rename.name; } ``` The handler runs only when the entity the command was sent to has an `Owner` whose `player` is the command's sender. A command sent for any other entity is dropped, as the guard dropped it: it counts as handled, a resend of it is refused, and nothing changes. `without ownership` is the other side, any entity the sender doesn't own, another player's or nobody's, for something like an attack: ```csharp command(Steal steal, PlayerID sender) Take(mut Purse purse, without ownership) { purse.coins -= steal.amount; } ``` It's the word a [view](#doc-game--views-and-the-match) filters with, where it means this machine's player; in a command handler, the player is the one who sent the command. A handler that filters this way can leave its sender out of the first parentheses, or name it to read it. One that does neither is an error: a command handler names the player who sent it, so it can check what that player may do. Systems and event handlers can't filter by ownership: nothing there is a player's, so write `with Owner` for entities any player owns. Below are two machines in one match, each with a badge its player owns. Click the name's field in a frame, type one, and press **Rename my badge**: the command goes to the server, which picks its tick, and both machines run the handler. **Rename theirs** sends the same command for the other player's badge. Nothing stops a machine from sending it, so the handler looks at who did, refuses, and counts. **A command, and a handler that says no** ([Run example](https://tide-engine.dev/examples/commands/?stats)) ```tide settings { title = "Commands"; tickRate = 30; maxPlayers = 4; } scene Main { } component Badge { string name = "Player"; int seat; } singleton Roster { Map badges; int arrivals; int refused; } // An action a player submits. It holds what the player says, never who they are. command Rename { string name; } event(PlayerJoined joined) Arrive(mut Roster roster) { roster.badges[joined.player] = Spawn(Badge { seat = roster.arrivals % 2 }, Owner { player = joined.player }); roster.arrivals += 1; } event(PlayerLeft left) Depart(mut Roster roster) { roster.badges[left.player].Destroy(); roster.badges.Remove(left.player); } // The badge is the one the command was sent to, and `sender` comes from the // player's connection. Being sent a badge isn't permission to change it. command(Rename rename, PlayerID sender) RenameBadge(Owner owner, mut Badge badge, mut Roster roster) { if (sender != owner.player) { roster.refused += 1; return; } if (rename.name.length == 0 || rename.name.length > 12) return; badge.name = rename.name; } // What's typed stays on this machine until it's sent. local singleton Draft { string name = "Ada"; } float2 Seat(int seat) { return float2(Screen.width * (0.27 + seat * 0.46), 190); } view Backdrop(Roster roster) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); GUI.SetTheme(GUITheme { radius = 6 }); // For the views after this one too Draw.Text($"Commands the match refused: {roster.refused}", float2(16, Screen.height - 30), 14, Color(0.64, 0.64, 0.68)); } view Mine(Badge badge, mut Draft draft, with ownership) { var at = Seat(badge.seat); Draw.RoundRect(at, float2(150, 64), 12, Color(0.36, 0.26, 0.04)); Draw.WireRoundRect(at, float2(150, 64), 12, 2, Color.white); Draw.Text(badge.name, at, 20, Color.white, Anchor.MiddleCenter); Draw.Text("yours", at + float2(0, 48), 13, Color(0.64, 0.64, 0.68), Anchor.MiddleCenter); GUI.TextField(Rect(12, 12, Screen.width - 24, 32), "Name", draft.name); if (GUI.Button(Rect(12, 52, Screen.width - 24, 32), "Rename my badge")) this.Send(Rename { name = draft.name }); } view Theirs(Badge badge, without ownership) { var at = Seat(badge.seat); Draw.RoundRect(at, float2(150, 64), 12, Color(0.2, 0.2, 0.23)); Draw.Text(badge.name, at, 20, Color.white, Anchor.MiddleCenter); // Nothing stops a machine from sending this. The handler does. if (GUI.Button(Rect(at.x - 75, at.y + 42, 150, 30), "Rename theirs")) this.Send(Rename { name = "Mine now" }); } ``` A handler is void. Guard clauses end processing, and writes take effect normally, just as in a system or event handler. There is no acceptance call, return status, or transaction that undoes earlier changes. Each command can have at most one handler. The handler can send ordinary events when other parts of the game should react. Components and `this` refer to the target entity, as in an event handler. A handler that takes components, or [filters by ownership](#doc-game--commands--only-the-sender-s-own-entities), runs for the entity the command is sent to, and the compiler requires an entity target for it. A handler with neither runs once for the command. A target that no longer exists, or no longer matches the handler, has no effect. Synchronous command handlers also take read-only `query` parameters, using the same [query rules as match events](#doc-game--events--querying-other-entities). A query selects a separate set of entities, so a handler taking only queries and singletons requires no entity target. It reads the current match at the command's turn in the tick-end queue; recorded events and structural changes remain deferred. Check the authenticated sender's permissions before acting on queried entities, as with any command target. ## Delivery and ticks Commands are queued independently of input. Multiple submissions between ticks remain separate commands, and a late command is not lost because its original input tick passed. The engine resends pending commands and identifies duplicates by a per-player sequence. The server chooses the tick and order. Handlers run at the end of that tick with the existing event and structural-change queue. Each handler sees the changes made by the commands handled before it. Full-world games send recorded commands with tick history so every machine replays that order. With [state visibility](#doc-game--visibility), command handlers execute only on the authoritative server; clients receive their permitted state consequences rather than raw command targets or payloads. Sequence state belongs to the world: snapshots, state hashes and host migration include it. A received command occupies one entry in the authoritative timeline, but its handler can run again during rollback. External side effects must account for replay, as in any simulation code that calls C. ## Ordering: channels A player's commands are handled in the order they were sent, each after every earlier one: the server holds a command back until the one before it has arrived. That's right for most actions, and wrong for a big one: a chat line sent after a file would wait until the file had been uploaded. A command's ordering is its type's. Without an attribute, a command is in the **default channel**, in order with every other command of that channel. `[Channel(...)]` with an enum member of the game's puts it in a channel of its own: in order among that channel's commands, and in no order against the others, so a chat line never waits behind an upload. `[Unordered]` gives a command no order at all: the server handles it in whichever tick it arrives, before or after commands sent earlier, still exactly once. ```csharp enum Channels { Uploads } command Say { string text; } // The default channel [Channel(Channels.Uploads)] command SetBackground { List png; } // Its own: a Say never waits for one [Unordered] command Ping { int at; } // Whenever it arrives, once ``` Whatever the ordering, the server picks the tick and every handler runs in the tick's end queue, in the server's order: a channel only decides what the server holds back waiting for an earlier command. Commands can share a channel, and a channel's name can come from any enum. Each channel has a sequence of its own in the world, and an unordered command has an id of its own, which the world keeps a window of the last 64 of, per player, to drop a resend. The 32 pending commands per player are per channel, so a full channel holds back only its own. ## Big commands A command holds a `List` too, so a player's file goes into the match as it is: an image's bytes, a text's, any file's, for a handler to keep in a component or decode. Such a command is 4 MiB at most. One that doesn't fit a datagram goes as a numbered transfer in chunks, the way worlds go, resent until acknowledged and paced under the input traffic (16 KB an update, about a megabyte a second), so a transfer never delays a tick. It lands in a later tick, as any command may. A command holds lists of other values as well: numbers, bools, enums, vectors, entity or player IDs, and structs of those, in a field or in a struct the command holds. ```csharp struct Slot { [Clamp(0, 9)] int level; float weight = 1; } command Enlist { [Clamp(0, 20)] List attributes; // Each element is bounded List slots; } ``` Each element goes on the wire as a field of its type would, after the list's count, and is checked the same way: a float that isn't finite becomes the element type's default, an enum value no member has becomes its default, and `[Clamp]`, `[Min]` and `[Max]` bound each element, on the list or on a struct's fields. A command with a list follows the same rules as one with a `List`: 4 MiB at most, sent in chunks when it doesn't fit a datagram. A list of text or of other lists can't be sent: send text in string fields or a fixed `string[N]`, or its bytes as a `List`. Commands can't hold maps, sets or grids; a map's keys and values can go as two lists. In full-world games, the server distributes a big command to every player before scheduling it, so no player's tick waits for its download; later joiners receive the resulting world. Visibility-enabled games keep that upload server-side and replicate only permitted state consequences. A few megabytes is fine; larger public media can be a URL fetched by each machine. Put a big command in a channel of its own, or make it unordered, so nothing waits behind it. ## Untrusted payloads The engine checks payload structure and size, UTF-8, numeric values and declared bounds before match code sees the fields. A command holds numbers, bools, enums, vectors, entity or player IDs, strings, `List`, lists of those but strings, and structs of those; it does not hold lists of text or lists, maps, sets, grids, components or device records. The initial limits are 1024 packed bytes per command (4 MiB for one with a list), 32 pending commands per player in each channel, and 16 commands scheduled per authoritative tick. The packed limit includes the command type, target and string bytes. Incoming queues are bounded before allocation. A full session queue leaves local submissions of that channel waiting for capacity. Sending a payload larger than the packed limit, or filling a channel's local submission queue, is a programming error that stops the program with a diagnostic. Starting or leaving a match clears its pending submissions. Host migration preserves them. A hot reload that changes the game's data layout clears pending packed commands, because the new build can give their types a different wire layout. Those checks establish well-formed data. The handler checks permissions, allowed choices, affordability, cooldowns and any other rules of the game. A valid name, item ID or target is not permission to act on it. Use [input](#doc-game--input) for state sampled each tick, commands for submitted actions, and [events](#doc-game--events) for notifications produced inside the simulation. --- Source: https://tide-engine.dev/game/assets.md Import images, audio and glTF, FBX or OBJ models as Tide assets. See supported formats and their limits, then load files or fetch URLs while the game runs. # Assets [Dedicated server builds](#doc-tools--cli--dedicated-servers) can omit assets used only by views and other client code. Assets reached by simulation helpers, defaults and dynamic match asset references remain available. Server and client retain the same match identity even when their packs differ. Projects with custom C retain assets conservatively unless explicitly opting into pruning. An asset is a file a game is built with: an image, a model, a text, some bytes. The language names it, the compiler checks it, and the build packs what's named and nothing else. The second half of this page covers what a machine loads while the game runs instead: a file of the player's, or a URL, which is local to that machine until the match is told about it. `tide build` and `tide run` reuse expensive imports between launches from `.tide/assets/imports`: static/skinned models and animations, generated tangents, audio validation/conversion, and prepared texture pixels or mip blocks. Unchanged draw-only textures can skip image decoding too. The cache is keyed by source contents, external model buffers, import options and importer/decoder revision; editing code, or updating to a Tide whose importers are unchanged, keeps it useful. Entries unused for 30 days, and other Tide versions' results after 14 days, are removed. Each build still discovers glob matches and packs the current declarations and vertex layouts. Grid images keep their exact CPU-readable decoder path. Cache files are disposable: missing, incompatible or damaged entries fall back to the ordinary import, and an unwritable cache does not prevent a build. ## Supported formats | Asset | Build-time source formats | What reaches the game | | --- | --- | --- | | `Texture`, `Grid2`, cubemap faces | PNG, PSD, JPEG (`.jpg`, `.jpeg`), TGA, BMP, [RGBA8 DDS](#doc-game--assets--authored-mipmaps) | Decoded pixels; textures and cube faces use RGBA8 | | `Mesh` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX, OBJ | Static vertices and triangles | | `SkinnedMesh` | glTF 2.0, binary or ASCII FBX | Geometry, skeleton and animation; see [Animation](#doc-game--animation) | | `AnimationCatalog` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX | Skeleton and every animation clip; see [Animation files](#doc-game--animation--animation-files) | | `Animation` | glTF 2.0 (`.gltf`, `.glb`), binary or ASCII FBX | The only clip, or an exact `[Name("source name")]` selection | | `Clip` | WAV, Ogg Vorbis, MP3, FLAC | WAV/Vorbis bytes, or float PCM WAV converted from MP3/FLAC; see [Audio](#doc-game--audio--clips) | | `Font` | TrueType fonts: `.ttf`, an `.otf` of TrueType outlines, a `.ttc`'s first font | Its glyphs' outlines, checked; see [Fonts](#doc-game--views--fonts) | | `string` | Any UTF-8 text file | Text | | `List` | Any file | Its original bytes | These are source imports. Runtime [`grid.Decode`](#doc-game--assets--decoding-a-png) reads PNG only, runtime [`Mesh.Decode`](#doc-game--assets--meshes) reads GLB, a glTF with its buffers inside it and OBJ, runtime [`SkinnedMesh.Decode`](#doc-game--animation--load-while-playing) reads self-contained GLB only, and runtime [`Font.Decode`](#doc-game--views--fonts) reads what a `Font` asset does. `AnimationCatalog` has no runtime `Decode` operation. A supported extension doesn't imply every feature of that format: the image and model limits below say what is read. WebP, TIFF, animated images, SVG, HDR/EXR, compressed DDS and KTX/KTX2 aren't image imports yet. USD, Collada (`.dae`), Alembic, STL, PLY and Blender project files aren't model imports; export a model as glTF 2.0 or FBX, or OBJ for static geometry. Model materials and their textures still need separate declarations and draws. Fonts of CFF (PostScript) outlines, which many `.otf` files have, aren't read: convert one to `.ttf`. Video playback isn't built. Any file can still be packed as `List`, which preserves its bytes without interpreting them. ## Declaring an asset `asset` declares a file's contents under a name, at the top of a file like a constant. The type is what the file is read as: ```csharp asset Grid2 hero = "art/hero.png"; // An image, decoded as the game is built: cells code reads asset Texture tiles = "art/tiles.psd"; // An image that's only drawn asset string rules = "rules.txt"; // UTF-8 text asset List table = "data/table.bin"; // Any file, as its bytes ``` Code reads `hero` wherever it reads a `Grid2`: a system indexes its cells, a view draws it as a texture with `Draw.Mesh`, and a frag samples it by name, `hero.Sample(uv)`, as it samples a singleton's grid. Those four are the plain ones: `string`, `List`, `Grid2` and `Texture`. A sky is a [`Cubemap`](#doc-game--assets--cubemaps), a static model a [`Mesh`](#doc-game--assets--meshes), a model with bones a [`SkinnedMesh`](#doc-game--animation), animation clips an [`AnimationCatalog`](#doc-game--animation--animation-files) asset, a sound a [`Clip`](#doc-game--audio--clips), and a font a [`Font`](#doc-game--views--fonts). **A sprite from a file** ([Run example](https://tide-engine.dev/examples/assets/?stats)) ```tide settings { title = "A sprite from a file"; maxPlayers = 1; } // The file is read as the game is built and packed with it: every machine has // the same pixels, so match code can read them too. asset Grid2 sprite = "art/sprite.png"; component Bouncer { float2 position; float2 velocity; } singleton Arena { float2 half = float2(5, 4); } scene Main { } event(Spawned) Setup(with Main) { Spawn(Bouncer { position = float2(-2, 1), velocity = float2(3, 2) }); Spawn(Bouncer { position = float2(2, -1), velocity = float2(-2, 3) }); } // The match reads the sprite like any grid: here its size, to bounce by its edges. system Move(mut Bouncer bouncer, Arena arena, Time time) { var extent = float2(sprite.size.x, sprite.size.y) / 24 * 0.5; bouncer.position += bouncer.velocity * time.dt; if (bouncer.position.x < -arena.half.x + extent.x || bouncer.position.x > arena.half.x - extent.x) bouncer.velocity.x = -bouncer.velocity.x; if (bouncer.position.y < -arena.half.y + extent.y || bouncer.position.y > arena.half.y - extent.y) bouncer.velocity.y = -bouncer.velocity.y; } view Background(Arena arena) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), arena.half.y * 2); Draw.WireRect(float2(0), arena.half * 2, Color(0.24, 0.25, 0.27)); } // A view draws it as a texture, point-sampled so its pixels stay crisp. view Sprites(Bouncer bouncer) { var p = bouncer.position; var h = 0.5; Draw.Mesh([Vertex { position = p + float2(-h, h), uv = float2(0, 0), color = Color.white }, Vertex { position = p + float2(h, h), uv = float2(1, 0), color = Color.white }, Vertex { position = p + float2(h, -h), uv = float2(1, 1), color = Color.white }, Vertex { position = p + float2(-h, -h), uv = float2(0, 1), color = Color.white }], [0, 1, 2, 0, 2, 3], sprite, Filter.Point); } ``` An asset is read-only. Nothing assigns it, takes it `mut`, or clears it: it's the file as the game was built, the same on every machine. To change pixels, keep a `Grid2` field of your own and copy cells in. Match code reads assets like any value, since every machine has the same pack; a `Texture` is the one that's local code's alone (below). What a machine loads as the game runs is another matter, further down. ### Release builds A standalone `tide build --release` or `--distribution` omits asset declarations that no checked Tide code, default or shader references. An asset named in a helper or a type's default stays, even if that helper or type is unused. A referenced list or map keeps every file its path matches. Every declaration is still checked, so an unused asset with a missing or invalid file remains a build error. Debug and hot-reload builds keep every declared asset. So do games or packages with C/C++ sources or prebuilt libraries, and games with a custom C host: their C code may read assets through the generated API or by name in the pack. A web distribution also compresses the retained pack inside its self-contained page when that saves space. The page decodes the same packed bytes before the game starts; the asset values and match results stay the same. ### A field's default A field's default can name an asset, as it names a constant: ```csharp asset Texture logo = "art/logo.png"; asset string motto = "motto.txt"; asset List table = "data/table.bin"; struct Sprite { Texture image = logo; Color tint = Color.white; } component Sign { string text = motto; // The match's own copy of the text int size = table.count; // An expression can read one local Texture face = logo; // This machine's, as every Texture is local Sprite art; // Its image starts as the logo too } ``` - The field gets the asset's value where the default is given: as an entity is spawned, as a match or this machine's local state starts, and for an entity's [local fields](#doc-game--local-state) nothing wrote yet. - Text, bytes and a glob's list or map become independent field values: changing one changes neither the asset nor another field. Asset-backed lists can share immutable bytes until the first write, when that value detaches into owned storage. A field keeps the value it was assigned across asset reloads. - A `Texture`, a [`Clip`](#doc-game--audio--clips) and a `Cubemap` name their asset, so they cost nothing to give, and under `tide run` a saved file shows through them. - A `Grid2` field can't start as an asset's grid, since a grid is never copied: read the asset's by its name, or give an ordinary color grid to a `Texture` field, `Texture face = hero;`. A numeric `[Raw]` grid uses a [Raw texture field](#doc-game--shaders--textures-that-are-numbers). - One of a glob's, like `run[0]` or `icons["art/icons/star.png"]`, isn't a default yet: a view assigns it. - Only a field's default takes one. A `const`, a setting, an attribute's bound, an asset's path and a parameter's default are constants alone, as the compiler works those out while it builds. ## Images to draw with For color images used by lighting, declare `[Linear] asset Texture albedo = "art/albedo.png";`. The same mark works on a singular `TextureArray` or `Cubemap` asset. GPU reads then return linear light, with filtering and mipmaps in that space, while alpha stays unchanged. Unmarked images keep their existing display-number behavior. A glob's `List` or `Map` takes the mark for every image it holds, each packed for that reading; `[Linear]` does not go on a CPU-readable grid or a glob of grids. See [Linear-light color](#doc-game--shaders--linear-light-color) for fields, parameters and helper functions. `[Raw, Linear]` is refused; `[Linear, Lossless]` keeps a color image uncompressed. Marked DDS images rebuild their mip chain from the base image in linear light, so authored levels with an unknown filtering space cannot silently produce display-space mipmaps. Compression still uses BC1/BC3, through their sRGB forms on devices that support them. A device without BC receives the same mip chain decoded to sRGB RGBA8. Most of a game's images are only ever drawn: sprites, tile sheets, backgrounds, icons. Those are `Texture`s: ```csharp asset Texture hero = "art/hero.png"; asset List run = "art/run/*.png"; asset Map icons = "art/icons/*.png"; local singleton Player { int frame; Texture badge; // Whichever image it's given } view Show(mut Player player) { Draw.Mesh(corners, faces, hero); Draw.Mesh(corners, faces, run[player.frame % run.count], Filter.Point); player.badge = icons["art/icons/star.png"]; Draw.Mesh(small, faces, player.badge); } ``` - An ordinary color `Texture` is a value (see [A Texture is a value](#doc-game--meshes-and-textures--a-texture-is-a-value)): a draw's texture in 2D and 3D, the source a [frag's `Texture` parameter](#doc-game--shaders--textures) is given, a [`Draw.Blit`](#doc-game--render-targets--post-processing)'s source, something a field or a local holds and a function takes. A frag samples one by its name too: `hero.Sample(uv)`. Numeric Raw sources follow the field rules below. - Its RGBA pixels keep a byte per channel: a quarter of what the same image takes as a `Grid2`. Eligible color images use a smaller compressed image instead, described below. - `texture.size` reads its base-level dimensions as an `int2`, without uploading pixels. An image whose pixels the game needs is a `Grid2`, which draws as a `Texture` too, and one file can be declared both ways. - It's this machine's, like everything that's drawn: views, local handlers and frags use it, and match code can't name one. The match reads a `Grid2`. - What a field keeps of `hero` or of `run[2]` is that image as the files have it now: under `tide run`, a saved picture shows through the copies a game kept, as it does through `hero` itself. - How it's sampled can be said once, on its declaration: `[Filter(Filter.Point), Wrap(Wrap.Repeat)]` before the asset (see [Saying it once, on the texture](#doc-game--meshes-and-textures--saying-it-once-on-the-texture)). The `Texture` carries it: what a field keeps of `hero` is sampled as `hero` is. For numeric images, declare `[Raw] asset Texture masks = "art/masks.png";` and retain it in a `[Raw] Texture` field, or sample the asset by name in a shader. A folder of them is a glob's `[Raw] asset List normals = "art/normals/*.png";` (or a `Map`), each image kept as numbers and each element a Raw image. Raw images preserve all channels and stay out of ordinary color draws and `Texture` values. See [Textures that are numbers](#doc-game--shaders--textures-that-are-numbers) for field assignments, parameters and GPU helper forwarding. ### GPU compression `Texture` assets are compressed automatically during the build when both dimensions are powers of two and at least 128 pixels: color images and [`[Raw]` images of numbers](#doc-game--shaders--textures-that-are-numbers) alike, such as normal, roughness and mask maps. Opaque images use BC1; images with transparency use BC3. This includes images in asset lists and maps. Compression is lossy, so sampled values can differ slightly from the source, especially around sharp changes or faint transparency. A Raw image's channels are compressed as the file has them, never multiplied by its alpha. A full mip chain takes roughly one eighth of RGBA's bytes for BC1, or one quarter for BC3, and the pack keeps only the compressed image: a 4096 by 4096 picture is 11 or 22 MB rather than 64 MB of RGBA. Mips are prepared during the build; `Filter.Trilinear` reads them, while Point and Bilinear retain their existing sampling behavior. Vulkan uses BC where the device has it, and WebGPU uses its optional BC feature. A device without any of those (most phones) decodes every mip to RGBA as it uploads the image, preserving the prepared distant levels. That fallback uses the memory of a full RGBA mip chain. Small images, non-power-of-two images, cubemaps, grids and render targets keep their current representation. Images that come out the same bytes are one image in the pack and on the GPU, whichever declarations name them: the same opaque file declared with and without `[Raw]`, or two copies of one picture. `[Lossless]` keeps an image exact, a byte per channel, for numbers that must not move: a lookup table, a flow map, an ID mask. It goes before a `Texture` asset, alone or a glob's list or map, or a `TextureArray` asset, and beside `[Raw]` too: ```csharp [Raw, Lossless] asset Texture flow = "art/flow.png"; // Every byte as the file has it ``` A lossless image costs its full RGBA in the pack, 64 MB for 4096 by 4096, and on the GPU a third more for the mips a `Filter.Trilinear` draw makes as it first reads it. To see what each asset costs, build with `--asset-sizes` (see [the CLI](#doc-tools--cli--asset-sizes)): a line for each declaration, biggest first, with how its images are kept. The renderer keeps recently hidden pack images in a bounded GPU cache, avoiding another upload when they return soon. This is whole-image residency; mip streaming and virtual textures aren't built yet. ### Authored mipmaps For cutout leaves and distant sprites, ordinary averaging can make thin shapes disappear when an alpha test rejects their smaller mipmaps. Prepare a mip chain whose alpha preserves coverage at the material's exact cutoff, then import it as an ordinary texture: ```csharp [Filter(Filter.Trilinear)] asset Texture leaves = "art/leaves.dds"; [Raw, Filter(Filter.Trilinear)] asset Texture normals = "art/leaf-normal.dds"; ``` The DDS must contain one tightly packed, uncompressed RGBA8 or BGRA8 2D image, with power-of-two sides from 4 through 16,384 and every mip through 1 × 1. Use the legacy DDS header with explicit RGB and alpha channel masks. DX10 headers, BC-compressed data, cubes, arrays, volumes, padded rows, missing mips and extra payloads are rejected. Source bytes and decoded pixels plus retained mips each have a 512 MiB import budget. Supply straight RGBA color pixels. The importer premultiplies RGB by alpha separately at every mip; `[Raw]` retains all channels independently. It preserves the supplied mip pixels without recompressing them. The pack and GPU hold the full RGBA8 chain, roughly a third larger than the base image. `Grid2` and cubemap declarations read only the DDS base image. Runtime `grid.Decode` remains PNG-only. Vulkan and WebGPU preserve the chain. Unity's draw recorder currently retains only the base image and does not preserve authored mipmaps. Alpha coverage also becomes approximate at tiny mips because a handful of texels cannot represent every area fraction; atlas authors should preserve each view separately and supply suitable gutters. ### Image formats PNG supports its standard color types and bit depths, palette/key transparency and Adam7 interlacing. PNG metadata, color profiles and gamma aren't applied; an APNG supplies its default image, without animation. PSD retains the saved composite described below. All image formats have a maximum of 16,384 pixels per side. JPEG, TGA and BMP are decoded during the build, through the same `Texture`, `Grid2` and cubemap declarations. Only their pixels enter the pack, so the game needs none of these source decoders. JPEG is lossy and has no alpha; use PNG, PSD or TGA for transparent art. Imported textures keep eight bits per channel, including when the source has more. Color profiles and JPEG EXIF orientation aren't applied; export sRGB pixels in the intended orientation. | Format | Accepted variants | | --- | --- | | JPEG | 8-bit baseline/sequential or progressive, grayscale, RGB/YCbCr or Adobe-marked CMYK/YCCK converted to RGB; no arithmetic coding or 12-bit channels | | TGA | Non-interleaved raw/RLE RGB, grayscale or indexed images, with either vertical/horizontal origin; use 32-bit RGBA for pixel alpha | | BMP | 1/4/8/16/24/32-bit uncompressed pixels or RGB bitfields; no RLE or embedded JPEG/PNG | JPEG/TGA/BMP source data and combined decoder/output allocations are bounded to 512 MiB. Larger images get an error asking for smaller dimensions. A progressive JPEG has at most 256 scans: each one decodes the whole picture again, so a small file of thousands of scans would take minutes to build. These limits, and the Photoshop and FBX ones below, are provisional. ### Photoshop images PSD import needs no Photoshop installation, including when CI builds the game: ```csharp asset Texture portrait = "art/portrait.psd"; asset Grid2 mask = "art/mask.psd"; asset List portraits = "art/portraits/*.psd"; ``` Tide reads the composite image saved in the PSD: the visible layers combined into one picture. Save with Photoshop's **Maximize Compatibility** enabled so the file includes it. Tide doesn't read individual layers or render their effects, text or smart objects itself; their saved appearance is in that composite. The file must be an ordinary PSD (version 1) in RGB mode, with 8 or 16 bits per channel and at most 16,384 pixels per side. Uncompressed, RLE, ZIP and ZIP with prediction are supported. PSB files, other color modes such as CMYK, and 32-bit channels are errors at the asset's path, as is a missing or damaged composite. A `Texture` keeps a byte per channel, while a `Grid2` keeps each decoded channel as a float. Color profiles aren't applied; save RGB art as sRGB for matching display colors. A PSD is at most 16384 pixels a side and 8192 × 8192 in all. Only the decoded pixels are packed, as with a PNG. The game needs no Photoshop files or decoder when it runs. [`grid.Decode(bytes)`](#doc-game--assets--decoding-a-png) still reads PNG only. ## Texture arrays Images of one size, read by a uv and a layer (see [Texture arrays](#doc-game--shaders--texture-arrays)), are a `TextureArray`: a glob's files, in their paths' order, or a list of paths in its own, each a file or a glob: ```tide asset TextureArray ground = "art/ground/*.png"; asset TextureArray picked = ["art/grass.png", "art/rock.png"]; ``` Every image is the same size, 256 at the most. `[Filter]` and `[Wrap]` say how a `Sample` that says neither reads it. ## Cubemaps A sky or a room's surroundings is six images, the faces of a cube, which a frag reads by a direction (see [Skybox and reflections](#doc-game--shaders--skybox-and-reflections)). That's a `Cubemap`, and its path is a glob that matches the six files: ```csharp asset Cubemap sky = "art/sky_??.png"; ``` - **Each file is named for its face** by how its name ends before the extension: `px` and `nx` are the faces `+x` and `-x` point at, `py` and `ny` the ones above and below, `pz` and `nz` the ones ahead and behind. `sky_px.png`, `px.png` and `dusk-PX.png` are all the first. - **Each is a face as it's seen from the cube's middle,** the way a picture is: `+y` is up for the four around, with `+x` to the right of `+z`. The one above has `-z` at its top, and the one below `+z`. - Each uses a supported image format, is square, and all six are one size. A file that's none of the six, a face that's missing or there twice, and a size that differs are errors at the path, which name the file. - A file is in the pack once, as any is: a face that's also an `asset Texture` shares its pixels. - It's a value, like a `Texture`: a field or a local holds one, a function takes one, and a frag samples one by its name, `sky.Sample(direction)`. It's this machine's, so match code can't name one. - No list or map of cubes yet, and no `[Filter]` on one: a cube's filter is said where it's sampled. ## Meshes To keep a static model selection in a component, use a checked asset reference: ```csharp asset Mesh rock = "art/rock.glb"; component Model { Asset> model = rock; } view Render(Model model, World world) { Draw.Mesh(model.model.Value, world.LocalToWorld(this)); } ``` Assign a matching singular asset name in code or a prefab override. `.Value` reads the currently loaded mesh; the stored reference survives geometry reloads and world snapshots. `default` reads an empty mesh. The compiler rejects missing assets and mismatched vertex types. A borrowed mesh variable or a collection element cannot become a persistent reference in this first version. Use `==` and `!=` to compare references of the same mesh type, including aliases: `model.model == rock` or `model.model != default`. Equality identifies the named declaration, so reloading its geometry preserves equality; two declarations naming identical files remain different. References have no ordering or public numeric identity. The same reference rules support `Asset>`, including transparent type aliases. Its `.Value` preserves the packed model's skinning palette and LOD paths; persistent model assignment still uses ordinary owned value semantics. See [Skinned meshes and animation](#doc-game--animation) for an example. A model an artist made, or one a tool generated, is a mesh file: glTF (a `.glb`, or a `.gltf` with its buffers), FBX (`.fbx`, binary or ASCII) or a Wavefront `.obj`. `asset Mesh` declares one as vertices of a struct of yours, `V`, which the file fills by its fields' names: ```csharp struct Corner { float3 position; float3 normal; Color color = Color.white; } asset Mesh tree = "art/tree.glb"; asset List> rocks = "art/rocks/*.glb"; // In order of their paths asset Map> props = "art/props/*.glb"; // By them: props["art/props/bench.glb"] frag Look(Corner corner, out Color color, Instance instance, Sun sun) { color = corner.color * Math.Max(Math.Dot(instance.Normal(corner.normal), -sun.direction), 0.2); color.a = 1; } view Trees(Tree at) { Draw.Mesh(tree, float4x4.Translate(at.position), Look); } ``` The rocket below is a `.glb` as a modelling tool exports one: five meshes with a material's color each, placed by the file's nodes, and no normals. Here it's one mesh, and a frag lights it from the normal each triangle was given. **A model from a file** ([Run example](https://tide-engine.dev/examples/model/?stats)) ```tide settings { title = "A model from a file"; } local scene Main { } // What the file fills, by these names: where each corner is, which way its // face looks, and the color of the part it's in. struct Corner { float3 position; float3 normal; Color color; } // A glTF: five meshes in it, a color each, placed by its nodes. Here it's one mesh. asset Mesh rocket = "art/rocket.glb"; local singleton Stand { float turn = 2.4; float lightAngle = 0.8; bool spin = true; } // The engine has no lighting, so this is ours: the file's normal against a light. frag Lit(Corner corner, out Color color, Instance instance, Stand stand) { float3 normal = instance.Normal(corner.normal); float3 toLight = Math.Normalize(float3(Math.Cos(stand.lightAngle), 0.6, -Math.Sin(stand.lightAngle))); color = corner.color * (0.25 + 0.75 * Math.Max(Math.Dot(normal, toLight), 0)); color.a = 1; } view Show(mut Stand stand) { if (stand.spin) stand.turn += Math.Min(Frame.dt, 0.05) * 0.6; if (stand.turn > Math.TAU) stand.turn -= Math.TAU; Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float3(0, 0.7, -7), quaternion.identity, 45); var turned = quaternion.AxisAngle(float3(0, 1, 0), stand.turn); // The mesh where its vertices and its indices would go Draw.Mesh(rocket, float4x4.TRS(float3(0, 1.2, 0), turned, float3(0.85)), Lit); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 124, Screen.width - 24, 112)) { // Its two lists are there to read, like any list GUILayout.Label(rocket.vertices.count + " vertices, " + rocket.indices.count / 3 + " triangles"); GUILayout.Slider("Light", stand.lightAngle, 0, Math.TAU); GUILayout.Toggle("Spin", stand.spin); } } ``` **A draw takes it where its vertices and its indices go.** `Draw.Mesh(tree, transform, ...)` and `Draw.Instanced(tree, instances, ...)`, a render target's too, with whatever follows a mesh's lists after it: a texture, a vert, a frag, [values](#doc-game--shaders--values-for-one-draw). A view that runs for each of a thousand trees draws them [all at once](#doc-game--shaders--many-at-once), and the mesh is sent to the GPU once, however often it's drawn. **The file fills the struct by its fields' names**, each a type the file's values are: | Field | Type | What the file gives it | | --- | --- | --- | | `position` | `float3` | Where the vertex is. Every mesh's vertex has one. | | `normal` | `float3` | Which way the surface faces there. A file with none gets each triangle's own, so it's lit flat. | | `uv` | `float2` | Where in a texture the vertex is, (0, 0) at its top left. (0, 0) where the file has none. | | `uv2` | `float2` | The file's second set of those, which a lightmap uses. | | `color` | `Color` | The vertex's color times its material's. White where the file has neither. | | `tangent` | `float4` or `float3` | Tangent direction in `xyz`; a `float4` also carries bitangent handedness in `w`. Missing tangents are generated only for static `Mesh` layouts declaring `float4 tangent`. | | `joints` | `int4` | A skinned model's four heaviest bones at the vertex, heaviest first, numbered as a [`SkinnedMesh`](#doc-game--animation) of the file numbers its `Bone`s. 0 where no bone moves it. | | `weights` | `float4` | Those bones' weights, which sum to 1. Zeros where no bone moves it. | - A struct has the ones it needs, in any order: `Corner` above takes no uvs, so the pack holds none. - **A field of any other name keeps its default.** So one struct serves the meshes a game makes in code and the ones it loads: `float glow = 1;` is 1 at every vertex of a file's. A default can read another asset, even one declared later; each pack load supplies its current value and refreshes what is drawn when that value changes. - A field with one of those names and another type is an error at the declaration, which says the type the file's is. - The built-in [`Vertex3`](#doc-game--3d) is a position, a uv and a color: `asset Mesh crate = "art/crate.glb";` draws with no frag, `Draw.Mesh(crate, transform, wood)`. - **A mesh with bones is the model at rest.** A vertex with `joints` or `weights` reads the file as a skinned model: its `position` and `normal` are where the model's rest pose puts them, as a `SkinnedMesh` of the file draws at rest, in its skeleton's space (a model in centimetres comes out in metres, as it's drawn). A vert of the game's can then skin it itself, against bones of its own: a crowd's thousands in one instanced draw, each bone's `pose.Model(bone)` times the inverse of its rest's in a list the vert reads. `[LOD]` weighs the bones as it does a skinned mesh's. Only a static `Mesh` whose vertex layout declares `float4 tangent` gets a tangent-generation variant. For its primitives without authored tangents, import derives tangents from triangle UV gradients and averages them with corner-angle weights. Generated `xyz` is normalized and orthogonal to the imported normal, with handedness `w` of +1 or -1; the bitangent is `w * cross(normal, tangent.xyz)`. A vertex shared by generated corners with opposite UV handedness splits at that seam. Missing or degenerate UVs get a finite fallback frame. Authored tangents retain their existing coordinate/node-transform conversion, including authored zero and nonorthogonal values; the generated-basis guarantees do not apply to them. Generated tangents support ordinary tangent-space normal maps but do not guarantee a match to a MikkTSpace normal-map bake. Layouts without a tangent field, layouts with `float3 tangent`, and skinned meshes retain their prior imported streams, vertex counts, indices and canonical hashes. Missing `float3` tangents remain zero. Generating a variant for one declaration does not change another declaration's canonical import. Metadata-only language-server checks use canonical imports and do not generate tangent variants. **It's two lists.** `tree.vertices` is a `List` and `tree.indices` a `List`, three for each triangle, and `Draw.Mesh(tree.vertices, tree.indices, transform, Look)` is the same draw. Any code reads them, the match too, since every machine has the same pack, to the bit: a system can build a collider from a rock's own triangles. They're read-only, like every asset; copy one to change it, `mut var mine = tree.vertices;`. **One file is one mesh.** Everything the file's scene places is in it, where its nodes place it, as one list of vertices and one of triangles, with each part's material color in its vertices' `color`. Only vertices its triangles use are kept; a glTF primitive that shares a larger vertex array with other materials keeps its own part of that array. That's all a model in flat colors needs. What a game moves apart, a car's wheels from its body, is a file each, and a glob names them: `asset Map> car = "art/car/*.glb";`. **What's read, and what isn't:** - From a glTF: its meshes' positions, normals, tangents, two sets of uvs and vertex colors, its nodes' places, and each material's base color. Not its textures, nor the rest of a material; not skins, animation, morph targets, cameras or lights: a skinned model is the mesh as it stands. Required Draco/meshopt compression and other unsupported required extensions give an error with export guidance. Optional compression can use the file's valid uncompressed fallback. - From an OBJ: positions, uvs, normals and faces of any number of corners, with a color after a position where a tool wrote one. Not its materials file. - From an FBX: polygon meshes, node transforms, normals, tangents, two sets of uvs, vertex colors and material base colors. Polygons are triangulated, and the file's axes and units are converted to Y-up meters before Tide's coordinate conversion. An attribute index past its array, which some exporters write, reads the array's last element, as Blender and Unity read the file. Embedded textures and the rest of a material are not imported. A static `Mesh` takes the rest geometry; use [`SkinnedMesh`](#doc-game--animation) for bones and animation. A file's polygons can't take more than 2^32 steps to triangulate in all (a polygon's corners squared, summed: one polygon of 65,536 corners), and its animation takes bake to 16,777,216 keys at the most. - **A texture a model has is a file of its own**, using a supported image format, declared like any: `asset Texture bark = "art/bark.png";`, and given to the draw. - A mesh holds 16,777,216 vertices and 8,388,608 triangles at the most. A glTF's description can have 4,194,304 JSON values, and 536,870,912 numbers are read from its accessors in all, an accessor counting again for each part that names it. A file past one of these is refused before anything is made for it. The numbers are provisional. **It comes in as Tide has the world.** Tide's world is left-handed with fronts [clockwise](#doc-game--3d--which-side-draws), like Unity's. glTF is right-handed with fronts counterclockwise: a file's `x` is turned around and its triangles are wound the other way, so `+y` stays up and a model that faces `+z` still faces `+z`. OBJ uses the same conversion. FBX first converts its declared axes and units to right-handed Y-up meters, then uses that conversion too. A glTF's colors are light, and a `Color` is what the screen shows, so they're converted; an OBJ's are taken as written. **An asset's mesh value is a stable ID.** Fields, lists, arrays, maps, parameters and tasks can keep a `Mesh` without copying an asset's vertices or indices. Reading `.vertices` or `.indices` borrows the currently loaded geometry. `Asset>` holds only that ID, for a reference that must name an asset (the editor assigns one); it goes wherever a `Mesh` does, and its `.Value` is that `Mesh`. ```csharp component Prop { float3 position; Mesh model; } singleton Models { List> choices; Mesh[2] favorites; } view Props(Prop prop) { Draw.Mesh(prop.model, float4x4.Translate(prop.position)); } ``` **A mesh the game makes is a `Mesh` too.** `Mesh(vertices, indices)` takes a `List` of a 3D vertex struct and a `List` of indices, three a triangle, and makes a static mesh of copies of them. Nothing changes the copies after, whatever happens to the lists they came from, so there is nothing to free: the mesh lasts as long as the value holding it, like any list. It goes wherever an asset's mesh goes: fields, lists and maps of meshes beside assets', parameters, `Draw.Mesh` and `Draw.Instanced`, and anything else that takes a `Mesh`. A type alias makes one too: `Model(vertices, indices)`. ```csharp using Model = Mesh; singleton Terrain { Model ground; List pieces; } system Build(mut Terrain terrain) { List corners = [Vertex3 { position = float3(0, 0, 0) }, Vertex3 { position = float3(1, 0, 0) }, Vertex3 { position = float3(0, 0, 1) }]; terrain.ground = Mesh(corners, [0, 2, 1]); terrain.pieces = [rock, terrain.ground]; } ``` - **Where it's kept decides its cost.** In match state its geometry is part of the match: in snapshots and hashes, sent whole to a player who joins, and to the others once, as it's made. Its pages never change after, so rollback copies and the per-tick hash cost almost nothing more. Keep geometry only the screen needs in local state, where none of that applies, or make it in a view each frame. - **Copies are one mesh on the GPU.** Every copy draws with no list read: the mesh's id is worked out from its contents once, when it's made, and the draw uses it as the geometry's version. A copy of the value copies its two lists. - **Equality compares contents:** two meshes made of the same lists are `==`, and a made mesh is never an asset's or `default`, even with no triangles. - **Levels of detail** are the draw's to ask for, `lod:`, as for any mesh your game makes (below). - **Not there:** a made `SkinnedMesh`; and a 2D mesh, which draws from its two lists, `Draw.Mesh(vertices, indices)`. **A mesh read while the game runs is a `Mesh` too.** `Mesh.Decode(bytes)` reads a model from a `List`, from [`await Web.Fetch(url)`](#doc-game--files), `File.ReadAllBytes(path)` or a player's upload, and gives a `Mesh fails IOError`. It reads the file as an `asset Mesh` of it does: the same vertices, filled by your vertex struct's field names, every other field its default, a `float4 tangent` made where the file has none. It's the same bits on every machine, so match code can decode too, and the mesh then lives as a mesh your game makes does (above). ```csharp using Model = Mesh; singleton Arena { Model statue; PlayerID host; string message; } command SetStatue { List model; } command(SetStatue value, PlayerID sender) Apply(mut Arena arena) { if (sender != arena.host) return; if (Model.Decode(value.model) is Model statue) arena.statue = statue; else arena.message = "That isn't a model"; } ``` - **Formats:** a `.glb`, a `.gltf` whose buffers are inside it (data URIs), and an `.obj`, told apart by their first bytes, as the bytes have no name. A `.gltf` that names buffer files, and an FBX, which Tide reads at build time only, are `IOError.InvalidData`, as is anything else that isn't a mesh. - **A vertex with `joints` or `weights`** is a [Mesh with bones](#doc-game--animation), read from a `.glb` as its asset is: at rest, each corner with its four heaviest bones. - **Limits:** a file of more than 512 MiB, 1,048,576 vertices, 6,291,456 triangle corners, 4,194,304 JSON values or 67,108,864 numbers read (an `.obj`'s vertex, normal and uv lines count) is `InvalidData` before anything is made for it, and so is a mesh whose numbers a node's transform takes past what a float holds. Each machine that refused one says why on its log, naming the limit: `tide: Mesh.Decode refused a mesh: it has 2,000,000 vertices in a part, more than the 1,048,576 Mesh.Decode takes (TIDE_MESH_DECODE_MAX_VERTICES)`. Collections follow ordinary value-copy and mutation rules. Copying an immutable asset collection can share its ID storage until a write. Geometry stays in the asset pack. Singular IDs follow the qualified declaration name; glob-element IDs also include the written file key, so changing a glob's order keeps retained selections stable. A removed or unknown ID resolves to empty geometry. Renaming a declaration or file key changes that identity. A frag and a vert don't read a mesh's two lists: the draw sends them to the GPU as the mesh they are. ### Levels of detail A model with thousands of triangles costs the same to draw when it's a dot on the horizon as when it fills the screen. `[LOD]` before a mesh asset has simpler versions of it made as the game is built, and each draw then picks one by how big the mesh is on screen: ```csharp [LOD] asset Mesh rock = "art/rock.glb"; view Rocks(Scenery scenery) { Draw.Instanced(rock, scenery.transforms, Look); // Each rock at its own level } ``` That's all there is to write. There are no distances to set, no levels to author and nothing more to pass a draw. - **It's opt-in.** A mesh without `[LOD]` is drawn as it always was, with nothing made for it. - **A level is fewer of the mesh's own triangles.** Each has about half the triangles of the one before, over the same vertices: none is added or moved, so the pack grows by the levels' triangles alone, about as much again as the mesh's own. Open edges stay where they are, and so do the seams where a texture or a color changes, so no hole opens and no texture tears. - **Static layouts with a `float4 tangent` preserve opposite handedness signs as separate seams.** Tangent `xyz` adds no simplification error metric. Other vertex layouts and skinned meshes retain their previous LOD behavior and cache keys. - **A mesh of under 1,000 triangles gets no levels.** Levels only pay by the triangles they take off a draw, and picking one costs a little for each instance, so such a mesh draws exactly as if it weren't marked, with nothing picked. A bigger mesh's chain goes on to levels of a few dozen triangles, and stops before one of under 64: a crowd far off draws each figure that small. - **A draw picks by estimated visual error on screen.** Each level knows how far its surface, and what's on it, is from the full mesh's. A normal or a color is off by as much as the patch it's off on: a bevel shaded a little differently counts for the bevel's size, not the whole mesh's. A draw takes the simplest level within its pixel tolerance, 1 by default. A mesh drawn large keeps more detail at any distance. - **Each instance picks its own.** `Draw.Instanced` over a field of rocks draws the near ones whole and the far ones simple: one GPU draw for each level in use, the instances of each in the order the list has them. A view that runs for each entity is grouped the same way. - **Your code reads the full mesh.** `rock.vertices` and `rock.indices` are what they are without `[LOD]`, for the match too: a collider built from a rock's triangles is built from all of them, on every machine. - **It works on a [`SkinnedMesh`](#doc-game--animation) too:** `[LOD] asset SkinnedMesh hero = "art/hero.glb";`. Its levels are made from the model at rest, weighing how each vertex follows its bones so joints keep the vertices that bend them, and a pose deforms a level as it deforms the full mesh. - **A list or a map of meshes** takes it for every file: `[LOD] asset List> rocks = "art/rocks/*.glb";`. - **An asset can accept more error:** `[LOD(2)] asset Mesh rock = "art/rock.glb";` multiplies the draw's pixel tolerance by 2. `[LOD]` means 1. The argument must be a positive finite constant number; fractions below 1 keep more detail. It applies to every file in a list or map and works on skinned meshes too. The generated levels stay the same. - **They're made once.** tide keeps a mesh's levels in the game's `.tide/` folder, by what's in the file, so later builds don't make them again. **A mesh your game makes gets levels with `lod:`.** Terrain chunks, generated buildings, anything built into a `List` or a list of your own vertex while the game runs: write `lod:` last in its 3D `Draw.Mesh` or `Draw.Instanced`, with the same multiplier `[LOD(...)]` takes: ```csharp view Terrain(Chunk chunk) { Draw.Mesh(chunk.vertices, chunk.indices, chunk.transform, Look, lod: 1); } ``` - **The levels are the ones an asset of the same mesh would get**, made by the same code: the same floor of 1,000 triangles, the same seams kept, the same picking, and the same levels on every machine. - **They're made in the background**, on threads beside the frame's, never in it. Until they're there the mesh draws whole: a frame or so for a mesh of thousands of triangles, longer for a big one. Where there are no threads to make them on (a web page that isn't [cross-origin isolated](#doc-tools--cli--threads-on-the-web)), such meshes draw whole. - **They're kept by what's in the mesh.** Drawing the same lists again costs nothing more, nor does making the same mesh again or drawing it again after a while away. Lists made again with other numbers start over: what was being made of the old ones stops. A mesh that changes every frame keeps drawing whole, which is right for one that moves its vertices. - **The fields weighed are your vertex's `position` (a `float3`), and `normal`, `uv`, `uv2`, `color` and `tangent` where it has them** with those names and types, as an asset's file fills them. - **The same lists drawn without `lod:` are another mesh**, drawn whole, and so are the same lists drawn with another multiplier. `lod: 0`, or a multiplier that's no number, is 1, as `Draw.LODPixels` takes them. - It's for 3D meshes: a 2D mesh draws as it is. A model with bones takes it too, `Draw.SkinnedMesh(model, transform, lod: 1)`, with its bones weighed as `[LOD]` weighs them, so a model decoded while the game runs (`SkinnedMesh.Decode`) gets the levels its file would get as a marked asset. **A game's vert isn't known to the pick.** Where the mesh is and how big it is come from the file's own geometry and the draw's transform. A vert that moves vertices far from there, or grows the mesh, gets levels picked for where the mesh would have been: draw such a mesh with `Draw.LOD(0)`, below, or leave `[LOD]` off it. **`Draw.LODPixels` controls the quality/performance tradeoff** while each mesh still picks automatically. The default is 1 pixel of estimated visual error. Higher values allow coarser meshes at the same distance; positive values below 1 keep more detail: ```csharp Draw.LODPixels(4) { Draw.Instanced(rock, scenery.transforms, Look); } ``` `Draw.SetLODPixels(4);` applies to following window draws. A render target has its own tolerance: `shadow.SetLODPixels(4);`. The asset's multiplier applies too: `[LOD(2)]` allows 2 pixels normally and 8 in that shadow pass. Both draw-setting forms restore 1 with no arguments; a block restores the previous value when it ends, including an early exit. Nonpositive or nonfinite draw-setting values also use 1. This changes selection among the levels already built; it doesn't generate more levels. Pixels are counted through the same camera and resolution as automatic selection. **`Draw.LOD` names the level** instead of picking it, a [draw setting](#doc-game--draw-settings) with the two forms the others have. A named level overrides the pixel tolerance. `0` is the full mesh, `1` the first simpler one, and a number past a mesh's last level is its last: ```csharp Draw.LOD(0) { Draw.Mesh(rock, transform, Look); // Whole, wherever it is } ``` With no number, `Draw.LOD() { ... }` and `Draw.SetLOD();`, each mesh picks again. Every instance of an instanced draw has the level that's named, so the draw is one GPU draw in the list's order, which is what instances drawn with a blend and no depth need. **`Draw.LODCamera` names the camera to pick through**, in place of the one the meshes are drawn through. A [shadow map](#doc-game--render-targets) picks with its lamp's camera and its own pixels, so a mesh could cast the shadow of another level than the one the player sees. Told the player's camera, it casts what's shown: ```csharp view Cast(Lamp lamp, Viewer viewer, Rock rock) { lamp.shadow.SetCamera(lamp.transform, lamp.projection); // What the shadow is drawn through lamp.shadow.SetLODCamera(viewer.position, viewer.rotation, 60); // What picks its levels lamp.shadow.Mesh(rocks[rock.model], float4x4.Translate(rock.position), Depth); } ``` It takes what `Draw.Camera` takes for a 3D camera: a position, a rotation and a field of view, or a transform and a projection (`Draw.CameraTransform()` and `Draw.CameraProjection()` give the window's). With nothing, `SetLODCamera()`, the destination's own camera picks again. A level that's named wins over a camera that's named. A shadow map covers more than the player sees: meshes beside the player and behind them. Those pick by how far out of the view they are, so they cast coarser shadows the farther out they are, and the shadow map's `SetLODPixels` coarsens them as it does the rest. **Info** That a mesh opts in with `[LOD]`, that everything after it is automatic, that each instance picks its own, that skinned meshes have it, and that a game can name a level, a pixel tolerance or a camera to pick by, are decided. How the levels are made and the other rules above are how it works today, and may still change. ### Blend shapes to keep A skinned model's [blend shapes](#doc-game--animation--blend-shapes) are all imported, which can be most of a pack: a head with fifty facial shapes carries fifty sets of vertex deltas. `[BlendShapes(...)]` before a `SkinnedMesh` asset keeps only the shapes whose source names match one of its arguments, a name or a pattern where `*` is any run of characters: ```csharp [BlendShapes("masculineFeminine", "default*")] asset List> parts = "sidekick/parts/*.fbx"; ``` The other shapes are left out of the import, deltas and all, and the vertices keep every shape at the file's default weight as before. A pattern that matches nothing in a file is fine, as in a glob of parts where only some have a shape; `[BlendShapes()]` keeps none, and a model left with no shapes packs as it would with none in its file. It applies to every file of a list or a map. Without it, every shape is kept. ## Paths A path is relative to the `.tide` file that names it, whatever that file's namespace: there's no assets folder and no root. A package's files name files beside its own code the same way. Forward slashes, on every platform. A path is a constant: a string literal, or a `const string`, so a game that wants one path twice names it once: ```csharp const string TILES = "art/tiles.png"; asset Grid2 tiles = TILES; ``` ### Globs A glob names every file it matches, in order of their paths (byte by byte): `*` matches within a name, `**` across folders, and `?` one character. The type says what you get: ```csharp asset List> run = "art/run/*.png"; // Their contents, in order: run[0], run[1], ... asset Map> tiles = "art/tiles/**/*.png"; // Each path as written from this file, with its contents asset List notes = "notes/*.txt"; asset List frames = "art/walk/*.png"; // Images to draw with, in order ``` A map's keys are the paths as you'd have written them, `"art/tiles/grass.png"`, so a game finds a file by name: `tiles["art/tiles/grass.png"]`, `tiles.Has(name)`. A glob that matches nothing is an error, and so is a glob for a type that holds one file. A list or a map can name one file, and is then a list or a map of that one: ```csharp asset List shots = "sfx/shot.wav"; // shots.count is 1, and shots[0] is the file asset Map named = "sfx/shot.wav"; // named["sfx/shot.wav"] ``` Synchronous CPU helpers can [borrow resource asset collections](#doc-language--functions) through read-only `List`, `List`, `List>` or `Map` parameters. Pass the asset directly; the call reads its existing collection without copying it. That's for a path that changes while the game is made. Start with the one file there is, widen the path to `"sfx/shot*.wav"` or `"sfx/*.wav"` when there are more, or narrow it again, and the type and the code that reads it stay as they are. A map's key for the one file is its path as written, which is the key a glob gives it. A URL in a list or a map is the same: one entry, keyed by the URL. A frag samples an asset by its own name: it can't index a list of them (`run[1].Sample(uv)` is an error), so declare the one it samples as an asset of its own, or for a `Texture`, give the draw that one as the frag's source: `Draw.Mesh(corners, faces, frames[1], Shade)`. ### URLs A path can be an `http://` or `https://` URL. The compiler fetches it as the game is built and packs what it got, so it's a file kept elsewhere and nothing else: nothing is fetched when the game runs, and the game plays offline. ```csharp asset string credits = "https://example.com/credits.txt"; ``` What was fetched is kept in the game's `.tide/`, with the server's ETag. Each build asks the server whether the file changed, and builds from what it has when the server can't be reached, so an offline build works once the file was fetched once. A URL that can't be fetched and was never cached is an error. ## Assets made by code An asset's value can be a call of code that runs while the game builds, which makes it from nothing or from another asset's file: `asset Texture hero = Outlined(heroSource, Color.black);`. A sound's samples are an asset too: `asset ClipData step = "sfx/step.wav";`. See [Build code](#doc-game--build-code). ## What's checked Anything wrong that can be known as the game is built is an error at the declaration, in the editor as you type and in `tide build` alike: - A file that isn't there. The error says where a file with the same bytes is now, if the file was moved (the compiler keeps a hash of every named file in the game's `.tide/`), or else lists the files of that name, with a quick fix for each in the editor. - A glob that matches nothing. - Bytes that aren't what the type says: an unsupported image/audio/model format, a damaged supported file, an unsupported codec or required extension, or text that isn't UTF-8. The diagnostic names the source file and the reason, with supported alternatives or export guidance. - A type an asset can't be, a path that isn't a constant, a `local` or `virtual` asset, a write to one. The editor keeps assets in step with their files: renaming a file or a folder rewrites the paths that name it, and a path's completion offers the files it can lead to. See [Editors](#doc-tools--editors). ## The pack `tide build` packs the closure of the game's `asset` declarations, and nothing else in the folder. A file is in the pack once however many declarations name it, and they all read the same value: a `Grid2` of the pack lives in a read-only region every world can name, outside every world's heap, so no world copies, hashes or sends it. A file declared as a `Grid2` and as a `Texture` is in it once as each, and so is a text file with characters past ASCII that's declared as a `string` and as a `List`. Where the pack is: beside the program as `.pack` on desktop, inside the self-contained page on the web, and in the APK on Android. A release or distribution build's pack is compressed as a file and read into the same memory, so a game's assets take the room on disk and in a download that their content needs, and the room in memory that they always did. Under `tide run`, tide watches the files assets name. Ordinary images and static models reload as data. [Skinned models and animation catalogs](#doc-game--animation) and assets their vertex defaults read require a matching game build because their values can become match state; the running game refuses a mismatched pack and keeps the current one. This also applies to asset dependencies of vertex defaults used by runtime skinned decoding. A C host of its own (`tide_add_game` with `HOST`) gets the pack as a C array, `tide_game_pack`, to hand `tide_assets_load`. ## Loading at runtime [Skinned models](#doc-game--animation) import as `SkinnedMesh` from glTF, with checked animation and bone catalogs. They can also be loaded while playing with `SkinnedMesh.Decode(bytes)` or its optional contracted form; runtime decoding accepts self-contained GLB bytes and fails with `IOError.InvalidData` for malformed data or unmet requirements. Two things bring bytes in while a game runs, both local, both failing with `IOError`: - `File.ReadAllBytes(path)` reads a file of this machine's (see [Files and directories](#doc-game--files)). - `await Web.Fetch(url)` fetches an `http://` or `https://` URL, in a task, so frames go on meanwhile. Bytes that every player should see go into the match through a [command](#doc-game--commands), and the match keeps them as its own state, which the netcode sends like any other, to those in the match and to whoever joins. ## Decoding a PNG `grid.Decode(bytes)` reads a PNG into a `Grid2` field of a component, singleton or scene, sizing the grid as the image is and writing every pixel. It fails with `IOError.InvalidData` for bytes that aren't a PNG, or are wrong anywhere, and then the grid is as it was. Bytes can come from anywhere, so a small file can't ask for much. A picture of more than 4096 × 4096 pixels (16,777,216) is `InvalidData` before anything is made for it, whatever its shape; at that size its cells are 256 MiB of the match. So is a file whose compressed data goes on for more than 1 MiB past its last row. These limits are the engine's, the same for every game, so every machine in a match refuses the same files. A picture refused for one says so on each machine's log, naming the limit: `tide: grid.Decode refused a PNG: it's 5000 by 5000 pixels, 25,000,000 in all, more than the 16,777,216 grid.Decode takes (TIDE_GRID_DECODE_MAX_PIXELS)`. Build-time imports past a limit are errors that name it the same way. It's pure, so it runs in match code as well as local code: a handler that decodes gives every machine the same pixels, bit for bit, because the engine's own reader does the decoding, with no system library in the way. The grid then draws as a texture like any `Grid2` (see [Meshes and textures](#doc-game--meshes-and-textures--textures)). A player's own picture, decoded for this machine alone: ```csharp local singleton Picker { string path; bool load; Grid2 preview; string message; } view Pick(mut Picker picker) { if (!picker.load) return; picker.load = false; var bytes = File.ReadAllBytes(picker.path) ?? []; if (picker.preview.Decode(bytes) is IOError error) picker.message = "Not a PNG: " + error; else picker.message = "Loaded " + picker.preview.size.x + " by " + picker.preview.size.y; } ``` In the match, the handler of a command decodes, and every machine gets the same pixels: ```csharp singleton Arena { Grid2 background; PlayerID host; } command SetBackground { List png; } command(SetBackground value, PlayerID sender) Apply(mut Arena arena) { if (sender != arena.host) return; arena.background.Decode(value.png)!; } ``` A command's `List` goes to the server and on to every player, one that doesn't fit a datagram in chunks, so a few megabytes is fine; see [Commands](#doc-game--commands). Every kind of PNG decodes: gray, color, with a palette, with or without alpha, 1 to 16 bits a sample, interlaced or not. A clear black pixel is a cell that's zero, which takes no memory. A picture past 16384 pixels a side, or past 4096 × 4096 in all, is `InvalidData`. Decoding runs where it's called, on the frame's or the tick's thread: a 4K picture takes a frame, so decode once, when the picture arrives, not every frame. ## Fetching a URL `await Web.Fetch(url)` gives the body as a `List`. It's local only, like `File`: views, local handlers, local tasks and the functions they call, never the match, input sampling, the GPU, a sort comparison or a parallel loop. The task waits while this machine fetches, and the bytes arrive in a frame to come. | Result | When | | --- | --- | | `IOError.NotFound` | The server answered 404. | | `IOError.InvalidPath` | The URL doesn't start with `http://` or `https://`. | | `IOError.Failed` | Anything else: no connection, a certificate the system doesn't trust, another status, a body over 64 MiB, more than 5 redirects, or on the web a server whose CORS refuses the page. | ```csharp local singleton Download { string status; Grid2 preview; } async void Fetch(string url, mut Download download) { download.status = "fetching"; if (await Web.Fetch(url) is IOError error) { download.status = "failed: " + error; return; } download.status = "fetched"; } ``` Big media is better fetched by each machine than sent through the match: what goes through the match goes player to server to everyone, so a host uploads it once per player. Keep a URL in the match and let each machine fetch and decode. --- Source: https://tide-engine.dev/game/build-code.md Make and process Tide assets and constants with code that runs while the game builds: outline an image, bake a curve, generate a mesh, its levels of detail or a sound. # Build code Build code is Tide code that runs while the game builds. It makes an [asset](#doc-game--assets) or a constant: an image with an outline drawn on it, a table of numbers, a mesh, its levels of detail, a sound. What it made goes into the build as a file's contents do, so every machine has the same value and the game spends no time on it while it runs. Build code runs through the installed tools, including when building a web game with `tide run --web`. The browser playground cannot run its native build program. An asset's value is either its file's path or a call of code that makes it. That code is ordinary Tide: functions that return the value. ```csharp void Outline(mut Grid2 image, Color color) { for (int y = 0; y < image.size.y; y++) { image[int2(0, y)] = color; image[int2(image.size.x - 1, y)] = color; } } Grid2 Outlined(Grid2 source, Color color) { mut Grid2 image = source.Copy(); Outline(image, color); return image; } asset Grid2 heroSource = "art/hero.png"; asset Texture hero = Outlined(heroSource, Color.black); ``` `heroSource` is the file's pixels, and `hero` is the texture the game draws: the outlined copy. Functions that return and change grids are what any code can write (see [Grids in code](#doc-language--grids--grids-in-code)). ## What code makes An asset of these types can be made by code, which returns: | Asset | What its code returns | |---|---| | `string`, `List` | The text or the bytes | | `Grid2` | The grid, with a size: `Grid2(width, height)` | | `Texture` | Its pixels, a `Grid2`, which become the texture as a file's would | | `Mesh` | `Mesh(vertices, indices)`, or with [levels of detail](#doc-game--build-code--levels-of-detail) of its own | | `Clip` | A `ClipData`: its `rate`, its `channels` (1 or 2) and its `samples`, interleaved | | `ClipData` | The same, kept as data the game reads | Code can make an asset from nothing: ```csharp Grid2 Checker(int size) { mut Grid2 image = Grid2(size, size); for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { if ((x / 8 + y / 8) % 2 == 0) image[int2(x, y)] = Color.white; } } return image; } ClipData Beep() { mut ClipData beep = ClipData { rate = 48000, channels = 1 }; for (int i = 0; i < 4800; i++) { beep.samples.Add(Math.Sin(i * 0.06) * 0.5); } return beep; } asset Texture board = Checker(64); asset Clip beep = Beep(); ``` An image must have a size, and every pixel and sample must be a number, not NaN or infinity. A mesh's triangles must name vertices it has. ## Files code reads A file that code changes is declared as the data the code reads: an image as a `Grid2`, a sound as a `ClipData`, a mesh as a `Mesh`, text as a `string`. The asset code makes from it has a name of its own. ```csharp asset ClipData stepSource = "sfx/step.wav"; asset Clip step = Quieter(stepSource, 0.5); ClipData Quieter(ClipData source, float scale) { mut ClipData quiet = source; for (int i = 0; i < quiet.samples.count; i++) { quiet.samples[i] *= scale; } return quiet; } ``` Code can read other assets and what other code made: an asset whose code reads another asset made by code is made after it. A game built without what nothing reads (`--strip-unused-assets`, as release builds are) leaves out a file only build code reads. ## Constants A constant whose value calls a function is made by build code too: ```csharp const List CURVE = Curve(64); const float SCALE = Twice(0.25); List Curve(int count) { mut List curve = []; for (int i = 0; i < count; i++) { curve.Add(Math.Sin(i * 0.1)); } return curve; } float Twice(float x) { return x * 2; } ``` A constant build code makes can be an array or a list of plain values (numbers, vectors, colors and structs of those) as well as what any constant can be: `const int[16] SQUARES = Squares();`. A list can be as long as you like, where one [written out](#doc-language--basics--tables) holds 4096 values at the most. Code and field defaults read it. A `case` label, a bound, a setting or another constant can't, as its value isn't known until the game builds, and neither can a frag or a vert yet; build code that makes another constant can (`const float FIRST = Head(CURVE);`). ## Build functions Build code can call any function that doesn't need a running game. `build` marks a function that only runs while the game builds: anything but build code calling it is an error, and its body is checked as build code where it's written. It follows the same rules as any other code. Build code runs before there's a game. It can't use a world (queries, `Spawn`, `Send`), `Devices`, drawing, audio, files beyond the assets it names, tasks, or the match's random numbers. `Math.Hash`, or a `Random` the code makes with a seed, gives it random numbers. It can't call [C](#doc-c--functions) yet either. The error points at the asset, constant or build function, with a note at the function that does it. ## Levels of detail A mesh can have levels of detail of its own instead of `[LOD]`'s: `Mesh(vertices, indices, levels)`. Each `MeshLevel` is triangles of the mesh's own vertices, and its error: how far that level's surface is from the full mesh's, in the mesh's units. Draws pick among them just as they pick `[LOD]` levels. ```csharp asset Mesh rockSource = "art/rock.glb"; asset Mesh rock = Leveled(rockSource); build Mesh Leveled(Mesh source) { mut List levels = []; levels.Add(MeshLevel { indices = Simplify(source, 0.5), error = 0.02 }); levels.Add(MeshLevel { indices = Simplify(source, 0.1), error = 0.2 }); return Mesh(source.vertices, source.indices, levels); } ``` A mesh has at most 7 levels after the full one, each error at least the one before it. An asset can have `[LOD]` or levels from its code, not both. Only build code makes a mesh with levels of its own; a mesh made as the game runs gets its levels from the draw's `lod:` (see [Levels of detail](#doc-game--assets--levels-of-detail)). ## How it runs tidec turns the game's build code into a small program, compiles it with the engine's sources, and runs it on the machine that builds, whatever the game is built for. `tide build` and `tide run` do this with the compiler they build the game with. What it made is kept in the game's `.tide/`, by everything that made it: the code, what it calls, the types it uses and the files it reads. A build where nothing of that changed runs no build code. Under `tide run`, saving a file that build code reads makes it again. Build code that runs for more than ten minutes is stopped, and the build fails. What it logs with `Debug.Log` shows as the game builds. The details, and which choices are still provisional, are in the [specification](https://tide-engine.dev/spec.md#build-code). --- Source: https://tide-engine.dev/game/scenes.md Author rooted scenes and prefabs, choose a startup scene, load and unload levels, and manage scene ownership and multiple instances. # Scenes A scene is a group of entities that load and unload together: a menu, a level, an arena. Several scenes can be loaded at once, and several copies of the same one. ```csharp scene Arena { int size = 20; } ``` A loaded scene is an entity like any other. The declaration is its component, and its fields are the scene's state, so a system that takes `Arena` runs once per loaded arena. ## Systems for one scene's entities `with scene Arena` runs a system, a view or an event handler only for the entities of a loaded arena; `without scene Arena`, only for the others: ```csharp system Spinning(Spin spin, mut Transform transform, Time time, with scene Arena) { transform.localRotation = Math.Mul(quaternion.Euler(0, spin.speed * time.dt, 0), transform.localRotation); } ``` An entity is in the scene it was spawned into: the scene of the entity the code that spawned it runs for. A loaded scene's own entity is one of its entities too. `with Arena`, without `scene`, still takes that entity alone, as it does for any component, so `event(Spawned) Setup(with Arena)` runs once per loaded arena. A scene filter on its own runs for every entity of the scene. For an empty scene, use `scene Arena;` as shorthand for `scene Arena { }`. The same works for local scenes: `local scene Main;`. Both forms are complete declarations, and braces remain valid. ## Authored prefabs An authored `.tprefab` file describes a reusable rooted entity tree. The same tree can be spawned as an entity or loaded as a scene: ```csharp // Enemy.tprefab prefab Enemy { Transform; Health { value = 100 }; Target { weapon = Weapon }; entity Weapon { Transform { localPosition = float3(0, 1, 0) }; } } ``` Declare `Health` and `Target` in ordinary `.tide` code. A reference field can use `[SceneRequired] Entity weapon;` to require a named entity in authored prefabs. The compiler checks unused prefabs too; missing components, fields, references and recursive inclusion are errors. Ordinary code-driven construction can still leave these fields unset and initialize them later. ```csharp var enemy = Spawn(Enemy, Health { value = 50 }); var level = Scene.Load(Level, LevelSettings { difficulty = 2 }); Scene.Unload(level); ``` Settings are normal root components. Component literals override only the fields they name and can add root components. An existing component value replaces the whole root component. A bare component argument resets that component to its declared defaults. A match scene uses the ordinary root `Visibility` component: `Scene.Load(Level, Visibility { group = group })`. All entities, component values, references and parenting exist before the instance's `Spawned` handlers run, root-first. Nested children move with their parents and are destroyed with them. `entity Weapon : Pistol { ... }` reuses another named prefab; fields in its block override that prefab's root. Paths such as `Weapon.Muzzle` resolve through nested instances, and omitted values use the authored prefab and component defaults. Override an inherited descendant by matching its existing name with another `entity` block. This changes values on this instance without changing Pistol: ```csharp entity Weapon : Pistol { entity Muzzle { Transform { localPosition = float3(0, 0, 0.8) }; } } ``` Inside an inherited descendant, only field values of existing components can change. Match further `entity` blocks to reach deeper descendants. These blocks cannot add, remove or replace components or children, or name another base prefab. A nested instance's root can still add components and new named children. Reference paths keep the scope of the prefab whose source wrote them; `this` means the entity containing the value. Overrides do not create extra entities. `local Spawn(Enemy)` creates local entities, and `Scene.Load` from local code loads into the local world. References must use the corresponding `Entity` or `LocalEntity` type. Prefab names are factories, so filters use explicit root components. The initial limits are 1024 entities per instance and 128 nesting levels. ## Startup scene An authored scene can start the game directly. In an ordinary `.tide` file, name its declaration in project settings: ```csharp settings { startScene = Levels.Start; } ``` `startScene` takes a prefab or scene name, including its namespace when needed, not a string or a call. A prefab starts as a match scene with its own root, authored values and complete tree. Normal `Spawned` handlers, systems, views, camera and input run; no handwritten `Main` is needed. An ordinary scene can be selected too, including a local scene for a menu outside a match. For one run or build, override the project selection: ```sh tide run . --scene Levels.Start --stats tide build . --scene Levels.Start ``` This leaves project settings and any existing `Main` declaration unchanged. ## Main Without a selected startup scene, the game starts in the scene called `Main`, and there must be exactly one. It sets up the first scene, not the game loop: the engine runs the tick. ```csharp scene Main; event(Spawned) Setup(with Main) { Spawn(Transform { localScale = float3(1, 1, 1) }, Player); } ``` A match `Main`, like this one, starts a single-player match with it right away. A local `Main` starts the program outside any match, usually in a menu, which starts one later (see [Local state](#doc-game--local-state) and [Matches](#doc-multiplayer--matches)). ## Loading and unloading ```csharp var arena = Scene.Load(Arena { size = 30 }); Scene.Unload(arena); ``` `Scene.Load` loads a scene into the current world and returns its entity. `Scene.Unload` unloads it, destroying every entity it owns, and so does `Destroy` on a scene's entity. `Scene.Unload` of an entity that isn't a scene does nothing. `Spawn` of a scene is an error that says to use `Scene.Load`. Additional component arguments attach to the loaded root, for example `Scene.Load(Arena { size = 30 }, Visibility { group = group })`. They use the same component names, literals and existing values as `Spawn` and are present before `Spawned` handlers run. Local scenes can also take root components, using local placement. Loading and unloading happen at the end of the tick, like `Spawn` and `Destroy`. A scene can do heavy preparation before its `Spawned` handlers run, as described below. Its entities get `Destroyed` when it unloads. ## Switching scenes To leave one scene for another, switch: ```csharp Scene.Switch(Arena { size = 30 }); ``` `Scene.Switch` unloads every scene loaded in the world and loads this one, returning its entity. It takes what `Scene.Load` takes, root components included, and needs no handle to the scene being left, so any code can call it: a system of the scene, or a button in a view that runs for no entity. A match scene switches the match's scenes and a local scene this machine's. Entities in no scene stay. It happens at the end of the tick, in its turn: scenes loaded earlier in the same tick go too, and scenes loaded after it stay. The world is never left without a scene, so the startup scene doesn't load in between. Functions and methods can load, switch and unload scenes, for the code that calls them. A function that loads a match scene is for match code to call, and one that loads a local scene is for views and local handlers: ```csharp local scene Menu; local scene Lobby { int seats; } void OpenLobby(int seats) { Scene.Switch(Lobby { seats = seats }); } view MenuButtons(with Menu) { if (GUILayout.Button("Play")) OpenLobby(4); } ``` A prefab belongs to neither side. In a function it loads into the match; write `local Scene.Load(MenuPrefab)` or `local Scene.Switch(MenuPrefab)` to load it on this machine instead. ### From a menu into a match A menu is usually a local scene, and the game a match that `Session.Start` or `Session.Join` puts this machine in. Unload the menu as the match starts and it stays gone for the whole match: ```csharp local scene Main; view Menu(with Main) { if (GUILayout.Button("Play")) { Session.Start(Arena); Scene.Unload(this); } } ``` With a local scene for the match's own interface, switch to it instead: `Scene.Switch(Hud)`. The startup scene loads again by itself once this machine is offline with no local scene loaded: when the match ends, the player leaves, or joining fails. Nothing has to bring the menu back. The startup scene is also the fallback: the selected scene or prefab, or `Main` without a selection. When the last scene of its world unloads, the fallback loads again at the end of that tick, initialized as at startup. A match startup returns in the match, and a local one in local state, while this machine is offline: in a match, or with one asked for, it waits. Unloading one scene and loading another in the same tick never brings it back, and entities in no scene don't count. It returns at most once a tick: one that unloads itself as it loads leaves the world without a scene until the next. A match can't load a local startup scene. When startup is local, a match whose last scene unloads ends there. Every machine in it goes back offline and gets `Disconnected` with the reason `Ended` (see [Matches](#doc-multiplayer--matches)). Local state carries on as it was. ```csharp // Sets up each arena. The floor joins that arena. event(Spawned) SetupArena(Arena arena) { Spawn(Floor { size = arena.size }); } system Collapse(Arena arena) { if (arena.size <= 0) Scene.Unload(this); } ``` Each button below loads a `Room`, or unloads the one that's there. A `Spawned` handler furnishes a room with four balls as it loads. They're spawned for the room, so they join it, and unloading it takes them with it. **Rooms that load and unload** ([Run example](https://tide-engine.dev/examples/scenes/?stats)) ```tide settings { title = "Scenes"; tickRate = 30; maxPlayers = 1; } scene Main { } // A scene's fields are its state. Each loaded Room is an entity with a Room. scene Room { int slot; } component Ball { float2 position; float2 velocity; int slot; } singleton Slots { List rooms = [default, default, default]; } command Toggle { int slot; } float2 Center(int slot) { return float2((slot - 1) * 1.3, 0); } command(Toggle toggle, PlayerID sender) LoadOrUnload(mut Slots slots) { if (toggle.slot < 0 || toggle.slot > 2) return; if (slots.rooms[toggle.slot] == default) slots.rooms[toggle.slot] = Scene.Load(Room { slot = toggle.slot }); else { // Unloading destroys the room and every entity spawned into it. Scene.Unload(slots.rooms[toggle.slot]); slots.rooms[toggle.slot] = default; } } // Sets each room up as it loads. These spawns join that room. event(Spawned) Furnish(Room room) { for (var i = 0; i < 4; i++) { Spawn(Ball { position = Center(room.slot), slot = room.slot, velocity = float2(Math.Cos(i * 1.9 + room.slot), Math.Sin(i * 1.9 + room.slot)) * 0.9 }); } } system Bounce(mut Ball ball, Time time) { ball.position += ball.velocity * time.dt; var offset = ball.position - Center(ball.slot); if (Math.Abs(offset.x) > 0.4) ball.velocity.x = -Math.Sign(offset.x) * Math.Abs(ball.velocity.x); if (Math.Abs(offset.y) > 1) ball.velocity.y = -Math.Sign(offset.y) * Math.Abs(ball.velocity.y); } local singleton Count { int balls; } view Buttons(Slots slots, mut Count count) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, 0.2), 2.2); count.balls = 0; GUI.SetTheme(GUITheme { radius = 6 }); for (var slot = 0; slot < 3; slot++) { var loaded = slots.rooms[slot] != default; Draw.WireRoundRect(Center(slot), float2(1.1, 2.3), 0.1, 0.03, loaded ? Color(0.98, 0.75, 0.14) : Color(0.24, 0.25, 0.27)); var corner = Draw.WorldToScreen(Center(slot) + float2(-0.55, -1.3)); var width = Draw.WorldToScreen(Center(slot) + float2(0.55, 0)).x - corner.x; if (GUI.Button(Rect(corner.x, corner.y, width, 32), loaded ? "Unload" : "Load")) Send(Toggle { slot = slot }); } } view Balls(Ball ball, mut Count count) { Draw.Circle(ball.position, 0.1, Color(0.18, 0.83, 0.75)); count.balls += 1; } view Total(Count count) { Draw.SetScreen(); Draw.Text($"{count.balls} balls, in the rooms that are loaded", float2(16, 14), 16, Color.white); } ``` ## Which scene owns what A spawn joins the scene of the entity the code is running for. In a handler, that's the entity the event was sent to, so the floor above joins the arena it was spawned for. A spawn into a scene that's unloaded by the spawn's turn is never made, like the loot an enemy drops while its arena unloads. Code that isn't running for an entity, like a system that runs once per tick, spawns into no scene, and those entities live until they're destroyed. A scene itself is never owned: it lives until it's unloaded, whoever loaded it. Loaded scenes share their world: the same systems, singletons and `Time`. ## Heavy preparation Put expensive deterministic setup inside a scene's `prepare(...)` block: ```csharp singleton Geography { int completed; int total; } scene Campaign { int seed = 42; prepare(mut Geography geography) { geography.total = 3; GenerateTerrain(seed, geography); geography.completed = 1; GenerateRoads(seed, geography); geography.completed = 2; GenerateSettlements(seed, geography); geography.completed = 3; } } ``` The generation functions above are game code. A scene has at most one block, and parentheses are required even with no dependencies: `prepare() { ... }`. Scene fields and methods are available directly; `this` is the scene's entity. Other data uses the same explicit parameters as match handlers. A component parameter belongs to the root and must be supplied to `Scene.Load`; singletons and queries keep their ordinary meaning. Preparation runs for the initial scene and for later loads, before `Spawned`. Its spawns belong to the scene and exist before the scene's `Spawned` handlers. The match stops advancing ticks while this machine prepares; `Time` does not advance. On hosts with background workers, views and networking keep running. Views can read consistent progress snapshots between completed top-level preparation statements. Progress fields are ordinary game data: the engine doesn't infer a percentage, and a long helper or loop need not publish an intermediate update. ```csharp bool loading = !Scene.IsPrepared(campaign); bool playerReady = Scene.IsPrepared(campaign, player); ``` The one-argument form checks completion on this machine. The player form reads readiness acknowledged through the server's ordered commands, so match code can decide when to admit a player to gameplay. Missing, unloaded and non-scene handles return false. Scenes without a block finish immediately; their players still acknowledge readiness. Local scenes support the one-argument form and use ordinary `Spawned` setup. Read match readiness from match code and views; synchronous local event handlers operate on their recorded event state. Every peer with the complete match independently prepares the same committed state. The server resumes when its own preparation finishes. Slower peers catch up from buffered ticks, using normal state recovery if needed. Waiting for players, deadlines and kicks are game policy. In visibility-enabled matches, clients receive the permitted prepared result from the server, because they may lack private generation inputs. Preparation is deterministic match code. It can call synchronous helpers, change declared match data, query and spawn. It cannot access local state, await, start async tasks, or load another scene, including through helpers and sent events. Start follow-up work in `Spawned`. Trusted C retains its ordinary determinism and thread-safety responsibilities. Heavy work starts only for committed loads. Completed preparation becomes the baseline for subsequent prediction and rollback. Leaving the match discards unfinished work. Hosts without a background provider execute preparation synchronously; sharded matches currently reject preparation blocks. ## Private scenes Scenes are public by default. Give a match scene root an ordinary `Visibility` component to restrict the scene and every entity it owns: ```csharp scene Hand { PlayerID player; } event(PlayerJoined joined) DealIn() { var group = Visibility.CreateGroup(Audience.Only(joined.player)); Scene.Load(Hand { player = joined.player }, Visibility { group = group }); } ``` Use `Visibility.Set(group, audience)` to replace the scene's audience. The same group can serve several scenes and ordinary entities. Audience changes are match state, so only match code changes them. Local scenes belong to this machine and do not take `Visibility`. A scene whose group has `Audience.None` stays on the server. Including a player supplies its current permitted state; excluding one conceals it. An entity's group can restrict the scene audience further, and a component's policy can restrict the entity audience further. These three scopes intersect; an inner scope cannot broaden an outer one. See [State visibility](#doc-game--visibility) for shared groups and component policies. The server simulates the complete match and corrects clients where hidden simulation affects their permitted state. --- Source: https://tide-engine.dev/game/visibility.md Control Tide client state with scene, entity and whole-component visibility, shared audience groups, partial simulation and local availability events. # State visibility Visibility decides which match scenes, entities and components a player's machine receives. The server still runs the full match. A client predicts with the state it is allowed to have, and authoritative corrections supply consequences that its partial simulation could not reproduce. The server's own machine is the exception: its player sees the whole match, as the server does, so that machine runs each tick once. Its views and local handlers see hidden entities and components too, and hear every event the match sends. Visibility keeps state from the other machines. The API names below are provisional. Visibility applies to entities and whole components. To hide a card's face while keeping its back public, put the face in a separate component; individual fields do not have visibility rules. ## Share an audience An `Audience` is a set of players. `Audience.All` includes everyone and `Audience.None` includes nobody. `Audience.Only(player)` selects one player; `Audience.From(players)` takes a `List`. An audience value has `Add(player)`, `Remove(player)` and `Contains(player)`, and two audiences are equal (`==`) when they have the same players. A `VisibilityGroup` gives many entities one live audience: ```csharp singleton Region { VisibilityGroup group; } component Block { int kind; } scene Main { } event(Spawned) Setup(mut Region region, with Main) { region.group = Visibility.CreateGroup(Audience.None); Spawn(Block { kind = 1 }, Visibility { group = region.group }); Spawn(Block { kind = 2 }, Visibility { group = region.group }); } event(PlayerJoined joined) Admit(Region region) { Visibility.Set(region.group, Audience.Only(joined.player)); } ``` `Visibility.Set(group, audience)` replaces the audience for every entity using that group. Build an audience with all interested players before setting it. Changing an `Audience` variable after `CreateGroup` or `Set` does not change the group until another `Set` call. For a voxel world, make each chunk an entity with a group of its own, and update the group's audience as players approach or leave. A player's machine is then sent the chunks it walks into and nothing of the rest; chunks nobody is near can be saved and destroyed ([Saving the match](#doc-game--files--saving-the-match)). For distant players on a map, give each player entity its own group and compute the observers in match code. The engine supplies the mechanism; the game chooses distances, teams, occlusion and update frequency. An entity without `Visibility` is public, subject to its enclosing scene. A default `Visibility` uses an all-player group. `Visibility.DestroyGroup(group)` makes existing references to that group see nobody; a later group does not reuse the stale handle. ## Restrict a scene Scenes use the same groups. Put `Visibility` on the loaded root: ```csharp var group = Visibility.CreateGroup(Audience.Only(player)); var hand = Scene.Load(Hand { player = player }, Visibility { group = group }); ``` The root's group limits every entity owned by that scene, including entities spawned later. `Visibility.Set(group, audience)` updates them together. Use `Audience.None` for a server-only scene, or share a group across multiple scenes and entities. Scene ownership still controls loading and unloading; destroying a group conceals its members without unloading them. ## Hide a component Keep public and private data in separate components: ```csharp component Card { int back; } component CardFace { int rank; int suit; } event(Spawned) ProtectFace(Owner owner, mut Visibility visibility, with CardFace) { visibility.Set(Audience.Only(owner.player)); } ``` The entity must carry `Visibility`. Set the restriction during construction, before initial state can be published; waiting for the next system tick can expose the initial component. Update the policy when the holder changes. `visibility.Set(audience)` restricts the whole component. It also accepts a shared group: `visibility.Set(handGroup)`. `visibility.Reset()` removes that override, so the component follows the entity again. The effective audience is the intersection of the scene root's group, the entity's group and the component's restriction. An entity or component cannot broaden its enclosing scope. Ordinary transform parenting does not inherit visibility. A component outside a recipient's audience is absent on that client, including from queries and `Has()`; `without CardFace` can therefore match there. For poker, keep the public card back on the entity and restrict `CardFace` to the holder. Put an undealt deck in an audience of nobody, or a private scene with no members. Membership, group contents and component overrides are server policy; clients receive their permitted state rather than the policy's private membership data. `Time.seed` is public, and default `Random` state derives from it. Hiding card faces alone does not make a shuffle derived from that public seed unpredictable. A secret shuffle needs a private seed supplied authoritatively, with its RNG state and undealt deck kept restricted. ## Spatial parents A public child can remain visible while its transform parent or the parent's `Transform` is hidden. The projected hierarchy cuts that private link. Where the visible subtree contains a permitted `Transform`, an internal placement anchor preserves its composed placement, including rotated nonuniform scales. The child's local transform values stay unchanged; no private parent entity or component payload is copied. That derived placement is part of the permitted spatial state. A visible entity with no permitted `Transform` in its visible subtree does not receive an anchor just because its parent has one. Calling `world.LocalToWorld` on such an entity in a partial client can omit hidden influence. `world.Parent` reflects the projected links, so a concealed parent can appear null. Choose visibility for spatial state according to what players may infer from visible children. ## Availability and actual lifetime Use `local event(Shown)` to initialize presentation when an entity or a handler's required components become available. It runs for arrivals, reveals and genuine spawns. `local event(Hidden)` removes presentation when that availability ends, and reads the last permitted state. The same forms accept `verified Shown` and `verified Hidden`. `local event(Spawned)` and `local event(Destroyed)` describe actual match lifetime. Joining, revealing an existing entity or receiving a repair does not fabricate either event. A concealed entity's later destruction does not announce its death to a recipient who could not see it at destruction. [`Forgotten`](#doc-game--local-state--letting-go) remains the cleanup hook for local fields. On the server's own machine, which sees the whole match, an entity only leaves as the match destroys it, so its handlers hear `Destroyed` rather than `Hidden` while its player keeps up with the server. Where that player takes the server's world whole (after a new build takes over, or once it fell behind), an entity that went in the ticks it skipped is `Hidden` there, and one that came is `Shown` without `Spawned`, as for a joining player. Another player's machine hears `Hidden` for an entity hidden from it, even when the match destroys it in the same tick, since it couldn't see it at its destruction. Its predicted handlers hear what its own run of a tick did, which can be the destruction of an entity the server hid in that tick; its `verified` handlers then hear `Hidden`. To let go of what local code keeps for an entity however it leaves a machine, use `Forgotten`, which every machine sends once. Each handler's component requirements determine its availability. A handler reading `Card` can remain active while a handler reading `CardFace` becomes hidden. A `Shown` handler should prepare resources; a true `Spawned` handler can play the effect for a new object. **Provisional delivery rule:** availability follows the endpoints delivered to local presentation. Changes inside one tick or between frames coalesce to their final availability, so adding, removing and adding a component before a frame cannot leave its presentation released. A correction that restores an entity or component runs `Shown` again; an unchanged replay does nothing. Predicted and verified handlers follow separate presentation endpoints, and their queries read the corresponding old or new endpoint. A local rebuild clears this history and prepares available objects again, so `Shown` initialization should reuse or replace existing resources safely. ## In a sharded world In a [sharded world](#doc-multiplayer--shards--visibility), a group means the same on every shard: an entity in it is shown to the same players on whichever shard has it, and each shard sends its own players only what they may see. The groups are kept with the first shard. Code on another shard that creates, changes or destroys a group waits on the border for them, and other shards see the change a tick or two later. ## Consequences across a visibility boundary The server may simulate a hidden object affecting a public one. The client receives the corrected public result; it does not need the hidden cause. Design public state to contain the consequences players need, such as damage, a revealed projectile or a public combat log. Custom `local event(...)` and `local event(verified ...)` handlers currently hear events produced by the client's permitted simulation. They are not a general authoritative server-to-audience event channel. A hidden system's custom event is not automatically forwarded to other players. Choose public fields and input payloads deliberately, and decide what each command handler publishes. Commands execute only on the authoritative server in this path; clients receive permitted results. Projected clients also cannot become a new host: host migration needs a trusted complete-state handover, which is not currently implemented. Match task continuations and opaque `Resident` state stay on the authoritative server in a visibility-enabled match. They are not copied into projected clients. Publish the state needed for presentation and prediction in ordinary permitted components. Public match singletons remain public, so keep per-entity secrets in components or private scenes. The physics packages keep their worlds in `[Native]` fields, the library's own state: Box2D's `Physics.image`, Box3D's `Resident`, both packages' handles, collider and rewind-history lists. A client doesn't receive those. Its world arrives with them at zero, as on a shard an entity comes to, and the package makes its physics world again from the bodies the client has. A hidden body is absent from that world, so what it does to visible ones comes with the server's corrections. Rewind history starts again on a client after each correction, so a client's own `Physics.Rewind` can fail where the server's succeeds: hits are decided on the server. On a client, `Visibility.CreateGroup` can't number a group: the server does. What a client's own tick puts in a group without the client's player stays out of its projection, as it's out of the server's projection for it; what it puts in one with its player is visible to it. `Visibility.Set` does nothing there, so something coming into or going out of sight always arrives as a correction. See [Scenes](#doc-game--scenes--private-scenes) for scene ownership and audiences and [Networking](#doc-multiplayer--networking--who-sees-what) for verification and corrections. --- Source: https://tide-engine.dev/game/endless-worlds.md Build an endless world of blocks in Tide: chunks as entities with grids, each player sent only the chunks near them, dimensions as scenes, the server's store for what nobody is near, read off the tick's thread and listed by prefix, chunk faces meshed across their edges, and far ground drawn from the seed with far regions of what players built. # Endless worlds A world of blocks that goes on as far as players walk, in several dimensions, played together: more than any machine holds at once, and more than any player should be sent. Tide has no world type for it. It's made of what every game has, put together as this page shows: entities, grids, [State visibility](#doc-game--visibility), [Scenes](#doc-game--scenes) and [the server's store](#doc-game--files--saving-the-match). `bench/voxels` in the engine's repository is such a game, with bots that fly, dig and build across it, and a version people play. The code below is shortened from it. The names of the store's calls and of visibility are provisional. ## Chunks are entities A chunk is an entity with a grid of its own, found by its place: ```csharp component Chunk { int3 at; // In chunks int dimension; Grid3 blocks = Grid3(16, 16, 16); Stage stage; // Asked for, missing from the store, or made int edits; // Changes players made } ``` An entity is what the engine already serves one at a time: each player is sent only the entities they may have, `Destroy` unloads one, an event can go to one, and a sharded world splits its entities by place. One grid for a whole world would have none of that. A chunk is found by its place with an indexed loop: the loop's guard is one key of the place's three numbers and the dimension, and the loop visits only the chunks there ([Systems](#doc-game--systems)). ```csharp Block At(int dimension, int3 cell, query (Chunk chunk) chunks) { var at = int3(cell.x >> 4, cell.y >> 4, cell.z >> 4); mut var found = Block.Air; indexed foreach (var row in chunks) { if (row.chunk.at.x != at.x || row.chunk.at.y != at.y || row.chunk.at.z != at.z) continue; if (row.chunk.dimension == dimension) found = row.chunk.blocks[cell.x & 15, cell.y & 15, cell.z & 15]; } return found; } ``` ## Dimensions are scenes Each dimension is a scene, loaded once, with a seed of its own. A chunk spawned by code that runs for the dimension's entity is in that scene, so unloading a dimension destroys its chunks. ```csharp scene Dimension { int number; int seed; } ``` ## Who has which chunks Each chunk has a visibility group of its own, whose audience is the players near it. A player is sent the chunks they come near and nothing of the rest, and a player's machine drops a chunk once its group no longer has them. The code that decides it is the server's alone. It runs for components no player may have, so a player's machine runs none of it and has nothing of it to get wrong: ```csharp // On each dimension's entity: who is where, and its chunks by their places component Streamer { Map watching; Map chunks; List making; // Chunks asked for and not yet made, in the order they were asked for Map asking; // Players whose box isn't all asked for yet: how far through it they are int asked; // Chunks spawned this tick } // On each chunk: who wants it component Seen { VisibilityGroup group; Audience audience; bool shown; // Made, and its group has its audience bool dear; // It has ground in it: what making it costs bool ready; // The store had nothing for it... bool go; // ...and it may be made this tick (Pace, below) int emptied; // The tick its last player left } ``` Both are restricted to `Audience.None` where they're added (`visibility.Set(Audience.None)`). A player's moves tell their dimension which chunk they're in, and its handler adds them to the chunks their box of chunks took in and removes them from those it left. A chunk nobody has yet is spawned with an audience of nobody, and the group's audience is set once its blocks are made, so no player ever has a chunk that isn't. The box is asked for nearest first: a ring of chunks around the player's own at a time, the player's own height before the ones above and below. The store answers in the order it's asked, so what a player stands in and looks at is there before the edge of their view; and around each ring, each chunk beside the one before it, because a player is sent new entities in the order they were spawned and chunks side by side are alike, which makes what's sent smaller. A whole box isn't spawned in one tick. A view of 96 cells each way is 845 chunks; at twice that it's 3,125 and at three times 6,845, and a tick that spawns them all, each with a group and a load asked of the store, is as long as they are many (9 ms for 3,125). The handler spawns up to an allowance of new chunks for its dimension each tick and remembers how far through the box it got; the player's move in the next tick (which says where they are every tick) goes on from there: ```csharp event(Want want) Watch(mut Streamer streamer, Worlds worlds, Time time, mut World world) { var known = streamer.watching.TryGet(want.player, out var from); var going = streamer.asking.TryGet(want.player, out var gone); var moved = !(known && Same(from, want.to)); if (!moved && !going) return; // Where they were, with their whole box asked for // ...moved: the chunks the old box had and the new one hasn't lose the player mut var place = 0; // Places of the box gone through, nearest first mut var full = false; // for each place of the box, nearest first, while !full: // place++; if (place <= (moved ? 0 : gone)) continue; // a chunk that's there: the player joins its audience, while the tick's joins are under their allowance // none, and streamer.asked < worlds.ask: Spawn it, ask the store for it, streamer.asked += 1 // none, and the tick's allowance is spent: place--; full = true; if (full) streamer.asking[want.player] = place; else streamer.asking.Remove(want.player); streamer.watching[want.player] = want.to; } ``` The allowance costs a player nothing while it's more than the store answers in a tick (256): the box is asked for faster than it can be made, in the same order. `bench/voxels` spawns 1,024 a tick, so the default view is still asked for at once. Chunks that are already there cost a tick something too: each one a player joins or leaves is its `Seen` and its group's audience changed, and the world's check of that change, about a microsecond each. A player who comes where others are joins a whole view of them in one tick, and one who goes leaves one; several players coming or going in one tick are several views. So joins have an allowance of their own, and so have leaves, eight times the spawns' in `bench/voxels` (8,192 a tick for a dimension), the box's places gone through the same way. A box left goes in a list (`Streamer.leaving`, the player and the chunk they were in), and each tick takes the allowance's worth of its chunks from the oldest box first, passing over those inside the box the player has now, so one who comes back keeps what they came back to: ```csharp void Depart(mut Streamer streamer, mut World world, Worlds worlds, int tick) { // for each box in streamer.leaving, oldest first, while the tick's leaves are under the allowance: // for each of its places from box.place on: the chunk there, if it's outside where the player is now // (streamer.watching) and has them, loses them // a box gone through leaves the list; one that isn't keeps its place } ``` The handler that sees the move runs it, and so does a system each tick, as a player who left the dimension sends it nothing more to go on by. What the game chooses here is the audience: a chunk is a leaving player's a few ticks longer than their box says, never a tick less than it, and a player who joins has the nearest of a box first. A player's view taken in or let go over two ticks costs that player a round trip: what they're sent of it is a second repair, which waits for the first to be acknowledged. With an allowance of four times the spawns' (4,096), a view at three times the default radius (6,845 chunks) went over two ticks, and with eight bots hopping the server's longest updates lost their handlers' share (6 to 9 ms), but a player hopping to where another is had all of their box 2 ticks later (40 for 38), and a bot's verified world was 69 ticks behind the server's at most, for 59. At 8,192 no lone view is split: the allowance holds the ticks in which several players come or go at once. The server finds its chunks in `Streamer.chunks`, not with a query: a spawn joins the tables only once its tick's changes are applied, so two players who come near one place in one tick would otherwise make two chunks there. `Spawn` gives the entity at once, but its components are there only once the tick's changes are applied: `world.Has(chunk)` is false for a chunk another player's coming spawned this tick, and what's set on it is lost. The handler stops there for the tick, as if its allowance were spent, and goes on from that place in the next, when the chunk takes the player. ## Making chunks on every core A system that fills each new chunk from its dimension's seed, and then shows it to the players waiting for it, runs across every core, in a game that hides state as in any other ([The schedule](#doc-game--schedule--splitting-across-threads)): ```csharp system Generate(mut Chunk chunk, mut Seen seen) { if (chunk.stage != Stage.Missing || !seen.go) return; // ...the chunk's blocks, from Math.Perlin of the seed chunk.stage = Stage.Made; Visibility.Set(seen.group, seen.audience); } ``` Each chunk's blocks are its own, and the groups' audiences its rows set are set after them, in the chunks' order, as one thread would. Making or ending groups in the same system keeps it on one thread, so a game makes a chunk's group where it spawns the chunk. The chunks a tick makes go to every thread, wherever they are among the chunks: a system that starts with a test most of its entities fail (`if (...) return;`) hands out the ones that pass. A tick that made every chunk the store answered for would be as long as they are many, so the game says how much a tick makes (`seen.go` above): ```csharp // On each dimension's entity: the chunks the store had nothing for, in the order they were asked for, up to // `make` a tick by what each costs. One of air costs 1, one with ground in it (caves' noise, cell by cell) 10 system Pace(mut Streamer streamer, Worlds worlds, mut World world) { mut var left = worlds.make; mut var kept = 0; for (var i = 0; i < streamer.making.count; i++) { var chunk = streamer.making[i]; mut var seen = world.Get(chunk); if (seen.go || seen.shown) continue; // Made, or let be: off the line if (seen.ready && left > 0) // The store answered: nothing kept of it { left -= seen.dear ? 10 : 1; seen.go = true; world.Set(chunk, seen); continue; } streamer.making[kept] = chunk; // Still asked for, or over this tick's allowance kept++; } while (streamer.making.count > kept) streamer.making.RemoveAt(streamer.making.count - 1); } ``` `bench/voxels` makes 480 a tick: 48 chunks with ground, about 7 ms of one thread, 1.5 ms across twelve. ## Keeping what nobody is near A chunk is asked for from the store as it's spawned, and made from the dimension's seed only if the store has nothing: ```csharp var made = Spawn(Chunk { at = at, dimension = dimension.number }, visibility, Seen { group = group }); streamer.chunks[KeyOf(at)] = made; Storage.Load(SavedAs(dimension.number, at), made); event(Loaded loaded) Fill(mut Chunk chunk, mut Seen seen) { if (chunk.stage != Stage.Asked || loaded.failed) return; // Unreadable: asked again later, never made over if (loaded.found && Grid3.FromBytes(loaded.bytes) is Grid3 saved) { chunk.blocks = saved.Copy(); chunk.stage = Stage.Made; Visibility.Set(seen.group, seen.audience); return; } chunk.stage = Stage.Missing; // Made from the seed by a system } ``` A chunk nobody has had for a while goes. It's let go in an event, which runs after the tick's moves, so a player who came back to it in the same tick keeps it: ```csharp system Idle(Seen seen, Chunk chunk, Time time) { if (seen.audience == Audience.None && chunk.stage == Stage.Made && time.tick - seen.emptied >= LINGER) this.Send(Expire { }); } event(Expire) Drop(Seen seen, Chunk chunk) { if (seen.audience != Audience.None) return; if (chunk.edits > 0) Storage.Save(SavedAs(chunk.dimension, chunk.at), chunk.blocks.ToBytes()); Visibility.DestroyGroup(seen.group); this.Destroy(); } ``` `ToBytes` writes only a grid's chunks that have something in them, and runs of one block short: a chunk of air is a few bytes ([Grids as bytes](#doc-language--grids--grids-as-bytes)). A system that writes a chunk players changed into the store every while, as well as when it goes, keeps a server that stops from losing more than that while. A load whose answer never comes (the server stopped first) leaves the chunk waiting: ask again after a while, as `bench/voxels` does. A box a player left empties in one tick, so all of its chunks would go in one tick, a linger later: saved, forgotten and destroyed, 12 ms for 3,125 of them. Where the handler takes a player out of the box they left, `bench/voxels` gives each tick's allowance of the dimension's emptied chunks an `emptied` a tick later than the ones before (a tick and a count on the dimension's entity), so a box goes over as many ticks as it was asked for in. A border's row of chunks still goes together: spread by where each chunk is instead, every tick would have chunks going, and a tick in which entities come or go costs the server more than one in which none do. `Idle` writes nothing while it waits: `emptied` is a tick, not a counter. A system that counts in every chunk every tick changes every chunk every tick, and the server's checks cost what changes. The server reads and writes the chunks' files on a thread of their own, after the tick that asked: a player's first view of fresh ground asks for hundreds of chunks in one tick, and the tick doesn't wait for the disk. Their answers come over the next ticks, 256 a tick in a game that hides state (64 in one that doesn't, whose answers go to every player). What a dimension has saved can be listed, a page of keys at a time, for a map of where players built or to move a world's saves elsewhere: `Storage.List($"chunks/{dimension.number}/", this)` answers with a `Listed` event, and the next page is asked for after its last key ([Saving the match](#doc-game--files--saving-the-match)). Keys made of folders (`chunks//...`) keep a listing to the folder its prefix names. A match task can wait for the store instead of handling its events, which keeps a job of several steps in one place. A dimension's map of saved chunks, a page at a time: ```csharp async void Survey(mut Atlas atlas, int dimension) { mut var after = ""; mut var going = true; while (going) { var page = await Storage.List($"chunks/{dimension}/", after); if (page is StorageKeys keys) { atlas.saved += keys.keys.count; going = keys.more; if (going) after = keys.keys[keys.keys.count - 1]; } else going = false; // The store couldn't be listed } } ``` The task goes on in the tick each answer is given to, the same on every machine, and what it waits for is kept in it: a task whose entity goes ends with it, its answer changing nothing, and a rewind asks again for what the rewound tasks wait for ([Waiting for the answer in a task](#doc-game--files--waiting-for-the-answer-in-a-task)). ## Drawing what's far A chunk's faces are made into a mesh by a `local worker`, off the frame, and kept in the chunk's `local` fields ([Local state](#doc-game--local-state), [Async and tasks](#doc-game--tasks)); they're made again when its blocks change. Meshes outside the view aren't drawn ([frustum culling](#doc-game--3d--frustum-culling)). ### Faces across a chunk's edges A worker reads only what it's handed. Given a chunk's own grid, everything past its edge reads as air, so every block on its edge has a face there: two faces between every pair of solid chunks, hidden and drawn all the same. Hand it the neighbours' grids too, and those faces aren't made: ```csharp local worker Built Faces(Grid3 blocks, Grid3 east, Grid3 west, Grid3 above, Grid3 below, Grid3 north, Grid3 south) { // ...for each block, the one beside it, in this chunk or across its edge var right = x < 15 ? blocks[int3(x + 1, y, z)] : east[int3(0, y, z)]; if (Shows(block, right)) Face(vertices, indices, ...); // ...and each of the chunk's own sides as one number, for its neighbours } async void Remesh(mut Chunk chunk, Grid3 east, Grid3 west, Grid3 above, Grid3 below, Grid3 north, Grid3 south) { var built = await Faces(chunk.blocks, east, west, above, below, north, south); chunk.mesh = Mesh(built.vertices, built.indices); } // The blocks of the chunk at a place, or no grid's, all air Grid3 Near(query (Chunk other) chunks, int3 at, int dimension) { indexed foreach (var row in chunks) { if (row.other.at.x != at.x || row.other.at.y != at.y || row.other.at.z != at.z) continue; if (row.other.dimension != dimension) continue; return row.other.blocks.Copy(); } return default; } view Chunks(mut Chunk chunk, query (Chunk other) chunks) { // ...when its faces are to be made var d = chunk.dimension; chunk.job = Remesh(chunk, Near(chunks, chunk.at + int3(1, 0, 0), d), Near(chunks, chunk.at - int3(1, 0, 0), d), Near(chunks, chunk.at + int3(0, 1, 0), d), Near(chunks, chunk.at - int3(0, 1, 0), d), Near(chunks, chunk.at + int3(0, 0, 1), d), Near(chunks, chunk.at - int3(0, 0, 1), d)); } ``` The view finds each neighbour by its place, an indexed loop over the chunks it has, and hands the task the neighbours' grids, which are the task's own copies ([Async and tasks](#doc-game--tasks--what-a-task-keeps)): a neighbour that changes while the faces are made doesn't change them. Handing the task its own chunk as `mut` changes only the chunk's local fields, so the loop is still indexed by the chunks' places. Each mesh gives back its chunk's six sides and its neighbours' sides toward it as it read them, each as one number, kept in a map of this machine's. Its neighbours' meshes have been made from blocks of their own time, so whichever of two neighbours is made last compares the two: a neighbour made from another side of this chunk than this mesh's has its faces made again, and so has this chunk where it read another side of the neighbour than the neighbour's mesh was made from. That holds whichever was begun first, and when a side changes and changes back while one of them is being made. A change at the edge makes them again at once; a chunk that came or went, once its other neighbours have stopped coming, since a view's worth of chunks comes over many frames and the faces between them are hidden ones. Chunks that come together read each other's blocks, and each one's faces are made once. A chunk whose side is all air has no faces its neighbour hides: a chunk of sky has sides of air, its coming changes nobody's faces, and a block built under it changes none of its faces. In `bench/voxels` this draws fewer than a third of the triangles it did, with the same picture. When a player arrives somewhere, hundreds of chunks want faces at once. The chunks around the player go first: each call says its `priority:` ([Async and tasks](#doc-game--tasks--which-call-starts-first)), and the same `Faces` serves them all. ```csharp // In Remesh, which the view hands a priority var built = await Faces(chunk.blocks, east, west, above, below, north, south, priority: priority); // In the view: how far the chunk is from the player's, in chunks var away = Math.Max(Math.Max(Math.Abs(chunk.at.x - sight.chunk.x), Math.Abs(chunk.at.z - sight.chunk.z)), Math.Abs(chunk.at.y - sight.chunk.y)); var priority = !changed ? WorkerPriority.Background // Only a neighbour came or went: mostly hidden faces : away <= 2 ? WorkerPriority.Urgent : WorkerPriority.Normal; ``` The ground far off (below) is one big mesh, made with `WorkerPriority.Background`: after the chunks' faces, and never so late that it's missing for long, as a background call waits for at most sixteen others to start. Two things keep that picture whole. A block dug at a chunk's edge uncovers a face of the neighbour's, which only the neighbour's new mesh has: the chunk keeps its own new mesh aside until the neighbour's is made, and the two show in the same frame, rather than a hole into the neighbour for a frame or two. And a chunk that leaves this machine has the faces toward it made again, in a `local event(Forgotten)` handler, which keeps its place in a local field, as the match's fields are gone by then. `Forgotten` comes whichever way the chunk leaves this machine: hidden from its player, or destroyed, which is the only way on the hosting machine, whose views see the whole match. ### What players built far off Past the chunks a player has, the ground can be drawn from the dimension's seed: every machine has the seed, so the same hills the server would make are drawn there with nothing sent for them. What players built is sent as **far regions**: an entity for each 8 by 8 chunk columns, with a summary of each column of 8 by 8 cells that players changed, its highest block and how high it is. ```csharp struct Column { byte at; // In its region Block top; int height; } component Far { int2 at; int dimension; List columns; // Only those unlike the seed's int version; // Counts the times they changed } ``` A far region is an entity of its own, not a part of its chunks, because its audience is wider than theirs: the players within its far distance (768 cells in `bench/voxels`, where the chunks go out about a hundred). A component can be restricted further than its entity, never wider. Each has a visibility group, kept as a chunk's is, whose audience is set only while it has columns, so a world nobody built in sends nobody anything for it. The server's side is in components restricted to nobody, as the chunks' is: what the region is as it changes, and who wants it. The server keeps the summaries as players change chunks. A handler of the change that only the server runs, declared after the one that changes the block, tells the region the top of the chunk's part of that column; the region works out the column's top from it (higher where something was built above it, looked for below where it was dug out), and keeps it only where it isn't what the seed makes there: ```csharp // ...after Apply, which changes the block: handlers of one event run in the order they're declared event(Change change) Note(Chunk chunk, mut Seen seen, query (Far far, Summary summary) regions) { // The quarter of the chunk the cell is in, whose top goes to its far region as a Top event Summarise(chunk, seen, (change.cell.z & 15) / 8 * 2 + (change.cell.x & 15) / 8, regions); } ``` What changed goes to players at a pace, so building doesn't flood anyone. A region whose columns changed goes into its dimension's line once (`queued`), and every half second each dimension sends the regions in its line, in the order they changed, 64 columns at most in all: a player far off gets at most two corrections a second of it, however much is built. ```csharp system Publish(mut Streamer streamer, Worlds worlds, Time time, mut World world) { if (streamer.line.count == 0 || time.tick % worlds.gap != 0) return; mut var budget = worlds.pace; while (streamer.line.count > 0 && budget > 0) { var region = streamer.line[0]; mut var done = true; world.Edit(region, summary), world.Edit(region, far), world.Edit(region, seen) { // Far.columns, a step nearer the server's own: `all` once they're alike var changes = Follow(far.columns, summary.columns, budget, out var all); budget -= changes; if (changes > 0) far.version += 1; done = all; if (all) summary.queued = false; // Into the line again at its next change // Shown once it has columns; hidden once it has none left to send, not while a removal has used // the last of the budget before an addition var shown = far.columns.count > 0 || (seen.shown && !all); if (shown != seen.shown) { seen.shown = shown; Visibility.Set(seen.group, shown ? seen.audience : Audience.None); } } if (!done) break; streamer.line.RemoveAt(0); } } ``` A far region comes and goes as chunks do, a while after nobody is within its distance, and is kept in the server's store: `Storage.Save($"far/{dimension}/{at.x}_{at.y}", Json.Write(summary.columns).ToBytes())`, read back with `Json.Read>(loaded.bytes)`. It's saved apart from its chunks, so a server that stops between the two saves can leave a region with a build its chunk didn't keep: a region read back looks again at the chunks the server has, and a chunk made from the seed tells its region what it has where the region has a column, so what the region says comes back to what the chunks have. A player's machine draws a column where a far region it has gives one, in place of the seed's square, with walls down to the seed's ground around it, and the seed's ground everywhere else; where the player's own chunks are, it draws only what's above or below them. ## What it costs `bench/voxels` on one machine (a 12-core desktop, one core of it: the tick is one thread's work), 60 ticks a second, 50 ms each way with a datagram in a hundred lost, bots that fly, dig, build and change dimension every 20 seconds (`notes/voxels.md`, At scale, has every table and how each was measured; 2026-11-16): | | 8 players, 845 chunks each | 3,125 chunks each | 6,845 chunks each | 32 players | 32, far apart | 64 players | |---|---|---|---|---|---|---| | Chunks the server holds | 6,490 | 16,941 | 32,827 | 12,669 | 28,549 | 17,598 | | Server's update, median / 99th percentile / longest, ms | 0.28 / 2.9 / 6 | 0.70 / 7.6 / 12 | 1.4 / 10.5 / 20 | 1.5 / 8.2 / 15 | 5.4 / 16.5 / 24 | 3.6 / 16.2 / 28 | | Server, ms of every second | 28 | 66 | 119 | 104 | 300 | 214 | | Sent to each player, KB a second | 22 | 57 | 116 | 25 | 24 | 28 | | A player's machine's ticks, 99th percentile, ms | 0.9 | 2.5 | 4.4 | 1.4 | 1.4 | 1.9 | | A whole view on a player's machine after a dimension hop, ticks | 25 | 43 | 52 | 26 | 30 | 24 | (The first three columns and 32 far apart are of the build that asks for a box over a few ticks and packs a whole view off the tick's thread, on every core; the two others are of the build before it.) - **What holds 60 ticks a second**: 32 players at the default view (96 cells each way) with room, 64 at the edge of a frame when they start together; 8 players at twice the radius with room, and at three times but for its longest updates (20 ms: the tick a player joins or leaves every chunk of a view others are in). Players far apart, who share no chunk, cost the server more than players together: what it pays goes with the chunks it holds. 32 apart hold 60 Hz while nobody hops (11.6 ms at the 99th percentile). Threads change none of it. - **A player is sent** 17 KB a second flying over fresh ground, 22 to 25 with a dimension hop every 20 seconds, 5 standing, whatever the number of players. A chunk is about 140 bytes as sent, a thirtieth of its cells. Players who turn every tick, as a mouse does, add 8 to 19 KB a second to what each is sent. - **A whole view arrives in a third of a second**: one player hopping into a dimension nobody is in has its 845 chunks 20 ticks after the hop (21 with a datagram in a hundred lost, 29 with five), nearest first; at twice the radius, 40. Seven of those ticks are the player's own lead on the server. - **A dimension nobody is in costs nothing**, and eight players a dimension each cost what eight far apart in one do. Leaving a dimension frees its chunks once nobody has been near them for the linger, and the server lets go of the memory that held nothing else: about a quarter of what the dimension took in this game's runs, as memory that still holds one small value of another chunk stays. - **A long session is level**: 8 players flying outward for 20 minutes hold 9,000 chunks and far regions in 24 MB from the fourth minute on, the server's update 1.2 ms on average throughout. - **A player's own frame** at 1920 by 1080, paced at 60 Hz, takes 0.7 ms of CPU at the default view of the version to play (405 chunks) and 2.1 ms with 3,125. The chunks around the player have their faces 0.12 s after a hop at any view, and all of them are there after 0.15 s (405 chunks), 0.45 s (1,445) and 1 s (3,125). - **What breaks first**: the one thread for what isn't chunks being made. A tick in which a player joins or leaves the audiences of a whole view of chunks that are already there is 18 ms for 6,845 of them, and what a player is sent of a whole view is read on the tick's thread, 2 to 4 ms a view (its packing is another thread's, and a view of more than 4 MB goes out a tick later for it). Eight players who hop together have the last tenth of their views a few ticks later than one who hops alone: the server starts as many whole views in an update as fit in it. The engine's notes (`notes/voxels.md`) have the rest, and what's still missing. --- Source: https://tide-engine.dev/game/tasks.md Write Tide async functions and tasks that wait for time, ticks, frames or other async calls, in the match or local presentation. # Async and tasks Some code takes longer than a tick: a countdown before a round, an ability that ends after a moment, a sign-in that waits for a service. An `async` function can wait, with `await`, and pick up where it stopped. Calling one starts a **task**, which goes on by itself, tick after tick or frame after frame, until it's done. ```csharp singleton Round { int count; } event RoundStarted { } // Counts down a second at a time, then the round begins. async event(RoundStarted) Countdown(mut Round round) { for (var i = 3; i > 0; i--) { round.count = i; await Wait.Seconds(1); } round.count = 0; } ``` The round below is one task: it counts down a second at a time, lets the runners go for five seconds, and ends. While they run, tap a runner. Each dash is a task of its own, which speeds its runner up, waits, and slows it down again. **A countdown, and a dash** ([Run example](https://tide-engine.dev/examples/tasks/?stats)) ```tide settings { title = "Tasks"; tickRate = 30; maxPlayers = 1; } component Runner { float angle; float speed = 1; } singleton Round { int count; // 3, 2, 1 while it counts down bool running; bool busy; } event RoundStarted { } event Boost { } command StartRound { } command Dash { } scene Main { } event(Spawned) Setup(with Main) { for (var i = 0; i < 3; i++) Spawn(Runner { angle = i * 2.1 }); } command(StartRound start, PlayerID sender) Begin(mut Round round) { if (round.busy) return; round.busy = true; Send(RoundStarted { }); } // One task for the whole round: it waits, and goes on where it stopped. async event(RoundStarted) Countdown(mut Round round) { for (var i = 3; i > 0; i--) { round.count = i; await Wait.Seconds(1); } round.count = 0; round.running = true; await Wait.Seconds(5); round.running = false; round.busy = false; } command(Dash dash, PlayerID sender) DashRunner(with Runner) { this.Send(Boost { }); } // A task for each runner that dashes. It gets the runner again after the // wait, as it is then, and ends by itself if the runner is gone. async event(Boost) Sprint(mut Runner runner) { runner.speed = 4; await Wait.Seconds(0.6); runner.speed = 1; } system Run(mut Runner runner, Round round, Time time) { if (round.running) runner.angle += runner.speed * time.dt; } view Track(Round round) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, -0.2), 2.3); Draw.WireCircle(float2(0), 1.5, 0.03, Color(0.24, 0.25, 0.27)); var word = round.count > 0 ? $"{round.count}" : round.running ? "GO" : ""; Draw.Text(word, float2(0), 0.9, Color.white, Anchor.MiddleCenter, Font.Bold); } view Runners(Runner runner, Round round, Devices devices) { var at = float2(Math.Cos(runner.angle), Math.Sin(runner.angle)) * 1.5; Draw.Circle(at, 0.16, runner.speed > 1 ? Color.white : Color(0.98, 0.75, 0.14)); var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position)); if (round.running && devices.pointer.press.down && Math.Distance(pointer, at) < 0.4) this.Send(Dash { }); } view Controls(Round round) { Draw.SetScreen(); Draw.Text(round.running ? "Tap a runner to make it dash" : "A round is a task that waits", float2(16, 14), 16, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Disabled(round.busy) { if (GUI.Button(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Start the round")) Send(StartRound { }); } } ``` ## Async functions `async` before a function lets it wait. Its declaration names the completion value: `async int`, `async string`, or `async void` for nothing. Calling it returns a started task handle. ```csharp async int Doubled(int x) { await Wait.Ticks(1); return x * 2; } ``` A call can be awaited immediately, kept, or discarded: - **`await` it** for its value, from async code: `var n = await Doubled(3);`. The code waits there until the call is done, then goes on with its value. `await` binds like `try`, so `await Doubled(3) + 1` adds 1 to the value. - **Keep its handle**: `var build = BuildMesh(voxels);`. The operation has already started. `await build` gets its result; `build.Cancel()` requests cancellation. - **Call it as a statement** to start a task: `Doubled(3);`. The task goes on by itself, and the code that started it doesn't wait. A started task's value is dropped. Match calls produce `Task`; local calls and local workers produce `LocalTask`. Void uses `Task` or `LocalTask`. The type preserves the complete declared result: an `async MeshData Build(...) fails MeshError` call produces `Task` or `LocalTask` in its world. Optional results use `Task` or `LocalTask`. Copied handles name the same operation. Multiple tasks can await it, and repeated awaits get independent ordinary value copies of the same result. Awaiting a handle never restarts its operation. An async function that can fail works as any function that fails (see [Errors](#doc-language--errors)): `await Fetch(name) ?? "nobody"`, `if (await Fetch(name) is string token) { ... }`, `try await Fetch(name)`, and `await Fetch(name)!`. ## Async handlers `async` before an event handler makes each event start a task, which can wait like an async function: ```csharp async event(Spawned) Arm(mut Turret turret) { await Wait.Seconds(2); // Ready two seconds after it's spawned turret.armed = true; } ``` Local handlers can be async too: `local async event(...)` (see [Local state](#doc-game--local-state)). A local handler of one of the match's events can't be yet: it starts a task by calling an async function (see [Events](#doc-game--events--what-isn-t-there-yet)). Systems and views can't wait, as they run again every tick or frame: they start tasks instead, by calling an async function. ## What tasks wait for `await` waits for a task handle or an immediate async call. These engine operations also return started handles, so a timer can be kept and awaited later: | | | |---|---| | `await Wait.Ticks(n)` | `n` of the match's ticks. Match code only. | | `await Wait.Frames(n)` | `n` of this machine's frames. Local code only. | | `await Wait.Seconds(s)` | `s` seconds: in the match, the nearest whole number of ticks (at least one), the same on every machine; in local code, this machine's time. | | `await Storage.Load(key)` | What the [server's store](#doc-game--files--waiting-for-the-answer-in-a-task) keeps under the key, as a `List`, failing with `IOError`. Match code only: the task goes on in the tick the answer is given to, on every machine. | | `await Storage.List(prefix)`, `(prefix, after)` | The store's keys that start with the prefix, a page of them, as a `StorageKeys`, failing with `IOError`. Match code only. | A wait of 0, or less, doesn't wait at all. The store's two have no handle to keep: without `await`, they're answered by a `Loaded` or `Listed` event. For now: - Methods, extern functions and functions that take an `Action` can't be async. - `await` can't go in a block written after a call (an `Action`). - Tasks can't draw, or read this frame's `Devices`: that's what views do, every frame. - The input's `Sample`, `Sanitize` and `Predict`, frags and verts, operators and `Interpolate` start no tasks. A plain function or method does, as the code that calls it could: see [Starting a task](#doc-language--functions--starting-a-task). - Awaiting an event isn't supported yet. An event can start an async handler, which then waits for time or other tasks. `Storage.Flush()`, `Web.Fetch(url)` and `request.Send()` follow the same handle model. For example, `LocalTask flush = Storage.Flush();` starts one flush; `try await flush;` handles its eventual result. See [Files](#doc-game--files) for the provider and storage APIs. ## Where tasks run A task belongs to a world, like the code that starts it. A system's or a match handler's tasks are the match's: they're part of it, in snapshots, state hashes and rollback, they go to players who join, and they carry on when the match changes hands. A view's or a local handler's tasks are this machine's, in its local state. An async function's world comes from what it does: changing the match (spawning its entities, changing its components through `mut`, sending its events) makes it match code, and using local state, the [local fields](#doc-game--tasks--local-fields) of the match's components among it, or reading [`Frame.dt`](#doc-game--local-state--time), makes it local. A [function it calls](#doc-language--functions--sending-and-spawning) that sends or spawns counts as its own doing. One that does neither runs in whichever world starts it. Doing both is an error, as a task runs in one world. ## What a task keeps While a task waits, it keeps its locals and its parameters, copied: text, lists and grids too, a grid a `target.Read()` gave and one of an asset's among them. A `foreach` over an asset reads the asset as it is each time round, so a loop that waits a frame per element of `asset List> run` goes on through the files [tide run](#doc-tools--cli) loaded again while it waited; the element it held as it waited is its own copy. Its **components and singletons** it gets again each time it goes on, as they are then, so it sees what changed while it waited. They have to be the caller's own, its parameters: ```csharp async void Dash(mut Body body) { body.speed = 10; await Wait.Seconds(0.2); body.speed = 1; // The entity's Body as it is now } system StartDash(mut Body body, Controls controls) { if (controls.dash.down) Dash(body); } ``` An async function's `mut` parameters are its components and singletons; it can't keep the caller's other variables while it waits, so it returns what it works out instead. For the same reason it has no `out` parameters: a struct returns several values. **A grid parameter** is a copy of the task's own, made where it's called, as a list parameter is: a system or a view that changes its grid after starting the task doesn't change the task's, and the task reads its copy where it is after every wait, however many, with no copy made again. The pack's grid is copied whole, so a pack [tide run](#doc-tools--cli) loads again while the task waits leaves the task's copy as it was. An async function the task awaits with the grid gets a copy of its own too. A match task's copy is part of the match, in snapshots, hashes and what a joining player gets, like its other grids; a local task's is this machine's. A grid parameter can't be `mut`: to change a field's grid, take the component or singleton it's in. ```csharp singleton Field { Grid2 cells = Grid2(64, 64); bool watching; int changed; } int Differences(Grid2 now, Grid2 before) { mut var count = 0; foreach (var at in now) count += now[at] != before[at] ? 1 : 0; return count; } async void Settle(mut Field field, Grid2 before) { await Wait.Ticks(30); field.changed = Differences(field.cells, before); // The cells now, against the copy as they were 30 ticks ago } system Watch(mut Field field) { if (field.watching) return; field.watching = true; Settle(field, field.cells); } ``` ### Local fields A local task reads and writes the [local fields](#doc-game--local-state--local-fields) of the match components and singletons it takes, as a view does. They come with the component each time the task goes on, from where this machine keeps the entity's, so the task sees what views wrote while it waited, and what it writes is there for the next frame's views: ```csharp component Chunk { float3 corner; Grid3 blocks = Grid3(16, 16, 16); int edits; local Mesh mesh; local int drawn; // The edits its mesh was made at, plus one local LocalTask job; // The task making it, while it does } async void Remesh(mut Chunk chunk, int version) { var built = await Faces(chunk.blocks); // A local worker chunk.mesh = Mesh(built.vertices, built.indices); chunk.drawn = version; } view Chunks(mut Chunk chunk) { if (!chunk.job.isRunning && chunk.drawn != chunk.edits + 1) chunk.job = Remesh(chunk, chunk.edits + 1); if (chunk.drawn > 0) Draw.Mesh(chunk.mesh, float4x4.Translate(chunk.corner)); } ``` - **It's this machine's task.** Using local fields makes an async function local, so a view or a local handler starts it, never a system. `mut` on a match component lets it write the local fields alone: a task that also changes the component's match fields is an error, as it would run in both worlds. - **The view and the task share them.** What the view wrote before it started the task, the task reads, and the other way round. They're the entity's own from then on. - **Handing it the component changes nothing of the match.** A view that starts the task with its `mut Chunk chunk` changes the chunk's local fields, never its match fields, so a loop in that view over the other chunks that skips them by a match field of its own chunk, like `if (row.other.at.x != chunk.at.x + 1) continue;`, is still an [indexed loop](#doc-game--systems--only-the-rows-that-can-pass), and it can hand the task the neighbour's grid, `Remesh(chunk, row.other.blocks)`, which is the task's own copy. The same goes for a function the view hands it to that writes its local fields alone. A function written in C, or one that hands the component on to C, counts as changing all of it: what C writes isn't the compiler's to know. - **It ends with the entity**, once the world this machine draws no longer has it, and the entity's local fields go once neither that world nor the one the server confirmed has it. So a task never writes for an entity that's gone. If the server undoes a destroy this machine predicted, the local fields come back as the task left them, but the task doesn't. That's why the example keeps the task's handle rather than a flag the task clears: `job.isRunning` is false once the task has ended, however it ended, so the view starts another. - **Hidden or without the component**, the same: an entity this machine's player can no longer see is gone, with its local fields and its task, and comes back with its defaults; a task that takes a component the entity loses ends at the next frame, whether it was waiting or due to go on, and that component's local fields go. If the component comes back, it comes with new local fields and no task. - **Rollback and reloads** leave them as they are: a task that goes on after a correction reads its component as corrected, and its local fields as this machine left them. A task that carries over a hot reload finds them where the new build keeps them. ## When tasks go on, and when they end Tasks whose time has come go on at the end of the tick (or frame), after its changes and events, in the order they started; what they change, spawn and send then applies too. A task ends when its code does, and: - **with what started it**: a task started by code that runs for an entity belongs to that entity, and ends when the entity is destroyed. A task started by a task belongs to the same entity, and one a function starts belongs to what the code that called the function runs for. Code that runs for no entity starts tasks that belong to the world, which last as long as it does. - **without its components**: a task whose entity no longer has the components it takes ends. - **with its match**, for a local task of one of the match's entities, or one that takes the match's components or singletons: once this machine leaves the match, it ends at the next frame, even if the next match has an entity with the same handle. Immediate nested awaits can share a private frame. A kept handle identifies a separate started operation; its existing entity/world ownership still applies. An async function can't immediately await itself, as its private frame would hold itself; it can start another operation and keep its handle. ## Cancellation and lifetime `build.Cancel()` cancels that operation and ends every task awaiting it. Cancellation ends an awaiting continuation without inventing a success value or a declared error. Cancelling one awaiting task preserves a shared build for its other consumers. A task that ends while it waits, cancelled or with its owner, lets go of what it waited for at once: a file's or a fetch's, and a GPU read's, whose slot and pixels go free for the next read. `isRunning` is true while an operation is queued, running or waiting. `isCompleted` includes cancellation; `isCancelled` also describes default or stale handles. Cancelling a completed or stale handle has no effect. Old handles never refer to a newer operation that reused its storage. Equality compares operation identity. Running Tide code stops cooperatively at generated safe points in loops, statements and helper calls. Trusted C finishes its current call. An unused worker can be abandoned once no retained handle or awaiting task needs it; discarded ordinary async calls continue by themselves. Completed results are retained while reachable handles need them and reclaimed afterward, including unreachable cycles. Local saves and compatible reloads preserve handles and cached results. A task dropped by an incompatible reload leaves cancelled handles. Local jobs restart from saved owned inputs; native callbacks and provider pointers aren't saved. Match handles, results and cancellation remain deterministic match state. Local code can inspect a match handle's status; cancelling it belongs to match code, usually through a command. Match handles aren't supported in sharded games yet. Local handles and workers, and existing directly awaited or discarded match async calls, remain available. Distributed task identity, result retention and cancellation need their own ownership contract. With per-recipient visibility, match tasks remain authoritative server work. Their registries, continuations and cached results stay private. A projected client cannot start a retained match operation, and a published handle whose operation is absent there is stale. Publish permitted ordinary progress and results for views. ## Local workers Use a `local worker` for expensive CPU calculations such as chunk meshing. Capture its input from local code, await it from an async function, and publish the completed result there. The view can keep drawing the previous mesh. ```csharp struct MeshData { List vertices; List indices; } local singleton ChunkVisual { List voxels; MeshData mesh; int generation; bool building; } local worker MeshData BuildMesh(List voxels) { return GreedyMesh(voxels); // The game's ordinary calculation helper } async void Rebuild(mut ChunkVisual visual) { visual.building = true; var generation = visual.generation; var mesh = await BuildMesh(visual.voxels); if (visual.generation == generation) visual.mesh = mesh; visual.building = false; } ``` Start `Rebuild(visual)` from a view or local handler when the input changes and `building` is false. Advance the local generation whenever that meshing input changes, including neighboring boundaries and rollback corrections; discard an outdated result and request the latest input. For many chunks, keep a local queue and schedule the visible chunks first. This example uses a local singleton; for one of the match's entities, the task can keep the result in the entity's [local fields](#doc-game--tasks--local-fields) instead. Workers receive independent copies of their inputs and return independent values. Numbers, text, lists, maps, sets, ordinary structs, fixed arrays and optional/error results follow their normal value rules. A worker takes no `mut`, `out`, component/singleton binding, World, query, devices, resource handle, asset reference/borrow or callable/shader binding. Pass the CPU data it needs. Its helpers have the same restrictions: no live world, drawing, frame services, file/network operations, task starts or implicit match randomness. C remains trusted; C called by workers must be safe to run on their threads. A worker can also take read-only `Grid2` and `Grid3` snapshots: ```csharp local worker List FindSolidCells(Grid3 voxels) { mut List cells = []; foreach (var at in voxels) if (voxels[at] != 0) cells.Add(at); return cells; } ``` Await it with a grid field or grid asset. Capture copies its directory and existing chunks before dispatch; later source edits or pack replacement cannot change the worker's input. Capture costs time on the calling thread, so pass a chunk's grid rather than a whole voxel world's when possible. Ordinary helpers can read and forward the snapshot. Grid parameters stay read-only, including through those helpers; grid locals and return values remain unsupported. GPU `Sample` operations remain unavailable in workers. Arguments are captured in their written order. If a later argument changes the source or awaits another task, an earlier grid capture keeps its original cells. Loop semantics stay the same. Workers additionally permit `parallel` over their own lists of plain values, including local variables: ```csharp local worker List NormalizePoints(List points) { mut List result = points; parallel (var i in result) { result[i] = Math.Normalize(result[i]); } return result; } ``` Each step changes only its own output element or block. Code after the loop waits for all steps. Ordinary `for` and list `foreach` loops remain ordered. Grid `foreach` uses the existing independence analysis inside workers too; appending to an output list or reducing a total keeps the loop ordered. Explicit list-parallel steps can read the captured grids while writing their own output. Jobs and their parallel steps share the host's bounded pool. With no background provider, a worker runs synchronously when polled, so expensive work can still stall a frame on a host without threads. Small parallel loops run serially: small is the steps' reckoned work in all, counting the functions they call, so a short loop of costly steps still shares out. Local code can start a worker and keep its `LocalTask` handle; only local async code awaits its result. Bare `worker` is reserved for a future match contract and is currently an error. An owner disappearing drops its continuation. Abandoned queued calculations are skipped, and running Tide calculations stop cooperatively. Reload drains old callbacks before unloading their code; trusted C must return before that drain can finish. Saved or retained waiting tasks restart their pending worker after restoration or reload. No worker state enters match snapshots, hashes or networking. ### Which call starts first More worker calls can wait than there are threads free. A call says when it starts among them with `priority:`, written last, by name: ```csharp // The chunk the player stands in, before the ones far off var built = await BuildMesh(voxels, priority: near ? WorkerPriority.Urgent : WorkerPriority.Normal); // A handle's call takes it too LocalTask far = BuildMesh(horizon, priority: WorkerPriority.Background); ``` `WorkerPriority` has three members. `Urgent` calls start first, then `Normal` ones, which is what a call that says nothing is, then `Background` ones, each in the order they came. Nothing waits for ever: a waiting normal call starts after four urgent starts, and a waiting background call after sixteen starts of the others. The worker is the same function for all of them, so one mesher serves the chunk underfoot and the horizon. A priority says which waiting call a free thread takes. It never interrupts a call that has started, and it doesn't make the copy of a call's inputs cheaper. The match's ticks keep their threads first, as before. Each priority has its own room for waiting calls, so a flood of background calls keeps no urgent one out. The value is read once, as the call begins: before the call waits for room and before its arguments. It can be any `WorkerPriority` value, but not one that has to be awaited. A worker can't name a parameter `priority`. ## In C Hosts tell local code how long each frame is, before `tide_frame`: `tide_local_frame_time(local, seconds)`, which local tasks' waits count down and `Frame.dt` reads. `tide/run.h` does. Under `tide run`, a waiting task carries over to a new build when its code is the same; when it changed, the task is dropped, and tide says so. Custom hosts set `gui.jobs` to their `tide_jobs` provider before `tide_frame` to enable local background workers. The standard host supplies `tide_platform_jobs()`. Providers implement the optional `background` and `help` callbacks from `tide/jobs.h`; `tide/worker.h` describes item ownership and completion. A zeroed GUI retains the synchronous fallback. `gui.worker_limits` optionally supplies `tide_worker_limits`. Zero fields use the current defaults: 64 pending private jobs, 64 MiB of retained input captures, and 4 MiB of capture/result transfers per frame. Direct worker awaits wait for admission before evaluating their arguments. Nested awaited arguments don't hold a reservation while waiting for another worker. The first two limits count each priority apart: normal calls have them, urgent calls as much again, and background calls half as much. Local state hands a provider as many calculations as it has threads beside the caller's, and keeps the rest in its own queues by priority, so a provider's `background` needs no ordering of its own. Transfer limits are soft: one transfer that crosses the budget finishes, then later transfers wait for another frame. This lets an oversized job make progress. Started handle calls evaluate and snapshot their arguments when called; their saved async input frames are outside the private-job capture limit. These controls aren't a hard per-job or process memory cap. Feed very large bursts from an async queue when input snapshots themselves are costly. The profiler reports worker compute and queue wait per completed job, with input-capture and result-transfer totals. Frame-thread copying remains part of the frame's cost; worker compute runs on the background pool. --- Source: https://tide-engine.dev/game/input.md Sample keyboard, mouse, touch and gamepad devices into Tide player input, then predict, sanitize and share it across the multiplayer match. # Input A player's **input** is what they do in one tick, and it's what the network sends. A game can declare one `input`, whose fields systems read, or read [devices directly in the match](#doc-game--input--devices-in-the-match). ```csharp input PlayerInput { float2 move; bool jump; Sample(Devices devices) { var keys = devices.keyboard; if (keys.d.pressed) move.x += 1; if (keys.a.pressed) move.x -= 1; move += devices.gamepad.leftStick; jump = keys.space.pressed || devices.gamepad.buttonSouth.pressed; } } system Jump(PlayerInput input, mut Velocity velocity) { if (input.jump.down) velocity.value.y = 5; } ``` Click the game below so it has the keyboard, then walk with `A` and `D` or the arrows and jump with space. A drag works too: sideways to walk, up to jump. `Sample` turns what the devices say into the input's two fields, a system moves the hero by them, and the line at the top shows what the match got. **An input, sampled and read** ([Run example](https://tide-engine.dev/examples/input/?stats)) ```tide settings { title = "Input"; tickRate = 30; maxPlayers = 1; } // A drag of the pointer, which a view turns into a stick for the input. local singleton Stick { float2 start; float2 drag; bool up; } // What a player does in one tick. It's the only thing a machine sends the others. input Pad { [Clamp(-1, 1)] float2 move; bool jump; Sample(Devices devices, Stick stick) { var keys = devices.keyboard; if (keys.d.pressed || keys.rightArrow.pressed) move.x += 1; if (keys.a.pressed || keys.leftArrow.pressed) move.x -= 1; move += devices.gamepad.leftStick + stick.drag; jump = keys.space.pressed || keys.w.pressed || keys.upArrow.pressed || devices.gamepad.buttonSouth.pressed || stick.up; } } component Hero { float2 position; float2 velocity; float2 move; // What the views show of the input, which only the match reads bool jump; int jumps; } scene Main { } // The hero is its player's, so it reads that player's input. event(PlayerJoined joined) GiveHero() { Spawn(Hero, Owner { player = joined.player }); } system Walk(Pad pad, mut Hero hero, Time time) { hero.velocity.x = pad.move.x * 3; // The input says held. The match works out `down` against the tick before. if (pad.jump.down && hero.position.y <= 0) { hero.velocity.y = 6; hero.jumps += 1; } hero.velocity.y -= 16 * time.dt; hero.position += hero.velocity * time.dt; if (hero.position.y < 0) { hero.position.y = 0; hero.velocity.y = 0; } hero.position.x = Math.Clamp(hero.position.x, -1.7, 1.7); hero.move = pad.move; hero.jump = pad.jump; } view Drag(Devices devices, mut Stick stick) { var pointer = devices.pointer; if (pointer.press.down) stick.start = pointer.position; var pull = pointer.press.pressed ? pointer.position - stick.start : float2(0); stick.drag = float2(Math.Clamp(pull.x / 50, -1, 1), 0); stick.up = pull.y > 40; // The devices count y up } view DrawHero(Hero hero) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, 1), 2.2); Draw.Line(float2(-2.2, -0.3), float2(2.2, -0.3), 0.04, Color(0.24, 0.25, 0.27)); Draw.RoundRect(hero.position + float2(0, 0.05), float2(0.5, 0.7), 0.16, Color(0.98, 0.75, 0.14)); Draw.Line(hero.position + float2(0, 0.6), hero.position + float2(hero.move.x * 0.6, 0.6), 0.06, Color(0.18, 0.83, 0.75)); Draw.SetScreen(); Draw.Text($"move.x = {hero.move.x:F1} jump = {hero.jump} jumps: {hero.jumps}", float2(16, 14), 16, Color.white); Draw.Text("Click here, then A and D or the arrows, and space.\nOn a touchscreen, drag sideways, and up to jump.", float2(16, Screen.height - 46), 13, Color(0.64, 0.64, 0.68)); } ``` ## Sampling The engine calls the input's `Sample` method on the player's own machine, once per tick. Its fields start at their defaults, and `Sample` assigns them by name, without `mut`. `Sample` runs outside the match. It reads this machine's `Devices`, and the local singletons it takes as parameters, like `Sample(Devices devices, Settings settings)`, but never the match. It's the place to work out what the match needs from things only this machine knows: an aim direction from the mouse, which is in this machine's window, or anything that depends on its settings. ## Who gets which input An input parameter gives a system the input of the player who **owns** the entity it's running for. `Owner` is a built-in component that ties an entity to a player: ```csharp Spawn(Body, Owner { player = joined.player }); ``` It's a normal component: it can be read, written, added and removed, and writing it hands control over. Entities without an `Owner`, or whose owner is no player the match has a place for (`default`, or a `PlayerID` past its `maxPlayers`), get the **server's input**, and so do systems that run once per tick. An owner the match has a place for who isn't in it right now is still that player: the entity reads their input, not the server's. That's how the server controls what no player owns. An input parameter doesn't pick entities: add `with Owner` to only run on owned ones. Below are two machines in one match. Move the pointer over a frame to steer that machine's player. One system moves every body, and for each it reads the input of whoever owns that body. The gray body has no `Owner`, so it reads the server's input, which here is player 1's machine's: it follows player 1's pointer, slowly. **Trade bodies** writes the two `Owner`s the other way round, and from then on each player steers the other's body. **Whose input a system reads** ([Run example](https://tide-engine.dev/examples/owners/?stats)) ```tide settings { title = "Owners"; tickRate = 30; maxPlayers = 4; } scene Main { } component Body { [Position] float2 position; // Drawn gliding to where a correction put it Color color; float speed = 2.5; } singleton Roster { Map bodies; int arrivals; } command Trade { } // Where this machine's pointer is in the arena, which its input sends. local singleton Aim { float2 world; bool moved; } input Steer { // A place, not something a player does: what another machine guesses of it stays [Absolute, Clamp(-3, 3)] float2 target; [Absolute] bool steering; Sample(Devices devices, Aim aim) { target = aim.world; steering = aim.moved; } } // A body nobody owns. It reads the server's input: the machine hosting the match. event(Spawned) Setup(with Main) { Spawn(Body { position = float2(0, 1.4), color = Color(0.64, 0.64, 0.68), speed = 0.8 }); } // Owner ties an entity to a player, so it reads that player's input. event(PlayerJoined joined) Arrive(mut Roster roster) { var first = roster.arrivals % 2 == 0; roster.arrivals += 1; roster.bodies[joined.player] = Spawn( Body { position = float2(first ? -1 : 1, 0), color = first ? Color(0.98, 0.75, 0.14) : Color(0.18, 0.83, 0.75) }, Owner { player = joined.player }); } event(PlayerLeft left) Depart(mut Roster roster) { roster.bodies[left.player].Destroy(); roster.bodies.Remove(left.player); } // One system for every body. `steer` is the input of whoever owns the one it runs for. system Follow(Steer steer, mut Body body, Time time) { if (!steer.steering) return; var way = steer.target - body.position; var step = body.speed * time.dt; body.position += Math.Length(way) > step ? Math.Normalize(way) * step : way; } // Owner is a component like any other: writing it hands control over. command(Trade trade, PlayerID sender) TradeBodies(mut Roster roster) { mut PlayerID other = sender; foreach (var seat in roster.bodies) { if (seat.key != sender) other = seat.key; } if (other == sender) return; // Nobody to trade with var mine = roster.bodies[sender]; var theirs = roster.bodies[other]; mine.Add(Owner { player = other }); theirs.Add(Owner { player = sender }); roster.bodies[sender] = theirs; roster.bodies[other] = mine; } view Point(Devices devices, mut Aim aim) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, 0.2), 2.4); aim.world = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position)); if (Math.LengthSq(devices.pointer.delta) > 0) aim.moved = true; GUI.SetTheme(GUITheme { radius = 6 }); if (GUI.Button(Rect(12, Screen.height - 44, Screen.width - 24, 32), "Trade bodies")) Send(Trade { }); } // Every body this machine's player doesn't own: the other player's, and nobody's. view Others(Body body, without ownership) { Draw.Circle(body.position, 0.2, body.color); } view Unowned(Body body, without Owner) { Draw.Text("no Owner", body.position + float2(0, 0.3), 0.17, Color(0.64, 0.64, 0.68), Anchor.LowerCenter); } view Mine(Body body, with ownership) { Draw.Circle(body.position, 0.2, body.color); Draw.WireCircle(body.position, 0.32, 0.04, Color.white); Draw.Text("yours", body.position + float2(0, 0.4), 0.2, Color.white, Anchor.LowerCenter); } ``` A view picks the entities this machine's player owns with `with ownership`, and every other one with `without ownership` (see [Your own entities](#doc-game--views-and-the-match--your-own-entities)). That's for views: the match runs the same on every machine, so a system has no player of its own to ask about. Players are `PlayerID`s, not ints or connections. Like `Entity`, a `PlayerID` is opaque, compared with `==`, and has a null value. A player who reconnects gets their `PlayerID` back, and keeps everything they owned. `PlayerID(0)` names a player by number, for local play and tests. ## Held, not pressed Input carries whether buttons are held, not whether they just went down: when a player's input is late, the other machines guess it by repeating their last one, and a repeated "just went down" would press twice. In the match, `bool` fields of the input get `.down` and `.up`, worked out against the previous tick, inside structs too: `input.aim.fire.down`. ## Passing input to helpers Synchronous functions and methods can read the same input as their caller: ```csharp bool WantsJump(PlayerInput controls) { return controls.jump.down; } system Jump(PlayerInput input, mut Velocity velocity) { if (WantsJump(input)) velocity.value.y = 5; } ``` Pass the caller's input parameter directly. The helper borrows its current and previous tick together, preserving the selected player's input, nested `.down`/`.up` edges, prediction and replay behavior. Helpers can forward it to other helpers, without an extra argument or a full input copy. They gain no implicit player, entity or world access. Input parameters are read-only: no `mut`, `out`, `in` or default. A borrow cannot be stored, returned or kept by a task. Copy individual fields when ordinary values need to outlive the call. Synchronous action blocks, comparisons and parallel steps can read or forward input under their existing rules. Externs, operators, shaders, audio declarations and async routines take no input borrow. `Sample`, `Sanitize` and `Predict` still pass their field values to helpers; they have no input parameter to borrow. ## What other machines guess A machine runs ahead of the last tick the server confirmed to it, by about its round trip (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). For those ticks it has to guess what the other players do, and its guess is their last input, repeated. A guess that turns out wrong is put right when the server's answer comes, and the further ahead a machine runs, the more there is to put right: at a ping of 500 ms, a player who stopped running is shown running for half a second more, and then moved back all of it. So a guess only repeats an input for 0.15 seconds past what the machine knows. After that it takes the player to have let go: every field of their input is back at its default. However slow the connection, a guess that was wrong moves things by what a player does in 0.15 seconds, at most. A machine with a round trip under about a tenth of a second never runs that far ahead, and nothing changes for it. That suits what a player is **doing**: an axis that's pushed, a button that's held. A field that says **where something is**, like an aim or the cell under a pointer, has no rest to go back to: its default is only another place. Mark those `[Absolute]`, and a guess keeps them for as long as it goes on: ```csharp input Controls { [Clamp(-1, 1)] float move; // Doing: back to 0 bool fire; // Doing: let go [Absolute] float2 aim; // Where: kept [Absolute] int weapon; // Which: kept } ``` - **Letting go presses nothing.** No field's `.up` is true for it, so a shot that fires when a button is let go doesn't fire on a guess. - **The devices match code reads** (see [Devices in the match](#doc-game--input--devices-in-the-match)) are let go the same way: keys up, sticks centered. - **Only guesses change.** What the server runs, and what it confirms, is the input each player sent. A player whose input arrives late still keeps their last one for that tick, on every machine. - **What it costs.** A player who keeps going is shown a little behind where they'll turn out to be, and each tick the server confirms, the machine runs the ticks past its guess again. For the default guess, both happen only on a machine further ahead than 0.15 seconds, and only while someone is doing something. Custom guesses can require replay sooner. `[Absolute]` takes no arguments, and goes on the input's own fields, not on the fields of a struct it holds. ## Choosing a guess Use `[DontPredict]` for actions that should occur only when a real input sample says so. On every guessed tick, the field starts at its declared default: ```csharp input Controls { float2 move; [DontPredict] bool jump; [DontPredict] bool dash; [Absolute] float2 aim; } ``` Movement continues from the previous input; jump and dash become false immediately. Real input from this machine still acts immediately, and received input keeps its actions. The attribute takes no arguments and goes on the input's own fields. A marked struct or array resets as a whole. It cannot combine with `[Absolute]` on the same field. For a computed guess, add `Predict()`: ```csharp input Controls { float2 move; bool dash; Predict() { dash = false; move *= 0.9; } } ``` It runs once per guessed tick, starting from the previous input, after `[DontPredict]` resets. Fields it leaves untouched continue; computations such as the movement fade accumulate across guessed ticks. It can also explicitly replace a marked field's default. Repair, bounds and `Sanitize()` apply afterward. The existing 0.15-second limit still resets non-absolute fields after `Predict()` runs. `Predict()` takes no parameters and reads only the input's fields. It can call pure helpers, as `Sanitize()` does. It cannot read devices, match or local state, frame time or randomness, or send events, spawn entities or start tasks. The engine's `viewTime` remains read-only. These changes apply to client guesses of other players and a remote server. Actual samples, authoritative server ticks and confirmed replay keep their existing behavior. Changing a guess creates no `.down` or `.up` edges, so clearing an action does not invent a release. Normal `.down` already avoids repeated presses when a held bool is repeated; use these hooks when the held value itself or another action field should not continue into guessed ticks. ## Devices `Devices` has a keyboard, a mouse, a gamepad, a touchscreen and the pointer. Every button has `.pressed` (held), `.down` (went down since the last sample) and `.up` (went up). On a device, `.pressed` means held at any point since the last sample, so a quick tap between ticks is never lost. A match that starts from a menu doesn't read what was pressed there: its first tick gets what's held as it starts. - **Keyboard:** every key by its position, named after the US layout, so `WASD` is in the same place on AZERTY: - `a` to `z`, and `digit0` to `digit9` - `space`, `enter`, `escape`, `tab`, `backspace` - `insert`, `delete`, `home`, `end`, `pageUp`, `pageDown` - `upArrow`, `downArrow`, `leftArrow`, `rightArrow` - `leftShift`, `rightShift`, `leftCtrl`, `rightCtrl`, `leftAlt`, `rightAlt`, `capsLock` - `f1` to `f12` - `minus`, `equals`, `leftBracket`, `rightBracket`, `backslash`, `semicolon`, `quote`, `comma`, `period`, `slash`, `backquote` - `numpad0` to `numpad9`, `numpadEnter`, `numpadPlus`, `numpadMinus`, `numpadMultiply`, `numpadDivide`, `numpadPeriod` - `text`, a `string`: what was typed since the last frame, which views read (see [Typed text](#doc-game--input--typed-text)) - **Mouse:** `position`, `delta` and `scroll` (`float2`), and the buttons `left`, `right`, `middle`, `back` and `forward`. `position` is in window pixels from the bottom left, with `y` up, as a touch's and the pointer's are; in a view, `Screen.Flip(position)` gives it from the top left, as the screen and the GUI count (see [Screen and world coordinates](#doc-game--cameras--screen-and-world-coordinates)). While the cursor is [locked](#doc-game--input--locking-the-cursor), `position` stays where it was and `delta` is the mouse's own movement. - **Gamepad:** `connected`, `leftStick` and `rightStick` (`float2`), `leftTrigger` and `rightTrigger` (0 to 1), the face buttons by position (`buttonSouth`, `buttonEast`, `buttonWest`, `buttonNorth`, which is A, B, X and Y on Xbox), `dpad.up` and the other directions, `leftShoulder`, `rightShoulder`, `leftStickButton`, `rightStickButton`, `start` and `select`. - **Touchscreen:** `connected`, `primaryTouch`, and `touches`, a slot for each of 10 fingers. Each `Touch` has: - `press`, a button: `.down` when the finger touched, and `.up` when it lifted - `id`, the same while the finger touches, and a new one for each touch - `position`, `delta` and `startPosition` (`float2`) - **Pointer:** `position`, `delta` and `press`: the mouse, with its left button, or the primary touch, whichever was used last. Once a finger lifts, the pointer stays where it lifted, until another finger touches or the mouse is used. Each part has a type of its own: `Keyboard`, `Mouse`, `Gamepad`, `Dpad`, `Touchscreen`, `Touch`, `Pointer` and `Button`. Functions take them, and `Devices`, as parameters to read: ```csharp float2 Steer(Gamepad pad) { return pad.leftStick + float2(pad.dpad.right.pressed ? 1 : 0, 0); } ``` Axes follow Unity: `y` is positive up, for sticks, the mouse, touches and the pointer, and `scroll.y` is positive scrolling away from you. ### Touch A finger keeps its slot in `touches` while it touches, and lifts out of it. With ten fingers on the screen, an eleventh is left out. `primaryTouch` is the finger that touched while no other was the primary one, until it lifts: the one to follow for a single finger. A finger that touches and lifts between two samples reads as held for one, like a quick key press, so no tap is lost. `touches[i]` is the touch in slot `i` (an empty one past the last), `touches.count` is how many slots there are, and `foreach` goes through every slot, touching or not: ```csharp mut var fingers = 0; foreach (var touch in devices.touchscreen.touches) { if (touch.press.pressed) fingers += 1; } ``` A finger is never the mouse, as in Unity's Input System: the mouse only sees mice. Code that should work with both reads the **pointer**, which follows the mouse or the primary touch, whichever was used last, as Unity's `Pointer.current` does. The GUI follows it too, so buttons work with a finger. ```csharp input Brush { [Absolute] int x; [Absolute] int y; bool paint; // Cells of 16 pixels, under the mouse or a finger Sample(Devices devices) { var pointer = devices.pointer; x = int(Math.Floor(pointer.position.x / 16)); y = int(Math.Floor(pointer.position.y / 16)); paint = pointer.press.pressed; } } ``` Touches come from Android, the web on phones and desktops, and touchscreens on Windows and Linux, a Steam Deck's among them. On Linux they're X11's touch events, which XWayland has too; on a Steam Deck, Steam may make a mouse of the screen's touches itself unless the game is set to take them as touches. Native iOS support isn't built yet, and a Mac has no touchscreen. A browser on any desktop can still report touches. Where no touchscreen is available, `connected` is false and no finger ever touches. The cell coordinates above are `[Absolute]` because a prediction should keep the last cell the player pointed at, even after it guesses they stopped painting. Try a mouse, then a finger in the example below. The amber ring is the pointer; teal circles are individual touches, with lines back to where each started. A touch leaves the mouse where it was, and lifting it leaves the pointer where it ended. The ten slots show which fingers are still held. Click or tap the frame first so swipes go to the example. **The pointer and individual fingers** ([Run example](https://tide-engine.dev/examples/pointer/?stats)) ```tide settings { title = "Pointer and touch"; } local scene Main { } // Device inspection needs no match local singleton Trace { int presses; float flash; float2 last; string edge = "Move the pointer, then press"; } view Inspect(Devices devices, mut Trace trace) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); var quiet = Color(0.64, 0.64, 0.68); var amber = Color(0.98, 0.75, 0.14); var teal = Color(0.18, 0.83, 0.75); var pointer = devices.pointer; var at = Screen.Flip(pointer.position); // Devices count from the bottom left trace.flash = Math.Max(0, trace.flash - Frame.dt); if (pointer.press.down) { trace.presses += 1; trace.last = at; trace.flash = 0.7; trace.edge = "down: the press began"; } if (pointer.press.up) trace.edge = "up: the press ended"; Draw.Text("Pointer and touch", float2(16, 14), 20, Color.white); Draw.Text($"held: {pointer.press.pressed} presses: {trace.presses}", float2(16, 44), 14, amber); Draw.Text(trace.edge, float2(16, 68), 13, quiet); // A touch never moves the mouse. Its outline stays at the mouse's position. Draw.WireCircle(Screen.Flip(devices.mouse.position), 9, 2, quiet); mut var held = 0; for (var i = 0; i < devices.touchscreen.touches.count; i++) { var touch = devices.touchscreen.touches[i]; var center = float2(16 + (i + 0.5) * (Screen.width - 32) / 10, Screen.height - 88); Draw.Circle(center, 10, touch.press.pressed ? teal : Color(0.24, 0.25, 0.27)); Draw.Text($"{i}", center, 12, Color.white, Anchor.MiddleCenter); if (!touch.press.pressed) continue; held += 1; var finger = Screen.Flip(touch.position); Draw.Line(Screen.Flip(touch.startPosition), finger, 2, teal); Draw.Circle(finger, 12, Color(teal.r, teal.g, teal.b, 0.3)); Draw.Text($"id {touch.id}", finger + float2(16, 0), 13, teal); } Draw.WireCircle(at, pointer.press.pressed ? 20 : 15, 3, amber); if (trace.flash > 0) Draw.WireCircle(trace.last, 20 + (0.7 - trace.flash) * 60, 2, Color(amber.r, amber.g, amber.b, trace.flash / 0.7)); Draw.Text($"{held} fingers held; slots 0 to 9", float2(16, Screen.height - 62), 13, quiet); Draw.Text("Amber: pointer Teal: touch Gray: mouse\nTap here first, then try dragging several fingers.", float2(16, Screen.height - 40), 12, quiet); } ``` ### Locking the cursor A camera that turns with the mouse locks the cursor: a view calls `Cursor.Lock()` every frame the game wants the mouse (see [Looking around](#doc-game--cameras--looking-around)). `Cursor.locked` is whether the window holds it right now, which the system decides, not the game: the cursor goes back to the player when they press Escape, and a window that loses the focus lets it go. `Sample` reads `Cursor.locked`, so the mouse only turns the camera while the cursor is locked, and moving it over a menu doesn't: ```csharp input PlayerInput { float2 look; Sample(Devices devices) { if (Cursor.locked) look = devices.mouse.delta * 0.003; } } ``` `Sample` can't call `Cursor.Lock()`: it runs once per tick, and the lock is asked for every frame, by views. The match can't read `Cursor.locked`, as it can't read anything of this machine's: put what it needs in the input, as `look` is here. ### Typed text `devices.keyboard.text` is what the player typed since the last frame, as a `string`. Unlike keys, it follows the keyboard's layout: on AZERTY, the key in the `q` position types `a`, and `text` says `a`. Shift, accents and a phone's keyboard are applied, and what's pasted with Ctrl+V comes through it too. Backspace, Enter and the arrows are keys, not characters. A text field of the GUI's reads it for you. Views read it themselves, and so do the functions they call, for a text box of their own, or to pass on to a library: ```csharp local singleton Chat { string line; } view Typing(Devices devices, mut Chat chat) { chat.line += devices.keyboard.text; if (devices.keyboard.backspace.down) chat.line = chat.line.Substring(0, chat.line.length - 1); } ``` It's a frame's, so `Sample` can't read it, and neither can the match: an input holds no text, and what's typed is never sent. It's empty while the GUI has the keyboard, as when the player types into a `TextField`, and in every view but the one whose [control](#doc-game--gui--widgets-of-your-own) has the focus, or that [claimed the keyboard](#doc-game--gui--widgets-that-read-the-devices-themselves). A long paste comes over a few frames, 32 characters in each. ### Devices in the match Match code can read devices too, with a `Devices` parameter: the devices of the player who owns the entity, like an input parameter. The input then sends what match code reads of them, and nothing else. A game can do without an `input` declaration this way: ```csharp system Hop(Devices devices, mut Velocity velocity) { if (devices.keyboard.space.down || devices.gamepad.buttonSouth.down) velocity.value.y = 5; } ``` Device access always takes a `Devices` parameter. `Sample` and views receive this machine's devices; match code receives the entity owner's, or the server's. A system takes at most one `Devices` parameter and one input parameter. Views can't read the input. Local event handlers and tasks can't take devices. The match can't read positions on the screen either, the mouse's, a touch's or the pointer's: they're in this machine's window, which the other machines don't have. Work out what the match needs from them in `Sample`, like an aim direction, and read that from the input. ## Input is an attack point Inputs come from other players' machines, so the engine doesn't trust them: - NaN and infinite floats and doubles become the field's default. Double fields retain their full 64 bits in input packets and deltas. - Fields can declare bounds, `[Clamp(lo, hi)]`, `[Min(x)]` and `[Max(x)]`, which the engine applies to every input. A number bounds every component of a vector. - Then the input's `Sanitize` method runs, if it has one, for what bounds can't say. ```csharp input PlayerInput { [Clamp(-1, 1)] float2 move; [Min(0), Max(3)] int gear = 1; bool boost; Sample(Devices devices) { move = devices.gamepad.leftStick; } // After the bounds: what attributes can't say. Sanitize() { if (gear == 0) boost = false; } } ``` Every input goes through these steps before the match reads it, including this machine's, so systems can rely on them without checking again. Devices are repaired the same way, since the engine knows their ranges. An input holds numbers, bools, chars, enums, vectors and structs of those; not text or lists. A match takes as many players as the game's `maxPlayers` setting says, 16 without one (see [Matches](#doc-multiplayer--matches--how-many-players)). ## Presented view time With `settings { maxRewind = 0.25; }`, your input gains `ViewTime viewTime`; do not declare this field yourself. It is read-only and stamped by the engine after `Sample`, from the last actually presented confirmed frame. `tick` names the upper endpoint, `alpha` its interpolation fraction, and `valid` is false before a frame is presented. Use it with [collider rewind](#doc-multiplayer--networking--collider-rewind); the server validates the wire value as an untrusted claim. --- Source: https://tide-engine.dev/game/views.md Draw a Tide game with views: the camera, shapes, colors, text and the screen's pixels, motion that's smooth between ticks, and a frame's length. # Views and drawing A **view** draws the game. It looks like a system and takes the same parameters, components and singletons, but it runs once per rendered frame instead of once per tick, and it never changes the match. It reads this machine's devices through a `Devices devices` parameter, and can't read the input (see [Input](#doc-game--input--devices-in-the-match)). ```csharp view DrawBalls(Body body, Ball ball) { Draw.Circle(body.position, body.radius, ball.color); } view DrawHud(Arena arena) { Draw.SetCamera(float2(0, 0), arena.halfSize.y); Draw.Text("fire: space", float2(-arena.halfSize.x, arena.halfSize.y), 18, Color.gray); } ``` Drawing is immediate mode: views record their drawing calls every frame. Views run after the frame's ticks, in the order they're declared, and later ones draw on top. `[Before]` and `[After]` order views among themselves, as they do systems. A frame can draw as much as it needs: shapes go to the GPU together, so tens of thousands of rects or circles a frame are cheap, on the web too. A view's `mut` parameters, `Spawn`, `Add`, `Remove`, `Destroy` and `Send` are all local: views can change this machine's own state, like particles or a menu, but not the match (see [Local state](#doc-game--local-state)). Only views, and the functions they call, can draw. For expensive preparation such as voxel meshing, start a local async function that awaits a [local worker](#doc-game--tasks--local-workers), and draw the last completed geometry while it works. A heavy calculation directly in a view blocks that frame. For see-through shapes, sprites and 3D meshes, see [Transparency](#doc-game--draw-settings--transparency): alpha controls opacity, and 3D also needs the right depth setting and draw order. Tap a circle to select it, then change the camera's size. The grid and circles use world coordinates; the heading and slider keep their size in screen pixels. Pointer picking uses `ScreenToWorld` with that frame's camera. **A view draws the world** ([Run example](https://tide-engine.dev/examples/views/?stats)) ```tide settings { title = "Views and coordinates"; maxPlayers = 1; } component Dot { float2 position; Color color; local bool selected; } local singleton CameraSettings { float size = 3; } scene Main { } event(Spawned) Setup(with Main) { Spawn(Dot { position = float2(-1.5, 0.6), color = Color(0.98, 0.75, 0.14) }); Spawn(Dot { position = float2(0, -0.6), color = Color(0.98, 0.44, 0.52) }); Spawn(Dot { position = float2(1.5, 0.6), color = Color(0.18, 0.83, 0.75) }); } // The camera applies to every view that draws after this one. view Background(CameraSettings camera) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), camera.size); for (var i = -6; i <= 6; i++) { Draw.Line(float2(i, -6), float2(i, 6), Color(0.15, 0.15, 0.17)); Draw.Line(float2(-6, i), float2(6, i), Color(0.15, 0.15, 0.17)); } Draw.Line(float2(-6, 0), float2(6, 0), Color(0.3, 0.3, 0.33)); Draw.Line(float2(0, -6), float2(0, 6), Color(0.3, 0.3, 0.33)); } // Run once for each Dot. Only selected, a local field, can change here. view Dots(mut Dot dot, Devices devices) { var pointer = devices.pointer; var screen = float2(pointer.position.x, Screen.height - pointer.position.y); var world = Draw.ScreenToWorld(screen); var hovered = Math.Length(world - dot.position) < 0.4; if (hovered && pointer.press.down) dot.selected = !dot.selected; Draw.Circle(dot.position, 0.32, dot.color); if (hovered || dot.selected) Draw.WireCircle(dot.position, 0.43, 0.035, Color.white); } view Pointer(Devices devices) { var pointer = devices.pointer; var screen = float2(pointer.position.x, Screen.height - pointer.position.y); var world = Draw.ScreenToWorld(screen); Draw.Line(world - float2(0.12, 0), world + float2(0.12, 0), Color.white); Draw.Line(world - float2(0, 0.12), world + float2(0, 0.12), Color.white); } // Screen-space text keeps its pixel size when the camera zooms. view Controls(mut CameraSettings camera) { Draw.SetScreen(); Draw.Text("Tap a circle to select it", float2(16, 14), 18, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Camera size", camera.size, 2.5, 4.5); } ``` Views can share [named phases](#doc-game--systems--named-phases) instead of depending on individual view names: ```csharp enum RenderStages { Prepare, Objects, Effects, UI } [Stage(RenderStages.Prepare)] view ClearScene() { Draw.Clear(Color.black); } [Stage(RenderStages.Objects)] view DrawBalls(Body body, Ball ball) { Draw.Circle(body.position, body.radius, ball.color); } [After(RenderStages.Objects), Before(RenderStages.UI)] view Effects() { ... } ``` An offset such as `[Stage(RenderStages.Objects, 10)]` runs later within `Objects`. `After(RenderStages.Objects)` waits until every view in that phase has run for all its entities, including views with offsets. This page has what a 2D game draws with: the draw functions, colors, shapes, the screen, text, and how a view sees time. The rest is on pages of its own: - [Views and the match](#doc-game--views-and-the-match): entities other than a view's own, the ones this machine's player owns, and what the server has confirmed. - [Draw settings](#doc-game--draw-settings): blending, tints, stencil, transforms and clipping, and what's see-through. - [Meshes and textures](#doc-game--meshes-and-textures): triangles, and the images they're drawn with. - [Drawing in 3D](#doc-game--3d): 3D meshes and primitives, depth, and which side of a triangle draws. - [Cameras and coordinates](#doc-game--cameras): between the screen and the world, a camera that turns with the mouse, projections, and cameras as matrices. - [Render targets](#doc-game--render-targets): drawing into an image, and post-processing. - [Frags and verts](#doc-game--shaders): code of the game's that runs on the GPU. ## Draw functions `Draw` draws into the window: shapes, text and 2D meshes, 3D meshes and primitives, with a 2D camera and a 3D camera of its own. The 2D and 3D forms of a function are told apart by their arguments: `Draw.Camera(center, size)` is the 2D camera and `Draw.Camera(position, rotation, fieldOfView)` the 3D one, `Draw.Mesh(vertices, indices)` draws a `List` where its vertices are and `Draw.Mesh(vertices, indices, transform)` a `List` in the world, and `Draw.WorldToScreen` takes a `float2` through the 2D camera or a `float3` through the 3D one. A [render target](#doc-game--render-targets) has the same functions as its methods; `Draw.Clear` clears the window and its depth, and `Draw.list` hands the frame's draw list to C. Positions and sizes are in world units, with `y` up. The camera maps them to the screen. | Function | What it draws | |---|---| | `Draw.Clear(color)` | Fills the screen | | `Draw.ClearDepth()` | Sets depth back and leaves the picture: 3D meshes drawn after are in front of everything before (see [3D](#doc-game--3d)) | | `Draw.SetCamera(center, size)` | Sets the camera for the calls after it: `center` is the world position at the middle of the screen, and `size` is half the visible height, like Unity's orthographic size. One of the [draw settings](#doc-game--draw-settings), like the rows that name them below | | `Draw.Circle(center, radius, color)` | A filled circle | | `Draw.WireCircle(center, radius, color)` | A circle's outline | | `Draw.Rect(center, size, color)` | A filled rectangle | | `Draw.WireRect(center, size, color)` | A rectangle's outline | | `Draw.Line(from, to, color)` | A line a pixel wide | | `Draw.Line(from, to, width, color)` | A line `width` thick, with round ends: the first of the [smooth shapes](#doc-game--views--smooth-shapes), as are the rows from here to `Draw.Shape` | | `Draw.WireRect(center, size, width, color)`, `Draw.WireCircle(center, radius, width, color)` | Outlines `width` thick | | `Draw.Rect(center, size, rotation, color)` | A rectangle turned about its center | | `Draw.RoundRect(center, size, radius, color)` | A rectangle with round corners. `RoundRect(center, size, radius, rotation, color)` turns it, and `WireRoundRect(center, size, radius, width, color)` is its outline | | `Draw.Ellipse(center, radii, color)` | An ellipse. `Ellipse(center, radii, rotation, color)` turns it, and `WireEllipse(center, radii, width, color)` is its outline | | `Draw.Arc(center, radius, start, sweep, width, color)` | Part of a ring | | `Draw.Shape(shape)` | A [`Shape`](#doc-game--views--the-general-shape): a fill from one color to another, an outline around a fill, an edge that fades | | `Draw.Rect(rect, radius, fill)`, `Draw.Shape(shape, fill)` | A shape [filled by a function](#doc-game--views--fills) of where in it each pixel is: a `Gradient`, or any `Func` | | `Draw.Shadow(rect, radius, size)` | A soft shadow under a box at `rect`, fading out over `size` pixels, a quarter of `size` lower: black at 0.4, or `Draw.Shadow(rect, radius, size, color)`. Draw it before the box | | `Draw.Text(text, position, size, color)` | Text, with `position` its top left corner and `size` its font size, the height of a line of it (see [Text](#doc-game--views--text)) | | `Draw.Text(text, position, size, color, anchor)` | Text with `position` another place of its box: `Anchor.MiddleCenter` centers it there | | `Draw.Text(text, position, size, color, font)` | Text in a font: `Font.Bold`, or one of the game's (see [Fonts](#doc-game--views--fonts)). An anchor goes before it: `Draw.Text(text, position, size, color, anchor, font)` | | `Draw.MeasureText(text, size)` | Nothing: it returns how big `Draw.Text` would draw the text, a `float2` of its width and height (see [Measuring text](#doc-game--views--measuring-text)). `MeasureText(text, size, font)` measures in a font | | `Draw.Mesh(vertices, indices)` | Triangles, with a color at each corner (see [Meshes](#doc-game--meshes-and-textures--meshes)) | | `Draw.Mesh(vertices, indices, texture)` | Triangles drawn with a texture, read as it says or with the filter and the wrap after it (see [Textures](#doc-game--meshes-and-textures--textures)) | | `Draw.Sprite(texture, center, size, color)` | A texture upright over a box, its top left at the box's top left, times `color` (white without one). `Sprite(texture, center, size, part, color)` draws the part of it a `Rect` of uvs covers, and a `rotation` before the color turns it (see [Sprites](#doc-game--meshes-and-textures--sprites)) | | `Draw.Blend(mode) { ... }` | How what's drawn in the block goes over what's there: added, multiplied, replaced (see [Blending](#doc-game--draw-settings--blending)) | | `Draw.Tint(color) { ... }` | Fades or colors what's drawn in the block (see [Tints](#doc-game--draw-settings--tints)) | | `Draw.Stencil(test, value, operation) { ... }` | What's drawn in the block is drawn only where a number kept for each pixel passes a test, and changes that number where it draws: masks, cut-outs, counting (see [Stencil](#doc-game--draw-settings--stencil)) | | `Draw.Transform(offset, rotation, scale) { ... }` | Moves, turns and scales what's drawn in the block (see [Transforms](#doc-game--draw-settings--transforms)) | | `Draw.Clip(rect) { ... }` | Only what's inside `rect` draws, in the block (see [Clipping](#doc-game--draw-settings--clipping)) | | `Draw.Screen() { ... }` | The calls in the block are in the screen's pixels, from the top left, with `y` down (see [On the screen](#doc-game--views--on-the-screen)) | | `Draw.SetCamera(position, rotation, fieldOfView)` | Sets the 3D camera for the 3D meshes after it (see [3D](#doc-game--3d)) | | `Draw.Depth(mode) { ... }` | What the 3D meshes drawn in the block do with depth: hide and are hidden, are only hidden, or neither (see [Depth](#doc-game--3d--depth)) | | `Draw.Cull(side) { ... }` | Which side of the triangles of the 3D meshes drawn in the block isn't drawn: the back, the front, or neither (see [Which side draws](#doc-game--3d--which-side-draws)) | | `Draw.Mesh(vertices, indices, transform)` | A 3D mesh, placed in the world by `transform`, with a texture, a filter and a wrap as a mesh's (see [3D](#doc-game--3d)) | | `Draw.Cube(center, size, color)` | A box with full widths `size.x`, `size.y` and `size.z` | | `Draw.Sphere(center, radius, color)` | A sphere | | `Draw.Cylinder(center, radius, height, color)` | A capped cylinder along its local `y` axis, with full `height` | | `Draw.Plane(center, size, color)` | A rectangle in the local `xz` plane, with full widths `size.x` and `size.y` | | `Draw.Instanced(vertices, indices, instances)` | One mesh for each instance in a list, 2D or 3D by its vertices, with optional textures and shaders (see [Instances from a list](#doc-game--shaders--instances-from-a-list)) | Each frame starts black, with the camera at the origin and one world unit per pixel. ## Colors `Color` has `r`, `g`, `b` and `a`, floats from 0 to 1, as in Unity. Its constructor takes scalars and vectors totaling 3 or 4 channels, in order, just as vector constructors do. `Color(r, g, b)`, `Color(uv.xy, 0)` and `Color(rgb)` have alpha 1; `Color(r, g, b, a)`, `Color(rgb, a)` and `Color(rgba)` set it. Ints and int vectors convert to floats. The constants are `Color.white`, `black`, `red`, `green`, `blue`, `yellow`, `cyan`, `magenta`, `gray` and `clear`. Components and singletons can hold colors. Colors add, subtract and multiply channel by channel, alpha too, and scale by a number: `tint * Color.red * 0.5`. `==` and `!=` compare two colors whole, every channel and alpha, as they do vectors ([Operators](#doc-language--math--operators)). `Math`'s component-by-component functions take them the same way: `Math.Lerp(a, b, t)` blends two colors, in a view or in a frag. A color's numbers are the display's own: `Color(0.5, 0.5, 0.5)` is the middle gray a paint program shows for 128, a PNG's pixels are drawn as the file has them, and colors blend and add as those numbers. Nothing is converted on the way in or out, and the screen performs no automatic color-space conversion. It's what sprites and UI want. It isn't how light adds up: two lamps of half don't make white's brightness, and a half-clear white over black is darker than half the light. A game that wants that uses [Linear image sampling](#doc-game--shaders--linear-light-color) for its color textures and works in light in a float target. For unmarked inputs, explicit conversion is also available: ```csharp // Colors and textures to light as they're read, in the frags that draw the scene Color paint = models.wood.Sample(vertex.uv); Color light = Math.ToLinear(paint); // The last pass, from the float target to the window: under 1 first, then back to the display's numbers frag Present(Vertex vertex, out Color color, Texture source) { Color lit = source.Sample(vertex.uv); color = Math.ToDisplay(Color(lit.r / (1 + lit.r), lit.g / (1 + lit.g), lit.b / (1 + lit.b))); } ``` `Math.ToLinear` and `Math.ToDisplay` take `float`, `float3` or `Color` on the CPU and GPU. They use the sRGB transfer curve, clamp RGB to [0, 1], map NaN to zero, and preserve a color's alpha. GPU results have the same rounding limits as other `Math` operations. The scene is drawn into a [`Format.Rgba16f`](#doc-game--render-targets--what-a-target-holds) target, where light adds up past 1, and `Draw.Blit(scene.color, Draw.window, Present)` shows it. Without the last step the picture is too dark between its lights and flat white where they meet. What's drawn after it, the GUI and text among it, is in the display's numbers as ever. `Color.none` is no color, for where one can be left out, like a [`Shape`](#doc-game--views--the-general-shape)'s second color. It isn't one to draw with: nothing shows. ## Smooth shapes `Rect`, `WireRect` and the `Line` without a width fill whole pixels: rects side by side leave no seam between them, and a line is a pixel wide wherever it lands. A circle's edge is smooth, and so are the edges of the shapes that follow, at any size and turned any way: ```csharp view Bar(Health health) { Draw.SetScreen(); var middle = float2(120, 40); Draw.RoundRect(middle, float2(200, 24), 12, Color(0, 0, 0, 0.6)); // A pill Draw.RoundRect(float2(22 + health.left * 98, 40), float2(health.left * 196, 20), 10, Color.red); Draw.WireRoundRect(middle, float2(200, 24), 12, 2, Color.white); // Its outline, 2 pixels thick Draw.Line(float2(20, 64), float2(220, 64), 3, Color.gray); Draw.Arc(float2(250, 40), 14, 0, Math.TAU * health.cooldown, 4, Color.yellow); // A ring that fills up } ``` - Lengths are in the units the calls are in, like positions: world units under the camera, pixels [on the screen](#doc-game--views--on-the-screen). That goes for sizes, radii and widths alike. - An outline is `width` thick and inside the shape's edge, so a wire shape is as big as the filled one. - A `radius` rounds a rectangle's corners, up to half its smaller side: that much makes a pill, or a circle of a square. - An ellipse takes its `radii`, half its width and half its height, as a circle takes its radius. - A thick line reaches half its width past both ends, which are round, so lines that meet at a point join without a gap. - Angles are in radians, from `+x` towards `+y`, as `Math.Atan2(y, x)` gives them: counterclockwise under the camera, where `y` goes up, and clockwise on the screen, where it goes down. A `rotation` turns a shape about its center. - `Arc` draws the part of a circle's outline from the angle `start` on for `sweep`, the other way round for a sweep under 0, and its ends are cut straight across. A `width` of the whole radius makes it a slice of a disc, and a sweep of a whole turn or more is the whole ring. - A size, radius or width that isn't above 0 draws nothing. The engine's own shaders draw these, so they take no `frag` or `vert`. For anything they don't draw, there's a [mesh](#doc-game--meshes-and-textures--meshes) and a [frag](#doc-game--shaders) of your own. Move the slider to fill the bar and ring and rotate the ellipse. The card uses `Shape` for its gradient, outline and soft shadow. **Smooth shapes** ([Run example](https://tide-engine.dev/examples/shapes/?stats)) ```tide settings { title = "Smooth shapes"; maxPlayers = 1; } scene Main { } local singleton ShapeSettings { float amount = 0.65; } view Shapes(ShapeSettings settings) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), 3.6); // A shadow and a card with a gradient, rounded corners and an outline. Draw.Shape(Shape { center = float2(-1.2, -0.08), size = float2(2, 2.6), radius = 0.2, color = Color(0, 0, 0, 0.6), soft = 0.3 }); Draw.Shape(Shape { center = float2(-1.2, 0), size = float2(2, 2.6), radius = 0.2, color = Color(0.22, 0.22, 0.25), color2 = Color(0.12, 0.12, 0.14), outline = 0.025, outlineColor = Color(0.36, 0.37, 0.41) }); // A pill-shaped bar fills with the slider's value. Draw.RoundRect(float2(-1.2, 0), float2(1.6, 0.28), 0.14, Color(0.086, 0.086, 0.094)); Draw.RoundRect(float2(-2 + settings.amount * 0.8, 0), float2(settings.amount * 1.6, 0.28), 0.14, Color(0.98, 0.75, 0.14)); Draw.WireRoundRect(float2(-1.2, 0), float2(1.6, 0.28), 0.14, 0.02, Color.white); // Outlines stay equally wide all the way around an ellipse. Draw.Shape(Shape { center = float2(1.2, 0.65), size = float2(1.7, 0.8), ellipse = true, rotation = settings.amount, color = Color(0.98, 0.44, 0.52), outline = 0.045, outlineColor = Color.white }); Draw.WireCircle(float2(1.2, -0.7), 0.5, 0.13, Color(0.24, 0.25, 0.27)); Draw.Arc(float2(1.2, -0.7), 0.5, 0, Math.TAU * settings.amount, 0.13, Color(0.18, 0.83, 0.75)); Draw.Line(float2(-2, -1.8), float2(2, -1.8), 0.08, Color(0.18, 0.83, 0.75)); } view Controls(mut ShapeSettings settings) { Draw.SetScreen(); Draw.Text("Shapes, gradients and outlines", float2(16, 14), 18, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Amount", settings.amount, 0, 1); } ``` Shapes of every kind drawn one after another go to the GPU together, in one draw call, in the order they're written, so thousands a frame are cheap. Text or a mesh between them starts another. ### The general shape Those calls are short for `Draw.Shape`, which takes everything a shape can have: For a rectangle already represented by a `Rect`, use `Draw.Rect(rect, color)`, `Draw.Rect(rect, radius, color)` or `Draw.Rect(rect, radii, color)`. All three have antialiased edges, including square corners. A `float4` gives the top-left, top-right, bottom-right and bottom-left radii; each is clamped to half the smaller side. Equal radii use the ordinary rounded-box path. These filled boxes need no GUI theme and work inside `GUI.Draw` as well as ordinary views. The center/size `Draw.Rect` overload keeps its whole-pixel behavior for seamless adjacent tiles. `Shape` continues to provide gradients, outlines and soft edges with a uniform corner radius. ```csharp struct Shape // Built in { float2 center; float2 size; // Its width and height float rotation; float radius; // Its corners' bool ellipse; // The ellipse that fits `size`, rather than a box Color color = Color.white; // Its fill... Color color2 = Color.none; // ...and its fill at its bottom, when it's another float outline; // How wide its outline is, inside its edge Color outlineColor = Color.white; float soft; // How far its edge fades } ``` ```csharp view Card(Deal deal) { Draw.SetScreen(); // A shadow first: a dark shape whose edge fades outwards Draw.Shape(Shape { center = deal.at + float2(0, 6), size = float2(180, 240), radius = 16, color = Color(0, 0, 0, 0.5), soft = 18 }); // The card: lighter at its top than at its bottom, with an outline Draw.Shape(Shape { center = deal.at, size = float2(180, 240), radius = 16, color = Color(0.16, 0.2, 0.34), color2 = Color(0.07, 0.09, 0.17), outline = 2, outlineColor = Color(0.5, 0.62, 0.8) }); } ``` - **`color2`** makes the fill go from `color` at the shape's top to `color2` at its bottom. Top and bottom are the shape's own, as it is before `rotation` turns it, and the top is the upper one on the screen whether `y` goes up or down. Left at `Color.none`, the fill is `color` all over. A fill that goes to a clear color fades out without getting darker on the way. - **`outline`** is an outline that wide in `outlineColor`, inside the edge, over the fill. - **`soft`** above 0 fades the edge outwards: the shape's color goes on past its edge and is gone `soft` further out, which is a glow in a light color and a shadow in a dark one. Under 0, it fades inwards from the edge instead and leaves the middle clear, like a vignette over the whole screen. At 0 the edge is sharp, smooth over one pixel. - **`ellipse`** makes it the ellipse that fits `size`, whatever `radius` says. `Arc` is the one call `Shape` doesn't cover. ### Fills A fill colors a shape by a function of where in it each pixel is: `Draw.Rect(rect, radius, fill)`, `Draw.Rect(rect, radii, fill)` with four corners, and `Draw.Shape(shape, fill)`, where `fill` is a `Func`. It runs on the GPU for each pixel, given the pixel's place in the shape from `(0, 0)` at its top left to `(1, 1)` at its bottom right. `Gradient`'s functions make the usual ones: ```csharp view Buttons() { Draw.SetScreen(); // Lighter at the top: a button that looks raised Draw.Rect(Rect(20, 20, 200, 48), 12, Gradient.Vertical(Color(0.35, 0.5, 0.9), Color(0.15, 0.25, 0.6))); // Three colors, left to right Draw.Rect(Rect(20, 80, 200, 48), 24, Gradient.Horizontal(Color.red, Color.yellow, Color.green)); // A glow: bright in the middle, clear at the edge Draw.Rect(Rect(240, 20, 108, 108), 54, Gradient.Radial(Color(1, 0.9, 0.5), Color.clear)); // Any function of the place: stripes Draw.Rect(Rect(20, 140, 200, 48), 8, (float2 uv) => int(uv.x * 8) % 2 == 0 ? Color.white : Color.gray); } ``` | Function | From, to | |---|---| | `Gradient.Vertical(top, bottom)` | The shape's top to its bottom | | `Gradient.Horizontal(left, right)` | Its left to its right | | `Gradient.Linear(angle, from, to)` | Across it at `angle`, in radians from `+x` towards `+y`, one corner to the opposite one | | `Gradient.Radial(inner, outer)` | Its middle out to the middle of its sides, and on to its corners | `color.WithAlpha(a)` is the color with another alpha, its red, green and blue as they are: a glow of an item's color, `rarity.WithAlpha(0.4)`. It works in a fill, and in any GPU code, too. `color.rgb` is its red, green and blue as a `float3`, for the math a light or a blend does on them: `Color(tint.rgb * shade, tint.a)`. It's read, never assigned, and works in GPU code. A `Rect` reads as vectors too: `rect.position` is its top left corner, `rect.size` its width and height and `rect.center` its middle, each a `float2`, so a label goes at `slot.center` with `Anchor.MiddleCenter`. `rect.Contains(point)` says whether a point is in it, like the pointer over a slot (its left and top edges are in, its right and bottom ones out, so slots side by side share no point), and `rect.Inset(amount)` is the rect with every edge moved in by that much, or out by an amount under 0: `Draw.Rect(slot.Inset(1), 4, fill)` inside a border. Each takes two, three or four colors, spread evenly: `Gradient.Vertical(a, b, c)` is `b` at the middle. Colors blend with their alpha, so a gradient to `Color.clear` fades without darkening. - **A fill is a value.** Keep one in a field, pass it to a helper, or write your own: a function `Color Name(float2 uv)` named where a fill goes, or a lambda, which can use the variables around it: `Draw.Rect(rect, 8, (float2 uv) => tint * (1 - uv.y * 0.3))`. Calling one on the CPU gives the color a pixel there gets. - **A fill can take the shape's size too:** a `Func`, given the place and the shape's size in the units it's drawn in (pixels on the screen), for patterns of a fixed size whatever the shape's: `Draw.Rect(bar, 6, (float2 uv, float2 size) => int(uv.x * size.x / 12) % 2 == 0 ? light : dark)` has stripes 12 pixels wide. - **The rest of the shape is as ever.** `Draw.Shape(shape, fill)` takes its center, size, rotation, corners, outline, soft edge and ellipse from `shape`, and the fill replaces `color` and `color2`. Its place in the shape is the shape's own, before `rotation` turns it, and its top is the upper one on the screen whether `y` goes up or down. - **Fills drawn one after another are drawn together,** whatever their functions: a menu of gradient buttons costs one draw. The function is GPU code, with [what the GPU runs](#doc-game--shaders--what-the-gpu-runs)' rules. - **They're local code.** A fill is drawn by views and the functions they call, in the window or inside [`GUI.Draw`](#doc-game--gui--custom-controls-in-layout). A [render target](#doc-game--render-targets)'s own `Rect` and `Shape` take one too, drawn by the target's size: `card.Rect(Rect(0, 0, 200, 60), 12, Gradient.Vertical(top, bottom))`. ## On the screen In `Draw.Screen() { ... }`, Draw calls are in the screen's pixels: from the top left, with `y` down, as the GUI's are, `Screen.width` by `Screen.height`. After the block, the camera is what it was, so a view of the world can draw a label in pixels and leave the world's camera alone for the views after it: ```csharp view Nameplates(Player player, Body body) { var above = Draw.WorldToScreen(body.position + float2(0, 1.5)); Draw.Screen() { var size = Draw.MeasureText(player.name, 14); Draw.Text(player.name, above - float2(size.x * 0.5, size.y), 14, Color.white); } } ``` A view that only draws on the screen can set it for the views that follow instead, with `Draw.SetScreen()`: ```csharp view Health(Stats stats) { Draw.SetScreen(); Draw.Rect(float2(110, 30), float2(200, 20), Color.gray); Draw.Rect(float2(10 + stats.health, 30), float2(stats.health * 2, 20), Color.red); } ``` `Draw.SetCamera` goes back to the world. What views draw on the screen is under the GUI's widgets, which draw last. The mouse, touches and the pointer count pixels from the bottom left instead, with `y` up. `Screen.Flip(devices.pointer.position)` is where the pointer is in the screen's pixels: see [Screen and world coordinates](#doc-game--cameras--screen-and-world-coordinates). ## Text `Draw.Text(text, position, size, color)` draws text in the engine's font. Its `size` is its font size, as CSS's and Unity's: the height of a line of it, with its capitals in the line's middle. A newline in the text starts another line under it. Text is fitted to the display's pixels, so it's sharp at the sizes it's read at. ### Anchors Without more, `position` is the text's top left corner. An `Anchor` after the color says which place of the text's box it is instead, the nine of Unity's `TextAnchor`: `UpperLeft`, `UpperCenter`, `UpperRight`, `MiddleLeft`, `MiddleCenter`, `MiddleRight`, `LowerLeft`, `LowerCenter` and `LowerRight`. ```csharp view Banner(Round round) { Draw.SetScreen(); var middle = float2(Screen.width, Screen.height) * 0.5; Draw.Text("FIGHT!", middle, 64, Color.white, Anchor.MiddleCenter); Draw.Text($"Round {round.number}", float2(Screen.width - 16, 16), 24, Color.gray, Anchor.UpperRight); } ``` That's a word in the middle of the screen, and the round's number against its top right corner, wherever the window's edges are and however wide the text comes out. The box is as wide as the text's widest line and as tall as its lines. Upper is towards the top of the screen, whether the calls are in the world, where `y` goes up, or in the screen's pixels, where it goes down: a name over a body is `Draw.Text(player.name, body.position + float2(0, 1), 0.5, Color.white, Anchor.LowerCenter)` under any camera. Text of several lines lines up on the anchor's side: its lines start together at a left anchor, end together at a right one, and are centered on one between. ### Bold The font has two weights. `Font.Bold`, last in the call, draws text in the font's own bold: ```csharp Draw.Text("DUEL", at, 88, Color.white, Font.Bold); Draw.Text("DUEL", at, 88, Color.white, Anchor.MiddleCenter, Font.Bold); ``` `Font.Regular` is the weight text has without one. A `Font` is a value, so a function can take one and pass it on, and `.Bold` and `.Regular` name the two where a `Font` goes. Bold is a second font file, and a game only carries it when its code says `Font.Bold`: about 95 KB more in the program, and nothing for a game that never does. Its strokes are a whole number of pixels thick, as the regular weight's are, so text stays sharp. At the smallest sizes, under 13 of the display's pixels, that's one pixel in both weights: bold is for text of about that size and up, and for titles. A letter the bold weight doesn't have (it covers Latin, Greek and Cyrillic, less widely than the regular one) is drawn in the regular weight. The GUI's widgets are in the regular weight, unless their [theme](#doc-game--gui--themes) says another font. ### Fonts A game can have fonts of its own, as many as it likes, each drawn wherever a call names it. A font file is an asset: ```csharp asset Font title = "fonts/Title.ttf"; asset Map fonts = "fonts/*.ttf"; view Hud(Round round) { Draw.Text("ROUND 3", float2(40, 40), 64, Color.white, title); Draw.Text(round.message, float2(40, 120), 20, Color.white, fonts["fonts/Body.ttf"]); } ``` A `Font` asset is a TrueType font: a `.ttf`, an `.otf` of TrueType outlines, or the first font of a `.ttc`. Many `.otf` files have CFF (PostScript) outlines instead, which aren't read: the build says so, and a font tool converts one to `.ttf`. A file that isn't a font it can read is an error where it's declared. A font that comes as the game runs, a player's file or one fetched from the web, is decoded from its bytes in local code: ```csharp local singleton Chat { Font font; bool loaded; } view Load(mut Chat chat, ChatSettings settings) { if (chat.loaded) return; chat.font = Font.Decode(settings.fontBytes)!; chat.loaded = true; } ``` `Font.Decode` fails with `IOError.InvalidData` for bytes that aren't such a font. It reads every file with the engine's own reader, which checks every place a file names before it reads anything there, so a broken or hostile file can't make the game read or write outside it. A file past its limits (64 MiB, or more glyphs and outlines than any font has) is refused too. Decoding the same bytes again gives the same font, at no cost. A `Font` is this machine's, as a `Texture` is: views, local handlers and local tasks hold one, and the match doesn't. A font every player should see goes into the match as bytes, a `List` field, which each machine decodes. A character a font has no glyph for is drawn in `Font.Regular`. Every font is fitted to the display's pixels as the engine's is, so text in it is sharp; hints and kerning in the file aren't read. ### Measuring text To fit a panel around a text, or to put something beside it, ask how big it will be: `Draw.MeasureText(text, size)` returns a `float2`, the width of the text's widest line in `x` and the height of its lines in `y`. One line is `size` high, and each newline adds a line. It's the box an anchor names a place of. ```csharp view Banner(Round round) { Draw.SetScreen(); var middle = float2(Screen.width, Screen.height) * 0.5; var size = Draw.MeasureText(round.message, 48, Font.Bold); Draw.Rect(middle, size + float2(32, 16), Color.black); Draw.Text(round.message, middle, 48, Color.white, Anchor.MiddleCenter, Font.Bold); } ``` That's the message in the middle of the screen, on a panel that fits it. Bold text is wider than regular, so it's measured in its weight: `Draw.MeasureText(text, size, Font.Bold)`, as text in any font is measured in it. Below, the cross is the position the text is given, and the frame is the box `MeasureText` says it has. Move the anchor's slider to put another place of the box on the cross, and change the size and the weight to see the box follow. **Anchors, sizes and weights** ([Run example](https://tide-engine.dev/examples/text/?stats)) ```tide settings { title = "Text"; } local scene Main { } local singleton Label { string words = "Tide\nfits text to pixels"; float size = 26; int anchor = 4; // Anchor.MiddleCenter bool bold; } view Show(mut Label label) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); var at = float2(Screen.width * 0.5, Screen.height * 0.3); var anchor = Anchor(label.anchor); var font = label.bold ? Font.Bold : Font.Regular; // The box MeasureText gives is the one an anchor names a place of. var size = Draw.MeasureText(label.words, label.size, font); var corner = at - float2(size.x * (label.anchor % 3) * 0.5, size.y * (label.anchor / 3) * 0.5); Draw.WireRect(corner + size * 0.5, size, Color(0.3, 0.3, 0.33)); Draw.Text(label.words, at, label.size, Color.white, anchor, font); // The position the text was given. Draw.Line(at - float2(10, 0), at + float2(10, 0), 2, Color(0.98, 0.75, 0.14)); Draw.Line(at - float2(0, 10), at + float2(0, 10), 2, Color(0.98, 0.75, 0.14)); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 178, Screen.width - 24, 166)) { GUILayout.Label($"Anchor.{anchor}: {size.x:F0} by {size.y:F0} pixels"); GUILayout.IntSlider("Anchor", label.anchor, 0, 8); GUILayout.Slider("Size", label.size, 10, 56); GUILayout.Toggle("Font.Bold", label.bold); } } ``` The answer is in the units the Draw calls are in: pixels on the screen, and the world's under a camera. It's what `Draw.Text` would draw at that point of the view, to the pixel. Text is fitted to the display's pixels to stay sharp, so the same text can come out a little wider or narrower on another display, under another camera or in a window of another size: measure where you draw, each frame, rather than keeping the answer. A [render target](#doc-game--render-targets) has its own camera, and pixels of its own to fit text to, so `target.MeasureText(text, size)` measures for it. ## Smooth at any tick rate Views draw at whatever frame rate the game renders, not the tick rate, and see the match blended between its last two ticks. So motion is smooth even at 20 ticks per second, at the cost of drawing up to a tick late. Every float, vector, quaternion and color a view reads of the match is blended, `Time.t` among them. Ints, bools, enums, entities and text come from the upper endpoint. An entity that wasn't there at the previous endpoint is drawn as it is. What a view reads [`verified`](#doc-game--views-and-the-match--confirmed-state) blends on a separate confirmed clock, which holds at the latest confirmation and never extrapolates. The match below ticks only five times a second. Both discs are the same position: the amber one is an ordinary field, which the view sees blended between ticks, and the teal one a `[Snap]` field, drawn as the last tick left it. **Five ticks a second, drawn every frame** ([Run example](https://tide-engine.dev/examples/tick-rate/?stats)) ```tide settings { title = "Tick rate"; tickRate = 5; maxPlayers = 1; } // Five ticks a second component Mover { float angle; float2 position; // A view sees it blended between the last two ticks [Snap] float2 stepped; // Kept out of blending: as the last tick left it } scene Main { } event(Spawned) Setup(with Main) { Spawn(Mover { position = float2(1.3, 0), stepped = float2(1.3, 0) }); } // The match only moves five times a second. system Orbit(mut Mover mover, Time time) { mover.angle += time.dt * 1.6; mover.position = float2(Math.Cos(mover.angle), Math.Sin(mover.angle)) * 1.3; mover.stepped = mover.position; } // Views run every frame, and draw the same match. view Show(Mover mover, Time time) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, -0.1), 2.2); Draw.WireCircle(float2(0), 1.3, 0.02, Color(0.24, 0.25, 0.27)); Draw.Circle(mover.stepped, 0.2, Color(0.18, 0.83, 0.75)); Draw.Circle(mover.position, 0.14, Color(0.98, 0.75, 0.14)); Draw.SetScreen(); Draw.Text($"tick {time.tick}, at {time.tickRate} ticks a second", float2(16, 14), 18, Color.white); Draw.Text("float2 position: blended", float2(16, Screen.height - 50), 14, Color(0.98, 0.75, 0.14)); Draw.Text("[Snap] float2 stepped: as the tick left it", float2(16, Screen.height - 30), 14, Color(0.18, 0.83, 0.75)); } ``` `[Snap]` keeps a field out of blending, for angles that wrap and values that jump: ```csharp component Body { float2 position; // Blended [Snap] float heading; // Wraps from 360 to 0: as it is int lives; // Ints are as they are } ``` ### Jumps Something that jumps, like a respawn, a portal or a camera cut, says so from match code: `entity.Snap()` or `singleton.Snap()`. For the tick it happens in, views draw it as it is, instead of sliding from where it was. ```csharp event(Died dead) Respawn(mut Body body, Arena arena) { body.position = arena.start; this.Snap(); // No sliding from where it died } ``` `entity.Snap()` is applied at the end of the tick, like `Destroy`, so it never makes systems wait. `singleton.Snap()` needs the singleton as a `mut` parameter. A single field can jump too: `field.Snap()` is the per-field counterpart of `entity.Snap()`. For the tick it happens in, views draw that field as it is at the newer tick, and from the next tick it blends again. The rest of its component or singleton keeps blending, so a position doesn't stutter. Use it whenever a float starts over together with something that doesn't blend. Here a stance is an enum, so views see the new stance at once, and `since` counts the seconds in it: ```csharp component Fighter { Stance stance; float since; // Seconds in this stance float3 hand; mut void Enter(Stance next) { stance = next; since = 0; since.Snap(); // Drawn from 0 with the new stance } } ``` **Warning: A timer that starts over** Without `since.Snap()`, every frame between the two ticks shows the new stance with `since` blended between its old value and 0: a timer running backwards, which pops whatever the view works out from it. `[Snap]` on the field would avoid it, but then `since` never blends, and `this.Snap()` stops the whole entity blending, position included. `field.Snap()` goes on a field of a match component or singleton that views blend, wherever code may write that field: systems, match event handlers, and the functions and methods they pass it to. A field that holds a struct snaps all of it, as in `arm.pose.Snap()`; a struct's own field can't snap alone. Each field that snaps keeps a count of its snaps beside it in the match, so snapshots, rollback and host migration carry it, and it is part of the match hash. ### Provisional correction smoothing **Warning: Provisional** `[Position]` and `[Rotation]` are available, with provisional names and behavior. They may change as games test them. Tick interpolation makes motion smooth between ticks. A prediction correction can still move the next frame abruptly. These attributes tell Tide how to preserve the displayed value and remove the correction error over time: ```csharp component Body { [Position] float2 position; [Rotation] float heading; // Radians, for 2D float2 velocity; // Ordinary tick interpolation } ``` `[Position]` accepts `float`, `double` and their vector types. It keeps linear tick interpolation and accumulates an additive presentation offset in the field's own precision. Double positions and correction errors remain double, preserving small offsets at large world coordinates. `[Rotation]` on a float uses the shortest wrapped angular difference, in radians. On a quaternion it uses the shortest relative rotation, for both tick interpolation and correction smoothing. For a game with its own large-world transform, the same attribute works on double coordinates: ```csharp component WorldPosition { [Position] double3 position; } ``` This smooths the value views read. Convert to rendering coordinates after subtracting the camera position in double precision; the drawing APIs still take floats. The error decays exponentially with frame time toward zero, or the identity rotation, with a provisional half-life of 75 ms. Another correction accumulates with whatever error remains. Ordinary movement follows the corrected simulation, so moving and aiming stay responsive. Untagged fields keep ordinary tick interpolation. The built-in `Transform` already uses this behavior for its match fields: `localPosition` is a `[Position]` and `localRotation` a `[Rotation]`. Its scale uses ordinary tick interpolation. These defaults apply to view bindings; `World.LocalToWorld` and other stored-state queries retain their existing behavior. Local-entity Transforms read their current values. This state belongs to this machine's presentation. Simulation values and collisions correct immediately, and snapshots, hashes and network state are unaffected. `entity.Snap()` and `singleton.Snap()` also clear any accumulated error, keeping intentional jumps immediate. A new match, a hot reload or a replacement world with no comparable presentation history clears the error too. While a host migration reconnects, the frozen presentation retains its error; adopting the new network timeline clears it. The tags take no arguments. Use them on match fields; local state, inputs and events cannot carry them. A field cannot combine `[Position]`, `[Rotation]` and `[Snap]`, and such a field can't snap alone with `field.Snap()`: snap its entity or singleton, which clears its error too. Ordinary structs can contain annotated built-in fields, including through nested structs. Correction smoothing for a type with its own `Interpolate` is deferred; its existing tick interpolation remains available. No new custom-type method or correction-rate setting is agreed. The [specification](https://tide-engine.dev/spec.md#provisional-correction-smoothing) records the provisional contract. ### Blending your own way A struct or component can say how it blends with an `Interpolate` method, declared in it like an operator. It replaces the default blend for that type wherever views see it: ```csharp struct Angle { float degrees; Angle Interpolate(Angle from, Angle to, float t) { mut var d = to.degrees - from.degrees; if (d > 180) d -= 360; if (d < -180) d += 360; return Angle { degrees = from.degrees + d * t }; } } component Body { float2 position; // Blended as usual Angle heading; // Blended the short way round } ``` `Interpolate` isn't for code to call. Custom interpolation is declared on structs or components; a singleton blends its own way through a struct in it that has one. ## A frame's length Frames come at the display's rate: 60 a second on one screen, 144 on another, fewer when the machine is busy. What a view animates of its own, like particles, a menu that slides in or a camera's shake, moves by time rather than by frames. `Frame.dt` is the seconds since the previous frame started: ```csharp struct Spark { float2 position; float2 velocity; float age; float life = 0.4; } local singleton Sparks { List list; } view DrawSparks(mut Sparks sparks) { mut var i = 0; while (i < sparks.list.count) { mut var spark = sparks.list[i]; spark.age += Frame.dt; if (spark.age >= spark.life) { sparks.list.RemoveAt(i); continue; } spark.velocity.y -= 9.8 * Frame.dt; spark.position += spark.velocity * Frame.dt; sparks.list[i] = spark; Draw.Circle(spark.position, 0.1 * (1 - spark.age / spark.life), Color.yellow); i++; } } ``` - **It's this machine's, not the match's.** It's there with no match, in a menu and while connecting, where a view that takes `Time` doesn't run. In a match it's the same value, whatever the tick rate. - **The match has `Time`.** What's in the match moves by `time.dt`, a tick's length, in systems. A view draws the match as it is, already [blended](#doc-game--views--smooth-at-any-tick-rate) to the frame, and uses `Frame.dt` for what it adds on top. A system that reads `Frame.dt` is an error that says so. - **It's the frame's real length.** A frame after the window was dragged, or the page was hidden, is as long as that took. Clamp it where a big step would show: `var dt = Math.Min(Frame.dt, 0.05);`. - **There's no clock beside it.** No `Frame.time`: code that asks `Frame` for one is an error that says what to write. A float of seconds gets coarser as it grows: after four and a half hours it counts in steps of 2 milliseconds, and whatever it animates starts to judder. Keep a clock of your own instead, in [local state](#doc-game--local-state): add `Frame.dt` up into a field, and wrap it where what it drives repeats: ```csharp local singleton Spinner { float turn; // Radians, always under a full turn } view Spin(mut Spinner spinner) { spinner.turn += Frame.dt * 4; if (spinner.turn > Math.TAU) spinner.turn -= Math.TAU; Draw.Circle(float2(Math.Cos(spinner.turn), Math.Sin(spinner.turn)), 0.1, Color.white); } ``` What moves with the match, the same for every player, reads the match's time instead: a view takes `Time time` and reads `time.t`, [the seconds since the match started](#doc-game--entities--singletons), which it sees move every frame. Views read `Frame.dt`, and so does the rest of [local code](#doc-game--local-state--time): the functions they call, local handlers and local tasks. ## Reading this machine's devices Views take `Devices devices` to read this machine's input devices for the frame: `.down` and `.up` since the last frame, and the `delta` of the mouse, touches and the pointer, and the mouse's `scroll`, too. A view that wants the mouse for itself [locks the cursor](#doc-game--cameras--looking-around). What the GUI is using is hidden from them, and so is what another view [claimed](#doc-game--gui--widgets-of-your-own) for widgets of its own. They read [what's typed](#doc-game--input--typed-text) too, as `devices.keyboard.text`. Helpers take the devices or a part of them as an explicit parameter. A helper that reads `keyboard.text` needs the frame, so only views and the functions they call can call it. --- Source: https://tide-engine.dev/game/views-and-the-match.md What a Tide view reads of the match: other entities through a query, this machine's player's own with ownership filters, and what the server has confirmed with verified. # Views and the match A [view](#doc-game--views) runs for the entities its parameters pick, and reads the match as this machine predicts it, [blended](#doc-game--views--smooth-at-any-tick-rate) between its last two ticks. This page is what else it reads: entities other than its own, the ones this machine's player owns, and what the server has confirmed. ## Other entities A view runs for its own entities, and often needs the others too: a shadow falls on the highest platform under a fighter, an aim line ends at whoever it would hit. A `query` parameter is that second set, as in a [system](#doc-game--systems--another-set-of-entities): ```csharp // A fighter's shadow falls on the highest platform under it. view DrawFighter(Body body, with Fighter, query (Platform box) platforms) { mut var ground = -10000.0; foreach (var entry in platforms) { var top = entry.box.center.y + entry.box.half.y; var over = Math.Abs(body.position.x - entry.box.center.x) < entry.box.half.x; if (over && top <= body.position.y && top > ground) ground = top; } Draw.Ellipse(float2(body.position.x, ground), float2(body.radius, 2), Color(0, 0, 0, 0.5)); Draw.Circle(body.position, body.radius, Color.white); } ``` The view's own parameters still pick the entities it runs for, and the query picks the ones it goes through for each: neither filters the other. Inside the `foreach`, `entry.box` is that platform's `Platform`, to read, and `entry.entity` is its handle. The syntax and the filters are a system's: bindings, `with` and `without`. A view with only queries runs once a frame. - **Rows are what the view sees.** They're [blended](#doc-game--views--smooth-at-any-tick-rate) between the last two ticks like the view's own parameters, with corrections smoothed the same way: the row of the view's own entity has the values its parameters have. An entity that wasn't there last tick is as it is, and one that's gone is in no row. - **`verified` works in a query** as it does on a view's own parameters (see [Confirmed state](#doc-game--views-and-the-match--confirmed-state)). `query (verified Health health) confirmed` goes through the confirmed world's entities, at the upper endpoint of its confirmed presentation interval. A query with bindings or filters of both worlds, `query (Body body, verified Health sure) both`, takes the entities that are in both: the same entity, and not only the same handle. `with verified Dead` and `without verified Dead` filter there too. - **A query is all the match's or all this machine's.** A view goes through local entities too, like its own sparks: `query (Spark spark) sparks`. Those are as they are now, with what views earlier in the frame wrote, and `entry.entity` is a `LocalEntity`. - **Match fields remain read-only.** A row can also read the entity's current [local fields](#doc-game--local-state--local-fields). Use `query (mut Fighter fighter) fighters` to write those local fields; the component's match fields and the row's entity handle stay read-only. This works with verified bindings too: local fields always use current local state. Queries over local-world components still have read-only bindings. - **A view that queries the match only runs in a match**, like any view that reads it. What should go on outside one stays in a view of its own. - **Going through a lot stays cheap.** A query's rows are made once a frame, however many entities the view runs for: a view over thousands of entities that goes through thousands of others blends those others once, not once for each. The rest is as in a system: queries are iterated directly or [borrowed by synchronous helpers](#doc-language--functions--borrowing-a-query), which keep the view's blended or verified data. Queries and whole rows can't be stored or returned, and whole rows can't be passed on; a component value like `entry.box` can. The order is the ECS's, not by distance or by entity ID. The editor says what a view's queries read above the view and on hover, as it does for a system. For example, mark the presentation of every dead fighter: ```csharp component Fighter { int health; local float flash; } view MarkDead(query (mut Fighter fighter) fighters) { foreach (var row in fighters) if (row.fighter.health <= 0) row.fighter.flash = 1; } ``` Passing `row.fighter` directly to a helper retains its local fields and the binding's write permission. Copying it into an ordinary variable copies only match data. A helper can borrow the whole query with a mutable binding when the source binding is mutable. A view takes a `World` as a system does, to read another entity's component by its handle: `world.Get(follower.leader)` (see [Other entities](#doc-game--systems--other-entities-the-world)). It reads the match through it and never changes it, and what it gets is the component as of the latest tick, not blended between ticks. ## Your own entities "My camera, my HUD, my health bar" is in every multiplayer game, so views have a filter for it. `with ownership` picks the entities this machine's player owns, and `without ownership` every other one: ```csharp view RenderGame(Player player, with ownership) { Draw.SetCamera(player.pos, player.rot, 75); } // Everyone else's body: a first-person camera doesn't draw its own view Bodies(Player player, Scenery scenery, without ownership) { Draw.Mesh(scenery.crate, scenery.faces, float4x4.TRS(player.pos, player.rot, float3(1)), scenery.wood); } ``` - `with ownership`: the entity has an [`Owner`](#doc-game--input--who-gets-which-input), and its `player` is `Session.player`, this machine's player. - `without ownership`: every other entity the view's parameters admit, which is another player's and those with no `Owner`. With `with Owner` beside it, only those whose owner is someone else. They're filters, beside `with` and `without`: the view takes neither `Owner` nor `Session` for them, and `if (owner.player != session.player) return;` goes. A view that wants both kinds at once, like one that draws your player yellow and the others gray, still takes `Owner` and `Session` and compares. Views have them, and so do [command handlers](#doc-game--commands--only-the-sender-s-own-entities), where the player is the command's sender. The rest of the match runs the same on every machine, so a system can't ask whose machine it's on: there it's an error, and `with Owner` picks the entities that any player owns. A local handler doesn't filter by them either: one of a match event takes `Owner owner` and `Session session`, and compares (see [Events](#doc-game--events--what-isn-t-there-yet)). `ownership` is a keyword only right after `with` and `without`, so it still names anything else. ## Confirmed state In a match with other machines, a client runs ahead of the server: its views draw the world as this machine predicts it, and a prediction can be wrong for a moment, until the server says how the tick went (see [Networking](#doc-multiplayer--networking--prediction-and-rollback)). That suits what has to answer at once, like movement. What must not be wrong, like a health bar, a score or a death, is read `verified`: from the world the server has confirmed. `verified` goes before a parameter's type, like `mut`: ```csharp // Movement as predicted, the health bar only what's confirmed. view DrawFighter(Body body, verified Health health) { Draw.Circle(body.position, 0.5, Color.white); Draw.Rect(body.position + float2(0, 0.8), float2(health.value * 0.01, 0.1), Color.red); } // The same component twice: what's predicted, and what's confirmed so far. view HealthBar(Body body, Health health, verified Health confirmed) { var at = body.position + float2(0, 1); Draw.Rect(at, float2(confirmed.value * 0.01, 0.1), Color.gray); Draw.Rect(at, float2(health.value * 0.01, 0.1), Color.red); } // A filter, and a singleton. view Corpse(Body body, with verified Dead) { Draw.Circle(body.position, 0.5, Color.gray); } view Board(verified Duel duel) { Draw.SetScreen(); Draw.Text($"Round {duel.round}", float2(20, 20), 24, Color.white); } ``` - **A view runs for an entity when each parameter exists in the world it names.** A view with components of both worlds needs the entity in both, so it skips one whose spawn isn't confirmed yet. A game that wants it drawn sooner splits the view in two: one that draws what's predicted, and one that adds what's confirmed. - **A view whose components are all `verified`** runs for the confirmed world's entities, and draws them as they are there: `this` is the confirmed entity, and corrections aren't smoothed. - **Filters take it**: `with verified Dead`, `without verified Dead`. Either asks for the entity in the confirmed world: `without verified Dead` is "confirmed, and not `Dead` there", so it skips an entity whose spawn isn't confirmed yet too. - **Singletons take it**: `verified Duel duel`. - **A `verified` value is whole.** Its text, lists, maps, sets and grids are the confirmed world's, and read like any other's: `sure.build.cards.count`, `foreach (var card in sure.build.cards)`, a copy of the value, a function it's passed to. They're to read, like everything a view takes of the match: to change one, take a copy. - **A `verified` value interpolates between confirmed ticks.** Its presentation clock holds at the latest confirmation and never extrapolates. Floats and rotations follow the ordinary [interpolation rules](#doc-game--views--smooth-at-any-tick-rate), including custom `Interpolate` and `Snap()`. Entity membership, integers, tags and containers come from the upper confirmed endpoint. - **`mut` goes with it.** `mut verified Health health` reads the confirmed `Health` and writes the entity's [local fields](#doc-game--local-state--local-fields), which are the entity's whichever world a parameter reads. A view that takes a component both ways reaches its local fields through the one that isn't `verified`. - **The same entity** in both worlds is the entity, not only its handle: running a tick again can give a handle to another entity, which is then in one world only (see [After a rollback](#doc-game--local-state--after-a-rollback)). - **It's the view's to say.** A function's parameter can't say `verified`: the view takes the value `verified` and passes it on. Nor can a [frag or vert](#doc-game--shaders), which reads what its view is given. - **The match has no "confirmed".** It's the same on every machine, so `verified` in a system, a match handler or a task is an error, which points to views and local handlers. Outside a match, a view with a `verified` parameter doesn't run, like any view that reads the match. A local handler takes `verified` on its event, to hear it once it's certain: see [Events](#doc-game--events--verified-handlers). ### Holding a death until it's confirmed With a predicted `Body`, an entity is gone from a view the moment the prediction destroys it, whatever a `verified` parameter beside it says: the view needs the entity in both worlds. There are three ways to hold a death until the server has confirmed it: - **Make the death a state of a living entity**, a field or a tag like `Dead`, and destroy the entity later. Views read the state `verified`, as `Corpse` does above. - **Take everything `verified` in that view.** It then runs for the confirmed world's entities, so the entity is drawn, as the server last confirmed it, until the server says it's gone. - **Show it from a local handler**: `local event(verified Destroyed) ...` hears the entity go once it's certain, with its components as they were (see [Events](#doc-game--events--verified-handlers)). ### What isn't there yet - **`verified World world`**, which is an error that points to `verified` component parameters. A view's `World` is the world it draws. --- Source: https://tide-engine.dev/game/draw-settings.md Tide's draw settings: blending, alpha, tints, stencil, transforms and clipping, each around a block or set for the draws that follow, and how to draw what's see-through. # Draw settings A setting changes how everything drawn after it comes out: how it blends, what tints it, what it does with depth and stencil, which side of it shows, where it lands. Each has two forms, and its name says which. The plain name wraps a block. It's set for the draws in the block, and when the block ends, what it found is back: ```csharp Draw.Blend(Blend.Add) { Draw.Circle(spark.position, 2, spark.color); } ``` The `Set` name is a statement. It stays for the draws that follow, in this view and the views after it, until it's set again or the frame ends, which is how a camera is set once for a frame: ```csharp view Follow(Player player, with ownership) { Draw.SetCamera(player.position, 10); } ``` | Around a block | For the draws that follow | What it sets | |---|---|---| | `Draw.Blend(mode)` | `Draw.SetBlend(mode)` | How colors go over what's there (see [Blending](#doc-game--draw-settings--blending)) | | `Draw.Tint(color)` | `Draw.SetTint(color)` | A color everything is multiplied by (see [Tints](#doc-game--draw-settings--tints)) | | `Draw.Stencil(test, value)`, `Draw.Stencil(test, value, operation)` | `Draw.SetStencil(test, value)`, `Draw.SetStencil(test, value, operation)` | The test draws pass, against a number kept for each pixel, and what becomes of that number where they draw (see [Stencil](#doc-game--draw-settings--stencil)) | | `Draw.Transform(...)`, `Draw.Transform(transform)` | `Draw.SetTransform(...)`, `Draw.SetTransform(transform)` | Where draws land: moved, turned, scaled (see [Transforms](#doc-game--draw-settings--transforms)) | | `Draw.Clip(rect)` | `Draw.SetClip(rect)` | The rectangle draws are kept inside (see [Clipping](#doc-game--draw-settings--clipping)) | | `Draw.Camera(center, size)`, `Draw.Camera(...)` | `Draw.SetCamera(center, size)`, `Draw.SetCamera(...)` | The camera | | `Draw.Screen()` | `Draw.SetScreen()` | The screen's pixels in the camera's place (see [On the screen](#doc-game--views--on-the-screen)) | | `Draw.Depth(mode)` | `Draw.SetDepth(mode)` | What 3D meshes do with depth: whether they're hidden behind what's nearer, and whether they hide what's behind them (see [Depth](#doc-game--3d--depth)) | | `Draw.DepthBias(constant, slope)` | `Draw.SetDepthBias(constant, slope)` | Pulls 3D draws nearer (negative) or pushes them farther (positive) against what has the same depth, like a decal on a floor (see [Depth bias](#doc-game--shaders--depth-bias)) | | `Draw.Cull(side)` | `Draw.SetCull(side)` | Which side of a 3D mesh's triangles isn't drawn: the back, unless this says otherwise (see [Which side draws](#doc-game--3d--which-side-draws)) | | `Draw.FrustumCulling(enabled)` | `Draw.SetFrustumCulling(enabled)` | Whether to skip 3D instances wholly outside the camera; enabled by default (see [Frustum culling](#doc-game--3d--frustum-culling)) | | `Draw.Occlusion(enabled)` | `Draw.SetOcclusion(enabled)` | Whether to skip instances of 3D lists that what's drawn before them surely hides; off by default (see [Occlusion culling](#doc-game--3d--occlusion-culling)) | | `Draw.Bounds(center, size)`, `Draw.Bounds()` | `Draw.SetBounds(center, size)`, `Draw.SetBounds()` | Conservative mesh-local culling bounds, with full size; no arguments restores automatic bounds | | `Draw.LOD(level)`, `Draw.LOD()` | `Draw.SetLOD(level)`, `Draw.SetLOD()` | Which level of detail the meshes marked `[LOD]` draw at, in place of the one each picks; with no level, each picks again (see [Levels of detail](#doc-game--assets--levels-of-detail)) | | `Draw.LODPixels(pixels)`, `Draw.LODPixels()` | `Draw.SetLODPixels(pixels)`, `Draw.SetLODPixels()` | Allowed estimated error for automatic LOD, in screen pixels; default 1, multiplied by the asset's optional `[LOD(multiplier)]` | | `Draw.LODCamera(...)`, `Draw.LODCamera()` | `Draw.SetLODCamera(...)`, `Draw.SetLODCamera()` | The camera those meshes pick their level through, in place of the one they're drawn through; with nothing, their own again | Every frame starts from the defaults, so a `Set` never outlives its frame, and the GUI and the stats are never drawn with what a game set. A `Set` with no arguments puts the default back early: `Draw.SetTint()`, `Draw.SetStencil()`, `Draw.SetClip()`, `Draw.SetDepth()`, `Draw.SetDepthBias()`, `Draw.SetCull()`, `Draw.SetFrustumCulling()`, `Draw.SetOcclusion()`, `Draw.SetBounds()`, `Draw.SetLOD()`, `Draw.SetLODPixels()`, `Draw.SetLODCamera()`; `Draw.SetCamera()` puts both cameras back, the 2D and the 3D, and `Draw.SetTransform()` both transforms. Bounds and the three for levels of detail have a block form with no arguments too, which does the same around some draws. Writing one form as the other is a compile error that names the right one: `Draw.Blend(Blend.Add);` with no block says to write `Draw.SetBlend`, and `Draw.SetBlend(Blend.Add) { }` says `Draw.Blend`. Your editor offers the rename. A block that's left early still puts back what it found, as a GUI container still closes: ```csharp Draw.Tint(Color(1, 1, 1, 0.5)) { if (!card.shown) return; // The tint is gone, here too DrawCard(card); } ``` Every setting belongs to the destination it's called on. `Draw`'s are the window's, and a [render target](#doc-game--render-targets) has its own, by the same names (`target.Blend(Blend.Add) { ... }`, `target.Clip(rect) { ... }`, `target.SetCamera(...)`, `target.Depth(mode) { ... }`): a blend or a tint set for the window doesn't reach a target's draws, and a target's doesn't reach the window's. Depth and cull are for 3D meshes alone: around 2D draws they change nothing, and that's no error. **Info** What a `Set` with no arguments does, how one setting nests in another, `Draw.Depth`'s name and its modes', `Cull`'s three names and which way round a triangle's front goes, how `Draw.Stencil` is written, its tests' and operations' names and each of its rules, and how `Draw.DepthBias` counts (its constant in the depth image's precision steps, truncated to a whole number, its slope, and the limits past which a factor becomes zero) are provisional: they're how it works today, and may still change. ## Several at once Calls that take a block can be listed with commas before one block, so settings don't nest three deep: ```csharp Draw.Blend(Blend.Add), Draw.Tint(Color(1, 1, 1, shown)), Draw.Clip(panel) { DrawGlow(panel); } ``` It means the same as each inside the one before. That's the language's, not `Draw`'s: the [GUI](#doc-game--gui--guilayout-and-gui)'s containers and [your own functions that take a block](#doc-language--functions--actions) go in the same list. ## Blending `Blend.Alpha` is the default: a color goes over what's there by its alpha. The others: | Mode | What it does | For | |---|---|---| | `Blend.Add` | Adds the color to what's there, as light adds | Sparks, trails, glows, fire | | `Blend.Multiply` | Multiplies what's there by the color: white changes nothing, black makes black | Shadows, stains, tinted glass | | `Blend.Replace` | Puts the color and its alpha in place of what's there | Writing into a [render target](#doc-game--render-targets) exactly | In each, a color's alpha is how much of it there is, so what's clear changes nothing: a shape's smooth edge and the gaps between a text's strokes stay clean when they're added or multiplied. ```csharp view Trails(Bullet bullet) { Draw.Blend(Blend.Add) { // Where trails cross, they're brighter Draw.Line(bullet.position - bullet.velocity * 0.05, bullet.position, 0.2, Color(1, 0.6, 0.2, 0.6)); } } ``` `Draw.Clear`, and a target's `Clear`, fill with their color whatever the blend, and [`Draw.Blit`](#doc-game--render-targets--post-processing) takes a blend of its own (`Draw.Blit(source, destination, Blend.Add, frag)`). ## Alpha A color's alpha is how much of it there is, and you write colors as they are everywhere: `Color(1, 0, 0, 0.5)` is red, half clear, in a draw, a tint, a grid's cell, a PNG and a frag. There's nothing to multiply yourself and no second kind of blend to pick. See [Transparency](#doc-game--draw-settings--transparency) for drawing something see-through, fading it, and cutting holes in a 3D mesh. What that buys: - **No fringes.** A sprite's clear pixels have a color too in its file, often black or white, which never shows. Scaled or turned with `Filter.Bilinear`, a pixel at the sprite's edge is blended with its clear neighbor, and the neighbor counts for none of the color: a white sprite over a white wall has no gray rim, whatever the file kept in its clear pixels. - **Layers.** What's drawn into a cleared [render target](#doc-game--render-targets), `target.Clear(Color.clear)`, and then drawn from it with `target.color` looks as it would drawn straight onto the window: a HUD, a minimap or a trail kept in a target goes over the game as it is. A few things follow from how that's kept, which is each color times its alpha, in textures and in targets: - **A pixel with no alpha has no color.** A frag that samples one gets `Color(0, 0, 0, 0)`, whatever the file or the cell said its color was. An image whose alpha is something other than how clear it is (a mask beside unrelated colors) would lose its colors where the alpha is 0: mark it [`[Raw]`](#doc-game--shaders--textures-that-are-numbers), and a frag reads its numbers as the file has them. - **`Blend.Replace` with an alpha under 1** leaves the window, which has no alpha of its own, darker by that much, as if over black. Into a target it's exact: drawn from the target later, it's the color and the alpha that were written. - **`Blend.Add` raises the alpha that's there** towards 1 by its own, and never past it, so light added into a clear target shows when the target is drawn over something. - A dim color that's nearly clear keeps few of its 256 steps in an image of bytes. It doesn't show once it's blended; a [`Format.Rgba16f`](#doc-game--render-targets--what-a-target-holds) target keeps them all. ## Tints A tint multiplies the color of everything drawn inside, alpha too. `Color(1, 1, 1, 0.5)` fades it to half, with no alpha to pass to every call: ```csharp view Menu(MenuState menu) { Draw.Screen(), Draw.Tint(Color(1, 1, 1, menu.shown)) { Draw.RoundRect(float2(200, 120), float2(320, 160), 12, Color(0.1, 0.1, 0.15)); Draw.Text("Paused", float2(160, 80), 32, Color.white); } } ``` A tint in a tint's block multiplies it: a faded menu's faded button is fainter than either. ## Stencil Beside its color and its depth, every pixel has a whole number from 0 to 255, its stencil. Nothing shows it. Draws store numbers there, and other draws are drawn only where the number passes a test, which is how one thing is cut to the shape of another: a view through a porthole, a map inside a round frame, a mirror that shows its reflection only where the glass is, an outline around whatever is selected. `Draw.Stencil(test, value, operation)` says both things for the draws in its block: the test they pass to be drawn at a pixel, their `value` against the number stored there, and what becomes of the stored number where they are drawn. It usually takes two steps. Something stores a number where it is, then something else is drawn where that number is: ```csharp view Porthole(Ship ship) { // The glass stores 1 where it is. It's drawn clear: it's there for what it stores Draw.Stencil(StencilTest.Always, 1, StencilOp.Replace) { Draw.Circle(ship.window, 3, Color.clear); } // The sea is drawn where the number is 1, and nowhere else Draw.Stencil(StencilTest.Equal, 1) { DrawSea(ship); } } ``` Move the lens below. The wall is drawn where the lens didn't store its number, and the pipes where it did: **A lens, cut out of a wall** ([Run example](https://tide-engine.dev/examples/stencil/?stats)) ```tide settings { title = "Stencil"; } local scene Main { } local singleton Lens { float2 at = float2(188, 170); float radius = 70; bool outside; // Show what's behind everywhere but in the lens float time; } // The wall: rows of bricks, each row half a brick along from the last. void Wall() { Draw.Rect(float2(Screen.width, Screen.height) * 0.5, float2(Screen.width, Screen.height), Color(0.24, 0.25, 0.27)); for (var row = 0; row < 17; row++) { for (var column = -1; column < 8; column++) { var corner = float2(column * 56 + (row % 2) * 28, row * 24); Draw.RoundRect(corner + float2(28, 12), float2(52, 20), 3, Color(0.13, 0.13, 0.15)); } } } // What's behind it: pipes, and what flows through them. void Pipes(float time) { Draw.Rect(float2(Screen.width, Screen.height) * 0.5, float2(Screen.width, Screen.height), Color(0.05, 0.05, 0.06)); for (var pipe = 0; pipe < 4; pipe++) { var y = 60 + pipe * 80; var color = pipe % 2 == 0 ? Color(0.18, 0.83, 0.75) : Color(0.98, 0.44, 0.52); Draw.Line(float2(0, y), float2(Screen.width, y), 18, Color(0.24, 0.25, 0.27)); for (var drop = 0; drop < 6; drop++) { var along = Math.Frac(time * (0.12 + pipe * 0.03) + drop / 6.0); var x = pipe % 2 == 0 ? along * Screen.width : (1 - along) * Screen.width; Draw.Circle(float2(x, y), 6, color); } } } view Show(mut Lens lens, Devices devices) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); lens.time += Frame.dt; var pointer = Screen.Flip(devices.pointer.position); if (pointer.y < Screen.height - 64) lens.at = pointer; // Every pixel has a number, 0 after a clear. The lens stores 1 where it is. // It's drawn clear, so nothing of it shows: it's there for what it stores. Draw.Stencil(StencilTest.Always, 1, StencilOp.Replace) { Draw.Circle(lens.at, lens.radius, Color.clear); } // The wall is drawn where the number isn't the lens's... Draw.Stencil(lens.outside ? StencilTest.Equal : StencilTest.NotEqual, 1) { Wall(); } // ...and the pipes where it is. Draw.Stencil(lens.outside ? StencilTest.NotEqual : StencilTest.Equal, 1) { Pipes(lens.time); } // With no test again: the lens's rim, over both. Draw.WireCircle(lens.at, lens.radius, 3, Color(0.98, 0.75, 0.14)); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40)) { GUILayout.Horizontal() { GUILayout.Slider("Lens", lens.radius, 20, 140); GUILayout.Toggle("Outside", lens.outside); } } } ``` The test is between the draw's `value`, on the left, and the stored number: | Test | A pixel is drawn where | |---|---| | `StencilTest.Always` | Everywhere: no test, which is what every frame starts with | | `StencilTest.Never` | Nowhere | | `StencilTest.Equal` | The stored number is `value` | | `StencilTest.NotEqual` | It's any other | | `StencilTest.Less` | `value` is less than the stored number | | `StencilTest.LessEqual` | `value` is less than it, or the same | | `StencilTest.Greater` | `value` is greater than the stored number | | `StencilTest.GreaterEqual` | `value` is greater than it, or the same | The operation says what becomes of the stored number at each pixel the draw is drawn at. Without one it stays as it is, so `Draw.Stencil(test, value)` only tests: | Operation | The stored number becomes | |---|---| | `StencilOp.Keep` | What it was: the draw only tests | | `StencilOp.Replace` | `value` | | `StencilOp.Increment` | One more, 255 at the most | | `StencilOp.Decrement` | One less, 0 at the least | | `StencilOp.Zero` | 0 | | `StencilOp.Invert` | 255 less it: each of its 8 bits the other way | - **Every pixel's number is 0 when a frame starts,** in the window. A [render target](#doc-game--render-targets) keeps its numbers from frame to frame, as it keeps its colors, until it's cleared. - **A draw stores where it's drawn, whatever its color.** `Color.clear` stores and shows nothing, which is how to lay a mask down without painting anything. That's so under every [blend](#doc-game--draw-settings--blending) but `Blend.Replace`, which puts the clear color there. - **Where it's drawn is every pixel it touches:** all of a rect, a circle out to its edge, a smooth shape to the pixels its edge only partly covers, text where its glyphs are (not the boxes around them), and all of a mesh's triangles, whatever its texture's alpha is there. For a mask the shape of a picture, draw it through a [frag](#doc-game--shaders) that leaves out what's clear with `this.Discard()`: a pixel a frag discards stores nothing. - **It's cut along pixels.** A pixel is in a mask or it isn't, so what's drawn where a mask is has a stepped edge where the mask's shape is round, however smooth the shape itself would be drawn. Draw a rim over it with no test, as the example does, where that shows. - **A draw that fails the test changes nothing,** and neither does a 3D mesh where it's hidden behind what's nearer: the number changes only where the draw is drawn. - **It's for everything that draws:** shapes, text, meshes, 3D meshes and the [primitives](#doc-game--3d--primitives), with a frag or without. Draws in a row under the same stencil are still one draw. - **`Draw.Clear`, and a target's `Clear`, set every number back to 0,** within the [clip](#doc-game--draw-settings--clipping), whatever is set, and are tested against nothing. [`Draw.Blit`](#doc-game--render-targets--post-processing) neither tests nor stores, whatever is set. - **A render target has its own numbers, and its own setting:** `target.Stencil(StencilTest.Equal, 1) { target.Rect(...); }`. `Draw.Stencil` is the window's, and doesn't reach what's drawn into a target; a target's doesn't reach the window. - **`value` is any `int`.** Under 0 it's 0, and over 255 it's 255. The test and the operation are values too: `Draw.Stencil(inside ? StencilTest.Equal : StencilTest.NotEqual, 1)`. - **A block's stencil replaces the one it found,** and puts it back when it ends. `Draw.SetStencil()` puts back none: every pixel passes, and nothing is stored. Counting is the other use. Each of these adds one where it's drawn, so afterwards a pixel's number is how many of them cover it, and a draw under `StencilTest.Less` with a `value` of 1 is drawn where more than one does: ```csharp Draw.Stencil(StencilTest.Always, 0, StencilOp.Increment) { foreach (var zone in zones.list) Draw.Circle(zone.center, zone.radius, Color.clear); } Draw.Stencil(StencilTest.Less, 1) // Where 1 is less than the count: two zones or more { Draw.Rect(zones.middle, zones.size, Color(1, 0.2, 0.2, 0.5)); } ``` What a GPU's stencil has beyond this isn't here: a setting for each side of a triangle, one for what happens where a mesh is hidden, and masks over the number's bits. ## Transforms A transform moves, turns and scales everything drawn inside, in the units the calls are in. `Draw.Transform` takes an offset, then a rotation in radians, then a scale, each optional after the first: ```csharp view Cards(Card card) { // Scaled about the card's middle, then turned, then moved there Draw.Transform(card.position, card.tilt, 1 + card.lift * 0.1) { Draw.RoundRect(float2(0, 0), float2(3, 4), 0.3, Color.white); Draw.Text(card.name, float2(-1.2, 1.6), 0.5, Color.black); } } ``` What's inside is drawn around (0, 0), and the transform puts it in the world: scaled, then turned (from `+x` towards `+y`, as [smooth shapes](#doc-game--views--smooth-shapes) turn), then moved. The scale is a number, or a `float2` to stretch more one way than the other, and `Draw.Transform(matrix)` takes any `float3x3` instead. `Draw.Transform(transform)` does the same for 3D meshes with a `float4x4`. A transform in a transform's block is inside it, so a card's badge can have one of its own. What's drawn through one: - Shapes stay shapes, with their smooth edges: moved, turned and scaled, exactly. Stretched, a circle is the ellipse it becomes, and a rect follows its own sides; a skew is approximated. Rects that are only moved and scaled still fill whole pixels, so tiles under a transform leave no seams. - Meshes go through any transform as they are. - Text that's moved and scaled as much each way is text of that size, as sharp as any. Turned or stretched, it has no pixels to be fitted to, so it's a little softer than upright text: fine for a tilting card, and worth avoiding for text people read at length. - A clip made inside one is the upright rectangle around what its `Rect` becomes: clips don't turn. `Draw.WorldToScreen` and the other [conversions](#doc-game--cameras--screen-and-world-coordinates) are the camera's alone, whatever the transform. [`Draw.MeasureText`](#doc-game--views--measuring-text) answers in the units the transform takes, so inside one, text measures as it's drawn. ## Clipping `Draw.Clip(rect) { ... }` keeps what's drawn in its block inside a rectangle: meshes, shapes, text, and `Draw.Clear`, which then fills the rectangle. ```csharp view Panel() { Draw.Screen(), Draw.Clip(Rect(20, 20, 200, 100)) { Draw.Clear(Color.black); // The panel only Draw.Text("A line too long for the panel is cut off at its edge", float2(28, 28), 18, Color.white); } } ``` The `Rect` goes from (x, y) to (x + width, y + height), in the units the calls are in: the world's under a camera, where `y` is up, and pixels on the screen. It stays where it is on the screen when the camera changes afterwards. A clip in a clip's block only narrows it: what draws is inside both, which is what a list in a panel wants. `Draw.SetClip(rect)` is the [other form](#doc-game--draw-settings--draw-settings), for the draws that follow, and sets the rectangle outright; `Draw.SetClip()` draws everywhere again. Each frame starts with no clip, and a view's clip never clips the GUI. ## Transparency Set a color's **alpha**, its fourth number, to the opacity you want: `0` is invisible, `0.5` is half opaque, and `1` is solid. `Color(r, g, b)` is solid. The default [`Blend.Alpha`](#doc-game--draw-settings--blending) blends the color over what's already drawn, so shapes and text need no extra setting: ```csharp view Overlay() { Draw.Screen() { Draw.Rect(float2(160, 100), float2(240, 80), Color(0.18, 0.83, 0.75, 0.5)); Draw.Text("Half opaque", float2(40, 60), 20, Color(1, 1, 1, 0.5)); } } ``` Draw the background first, then what goes over it. This is also how a **sprite with transparent pixels** works: give `Draw.Mesh` its PNG or texture, and the pixel's alpha supplies its opacity. A mesh's vertex colors multiply that alpha, and a [frag](#doc-game--shaders--a-frag) controls it through its `out Color`. To **fade a whole set of draws**, wrap them in [`Draw.Tint(Color(1, 1, 1, opacity))`](#doc-game--draw-settings--tints). This keeps their colors and multiplies each draw's alpha by `opacity`. Each draw still blends separately: if overlapping elements should fade as one finished layer, draw them into a [render target](#doc-game--render-targets) cleared with `Color.clear`, then tint the draw of `target.color`. Colors stay as you wrote them; Tide handles [premultiplied alpha](#doc-game--draw-settings--alpha) internally. ### Transparent 3D A 3D mesh also has depth. For glass, smoke and other translucent surfaces: 1. Draw solid geometry first with the default `Depth.ReadWrite`. 2. Draw translucent geometry inside `Draw.Depth(Depth.Read) { ... }`, with alpha below 1. It tests against the solid geometry's depth and writes no depth itself. 3. Draw the translucent surfaces **farthest first**, then the nearer ones, so they blend over what's behind them. Change **Opacity** below. The amber cube is behind the panes and shows through them; the solid pillar in front hides them. The camera stays fixed, so the rose pane is always farther away and is drawn first. The bar above the scene uses the same opacity on a 2D shape. **Opacity in 2D and 3D** ([Run example](https://tide-engine.dev/examples/transparency/?stats)) ```tide settings { title = "Transparency"; } local scene Main { } local singleton Glass { float opacity = 0.5; List pane = [ Vertex3 { position = float3(-1.3, -1.4, 0) }, Vertex3 { position = float3(-1.3, 0.5, 0) }, Vertex3 { position = float3(1.3, 0.5, 0) }, Vertex3 { position = float3(1.3, -1.4, 0) } ]; List faces = [0, 1, 2, 0, 2, 3]; } view Solid() { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float3(0, 0, -7), quaternion.identity, 50); // Solid geometry comes first, with the default Depth.ReadWrite. Draw.Cube(float3(-0.5, -0.35, 2), float3(1.5), quaternion.Euler(float3(0, 0.35, 0)), Color(0.98, 0.75, 0.14)); Draw.Cube(float3(0.8, -0.45, -1), float3(0.5, 1.8, 0.5), Color(0.64, 0.64, 0.68)); } view Panes(Glass glass) { // The camera is fixed: z = 1 is farther away than z = 0. // Read opaque depth, but let later translucent draws show through. Draw.Depth(Depth.Read) { Draw.Tint(Color(0.98, 0.44, 0.52, glass.opacity)) { Draw.Mesh(glass.pane, glass.faces, float4x4.Translate(float3(-0.2, 0.15, 1))); } Draw.Tint(Color(0.18, 0.83, 0.75, glass.opacity)) { Draw.Mesh(glass.pane, glass.faces, float4x4.Translate(float3(0.2, 0, 0))); } } } view Overlay(mut Glass glass) { Draw.SetScreen(); Draw.Text("2D: alpha blends over the background", float2(16, 16), 16, Color.white); var width = (Screen.width - 32) / 8; for (var i = 0; i < 8; i++) { var shade = i % 2 == 0 ? 0.2 : 0.35; Draw.Rect(float2(16 + (i + 0.5) * width, 85), float2(width, 54), Color(shade, shade, shade)); } Draw.Rect(float2(Screen.width * 0.5, 85), float2(Screen.width - 64, 36), Color(0.98, 0.44, 0.52, glass.opacity)); Draw.Text("3D: solids, then panes from far to near", float2(16, 132), 16, Color.white); Draw.Text("The pillar hides both panes", float2(16, Screen.height - 80), 14, Color(0.64, 0.64, 0.68)); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Opacity", glass.opacity, 0, 1); } ``` Tide draws in the order your views and calls give it; it **doesn't sort transparent entities or a mesh's triangles by distance**. For a moving camera, gather your transparent objects in a local list, [sort it](#doc-language--text-and-lists--sorting) from far to near for that camera, then draw them in that order. Intersecting transparent surfaces, or faces within one mesh, may need to be split and ordered too; sorting whole objects alone can't resolve every overlap. - **Alpha doesn't turn depth writes off.** Even alpha 0 can hide later geometry under `Depth.ReadWrite`. Use `Depth.Read` for translucency, or discard the pixel for a hole. - **`Depth.None` also stops testing depth,** so the mesh shows through solid walls. Use `Depth.Read` when walls should hide it. - **A thin pane has a back too.** If it should show from either side, use [`Draw.Cull(Cull.None)`](#doc-game--3d--which-side-draws). On a closed mesh that also draws the far faces, whose alpha blends with the near ones. - **A target has its own settings:** use `target.Depth(Depth.Read)` and `target.Tint(...)` for its draws. `Draw`'s settings reach the window alone. ### Cutout holes Leaves, a fence or a sprite standing in a 3D world often want solid pixels with holes between them. A frag can discard pixels below an alpha threshold and keep the rest opaque: ```csharp frag Cutout(Vertex3 vertex, out Color color, Texture image) { color = image.Sample(vertex.uv); if (color.a < 0.5) this.Discard(); color.a = 1; } // Keep the default Depth.ReadWrite: only the surviving pixels hide what's behind. Draw.Mesh(vertices, indices, transform, texture, Cutout); ``` [`this.Discard()`](#doc-game--shaders--where-the-pixel-is) ends the frag and writes no color, depth or stencil for that pixel. The surviving pixels can use the usual opaque draw order. The threshold gives a hard edge; use the translucent recipe above when you want partial opacity at the edge instead. A frag that can discard is run for every pixel it covers, even one a nearer leaf hides. Where many cut-outs overlap and their lighting is expensive, draw their depth first with `Depth.Only` and light them with `Depth.Equal`: see [A depth pre-pass](#doc-game--3d--a-depth-pre-pass). --- Source: https://tide-engine.dev/game/meshes-and-textures.md Draw triangles in Tide with Draw.Mesh, and texture them from an asset, a render target or a grid you paint: filters, wraps, mipmaps, one-channel textures and sampling said once. # Meshes and textures A mesh is triangles, and a texture is an image they're drawn with. This page has the 2D mesh and everything about textures; [3D meshes](#doc-game--3d) are drawn with them the same way. ## Meshes `Draw.Mesh(vertices, indices)` draws triangles, the shape every other one can be made of. `vertices` is a `List`, the corners, and `indices` a `List`: every three are a triangle, each a corner's place in `vertices`, so triangles share corners. ```csharp struct Vertex // Built in { float2 position; float2 uv; // Where in the texture: (0, 0) to (1, 1) Color color = Color.white; } ``` ```csharp view Arrows(Body body) { List corners = [ Vertex { position = body.position + float2(0, 1), color = Color.red }, Vertex { position = body.position + float2(-1, -1), color = Color.blue }, Vertex { position = body.position + float2(1, -1), color = Color.blue }, ]; Draw.Mesh(corners, [0, 1, 2]); } ``` Each pixel of a triangle is its corners' colors, blended across it, over what's behind it by its alpha. Triangles draw whichever way round their corners go (a 2D mesh has no back, where a [3D one](#doc-game--3d--which-side-draws) does), in the order they're given, among everything else a view draws. An index past the end of `vertices` leaves its triangle out. A mesh is one call however many triangles it has, and meshes drawn one after another go to the GPU together, so thousands of triangles a frame are cheap. A mesh's corners can be a struct of your own instead, with whatever fields the mesh needs, and a `vert` and a `frag` can run for its vertices and its pixels on the GPU: see [Frags and verts](#doc-game--shaders). ## Textures A color `Texture` is what you draw with. It comes from an asset, `asset Texture hero = "art/hero.png";` (see [Assets](#doc-game--assets--images-to-draw-with)), from a render target, `target.color` (see [Targets](#doc-game--render-targets)), or from a grid you paint: an ordinary `Grid2` or a `Grid2` with a size (see [Grids](#doc-language--grids)) is a `Texture` wherever one is wanted. Numeric [`[Raw]` sources](#doc-game--shaders--textures-that-are-numbers) use Raw fields and shader sampling instead of ordinary color draws. `Draw.Mesh` takes one after its indices. With no frag, each pixel is the triangle's color times the texture's at its `uv`: (0, 0) is the first pixel's outer corner, and (1, 1) the last pixel's outer corner. ```csharp local singleton Art { Grid2 checker = Grid2(8, 8); bool painted; } view Board(mut Art art) { if (!art.painted) { foreach (var at in art.checker) { art.checker[at] = (at.x + at.y) % 2 == 0 ? Color.white : Color.black; } art.painted = true; } List corners = [ Vertex { position = float2(-4, -4), uv = float2(0, 0) }, Vertex { position = float2(4, -4), uv = float2(1, 0) }, Vertex { position = float2(4, 4), uv = float2(1, 1) }, Vertex { position = float2(-4, 4), uv = float2(0, 1) }, ]; Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], art.checker, Filter.Point); } ``` Drag over the grid below to set its cells, and the next frame draws them. The toggle switches between `Filter.Point` and `Filter.Bilinear`. **A grid, drawn as a texture** ([Run example](https://tide-engine.dev/examples/textures/?stats)) ```tide settings { title = "Textures"; } local scene Main { } // A grid of colors is a texture. There's nothing to create, upload or free. local singleton Canvas { Grid2 pixels = Grid2(16, 16); bool ready; bool point = true; float hue; } view Paint(Devices devices, mut Canvas canvas) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), 1.4); if (!canvas.ready) { foreach (var at in canvas.pixels) canvas.pixels[at] = (at.x + at.y) % 2 == 0 ? Color(0.13, 0.13, 0.15) : Color(0.17, 0.17, 0.19); canvas.ready = true; } // The quad covers -1 to 1, and the grid's first row is its top one. var pointer = Draw.ScreenToWorld(Screen.Flip(devices.pointer.position)); if (devices.pointer.press.pressed && Math.Abs(pointer.x) < 1 && Math.Abs(pointer.y) < 1) { canvas.hue += Frame.dt * 2; var cell = int2(Math.Floor((pointer + 1) * 8)); canvas.pixels[cell.x, 15 - cell.y] = Color(0.6 + 0.4 * Math.Sin(canvas.hue), 0.6 + 0.4 * Math.Sin(canvas.hue + 2), 0.6 + 0.4 * Math.Sin(canvas.hue + 4)); } List corners = [ Vertex { position = float2(-1, 1), uv = float2(0, 0) }, Vertex { position = float2(1, 1), uv = float2(1, 0) }, Vertex { position = float2(1, -1), uv = float2(1, 1) }, Vertex { position = float2(-1, -1), uv = float2(0, 1) }, ]; // The next frame draws whatever the cells hold by then. Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], canvas.pixels, canvas.point ? Filter.Point : Filter.Bilinear); Draw.SetScreen(); Draw.Text("Drag on the grid to paint its cells", float2(16, 14), 16, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40)) { GUILayout.Horizontal() { GUILayout.Toggle("Filter.Point", canvas.point); if (GUILayout.Button("Clear")) canvas.ready = false; } } } ``` There's nothing to create, upload or free. The grid is ordinary state: change its cells whenever, with `[x, y]`, a loop or `Clear()`, and the next frame draws what it holds. The engine keeps a copy on the GPU while views draw with it, and sends only the cells that changed: a brush that paints a few cells of a big canvas costs those few, not the canvas. The grid can be local state or the match's, like a canvas each player paints. Views read the match's grids as they are at the latest tick: cells aren't blended. The argument after the texture says how it's read between pixels: `Filter.Bilinear` blends them, `Filter.Point` takes the nearest, for pixel art, `Filter.Trilinear` blends them and stays smooth where the texture is drawn smaller than it is (see [Drawn smaller](#doc-game--meshes-and-textures--drawn-smaller)), and `Filter.Anisotropic` is that for a surface seen at a shallow angle (see [Seen at a shallow angle](#doc-game--meshes-and-textures--seen-at-a-shallow-angle)). A call that leaves it out reads the texture as the texture says (see [Saying it once](#doc-game--meshes-and-textures--saying-it-once-on-the-texture)), which is blended unless something said otherwise. - A grid with an open axis has no size, so it's no texture: the mesh draws with its colors alone. Neither is one past 16384 cells a side. - How big a texture can be is the GPU's limit: at least 2048 by 2048 wherever Tide runs. - What a grid costs is game state, 16 bytes a cell of colors and 4 a cell of floats, with a copy on the GPU at a byte a channel (values are clamped to 0 to 1) or 16 bits a float. An asset's `Texture` keeps a byte per channel as its fallback, with [automatic GPU compression](#doc-game--assets--gpu-compression) for eligible color images: for an image that's only drawn, a sprite or a tile sheet, declare it as one. A grid is for pixels code reads and writes. A game's C can draw meshes too, with pixels of its own, like a font atlas a library made: see [Drawing from C](#doc-c--functions--drawing-from-c). Use [`[Linear]`](#doc-game--shaders--linear-light-color) on Texture, TextureArray and Cubemap assets and fields that hold display-encoded color for lighting. The GPU converts RGB to linear light before filtering. Unmarked images keep their current behavior; neither the mark nor `Math.ToLinear`/`Math.ToDisplay` changes alpha, frag output semantics or screen presentation. ### Sprites `Draw.Sprite(texture, center, size, color)` draws a texture upright over a box in one call, where a mesh would take four corners and six indices. `center` and `size` are as `Draw.Rect`'s, and the texture's top left is at the box's top left: the top is towards the top of the screen, under a camera (y up) as in [the screen's pixels](#doc-game--views--on-the-screen) (y down). Each pixel is the texture's times `color`, and a call can leave the color out for white. ```csharp asset Texture hero = "art/hero.png"; asset Texture sheet = "art/run.png"; // Four frames side by side component Runner { float2 position; bool left; int frame; // 0 to 3 float spin; } view Runners(Runner runner) { float2 size = float2(runner.left ? -1 : 1, 1); // A negative width mirrors it Draw.Sprite(sheet, runner.position, size, Rect(runner.frame * 0.25, 0, 0.25, 1), Color.white); Draw.Sprite(hero, runner.position + float2(0, 2), float2(1, 1), runner.spin, Color.white); } ``` - `Draw.Sprite(texture, center, size, part, color)` draws the part of the texture a `Rect` of uvs covers: (0, 0) is its top left corner and (1, 1) its bottom right, so a sheet's frame or an atlas's picture is one call. - A `rotation` before the color, in radians from +x towards +y, turns it about its center: `Draw.Sprite(texture, center, size, rotation, color)`, or after the part. - A negative width or height mirrors it. - A filter and a wrap after everything else read it as they say, as a mesh's do; a call that leaves them out reads it as the texture says. - Sprites one after another with the same texture, filter and wrap are drawn together, whatever their colors, as quads of the same texture drawn as meshes are. ### A Texture is a value An ordinary color `Texture` is a small value that names an image: a field or a local holds one, a function takes one and gives one back, and copying it copies no pixels. An ordinary color grid, or a float grid, goes wherever a `Texture` does, and is the texture it is there: ```csharp local singleton Art { Grid2 canvas = Grid2(64, 64); RenderTarget scene; Texture shown; // Whichever it's given } void Show(List corners, List faces, Texture texture) { Draw.Mesh(corners, faces, texture); } view Panel(mut Art art) { art.shown = art.paused ? art.scene.color : art.canvas; // A target's color, or the grid Show(art.corners, art.faces, art.shown); Show(art.corners, art.faces, hero); // An asset } ``` - A texture made of a grid is that grid, not a copy: it draws what the grid holds when it's drawn. It lasts as long as the grid does. One kept past its grid (the entity the grid was a field of is gone, the match ended) draws nothing, or whatever took the grid's place: it's a name, as an `Entity` kept past its entity is. - The default `Texture`, what a field starts as, is no texture: a mesh drawn with it draws its colors alone. - It belongs to this machine: views, local state and the functions they call have them, and the match doesn't. - A [`[Raw] Texture` field](#doc-game--shaders--textures-that-are-numbers) keeps a numeric image for shaders, such as a normal or mask map. Assign a Raw asset, another Raw texture field, a Raw color-grid field/asset or `default`; ordinary color textures are rejected. Its field annotation controls numeric sampling, so it cannot be copied into an ordinary `Texture` field or a `mut` local, or drawn directly; a local that isn't `mut`, a `[Raw] Texture` parameter and a frag's `[Raw] Texture` source keep it. - `texture.size` gives its base-level width and height as an `int2` of physical pixels, in local CPU code and shaders. It reads metadata without copying or uploading pixels. Assets and grids report their image dimensions; render-target aliases follow resize, display scale and the device's size limit. Missing, unloaded or disposed images give `int2(0)`. No code reads a `Texture`'s pixels; a grid's cells are read as the grid. For example, a shader can use `float2 texel = 1.0 / float2(image.size);` for pixel-sized UV offsets. A CPU helper can return `image.size` through ordinary Texture parameters. A `DepthTexture` also has `.size`, including for a depth-only target. Custom C hosts provide `draw.target_pixels = tide_platform_target_pixels` before `tide_frame` to resolve target dimensions; the standard host does this automatically. Without that frame metadata, target sizes are zero. For an explicit `parallel` loop, read the size before the loop and use that `int2` in each step. CPU metadata queries use the frame thread; an ordinary grid `foreach` that reads them stays ordered. ### One channel A `Grid2` is a texture of one channel, for what isn't a picture: a heightmap, a lookup table, a field of distances. A frag reads it like any texture, and gets the cell's number as the color's `r`, with `g` and `b` 0 and `a` 1: ```csharp local singleton Land { Grid2 heights = Grid2(256, 256); } frag Slope(Corner corner, out Color color, Land land) { float height = land.heights.Sample(corner.uv).r; float snow = Math.Saturate(height / 40); color = Color(snow, 0.6 + 0.4 * snow, snow); // Green in the valleys, white at 40 and up } ``` - The numbers are the grid's own, not clamped to 0 to 1: a cell that's 40 reads as 40, and one that's -3 as -3. - The GPU's copy is a float of 16 bits a cell, which every device Tide draws on can blend between cells. That's about three digits, up to 65504 either way: a bigger number reads as that, and a cell that's NaN as 0. The grid itself keeps its 32 bits for the code that reads it. - Drawn with no frag, it's red: the vertex's color times `(r, 0, 0, 1)`. It's a frag that makes something of the number. ### Grids of other numbers A grid of pairs, of four numbers, of ints or of bytes is a texture of its numbers too, read through the [typed role](#doc-game--shaders--number-images) of what it holds: a `Grid2` is a `[Raw(float2)] Texture`, a `Grid2` a `[Raw(float4)] Texture`, and a `Grid2` or a `Grid2` a `[Raw(int)] Texture`. A frag samples one by its name, or through a field or a helper of its role, and gets the cells' numbers as they are: ```csharp local singleton Wind { Grid2 flow = Grid2(128, 128); // Written by the CPU, a few cells a frame Grid2 zones = Grid2(128, 128); [Raw(float2)] Texture kept; } frag Drift(Corner corner, out Color color, Wind wind) { float2 push = wind.flow.Sample(corner.uv, Filter.Bilinear); // Blended between cells int zone = wind.zones.Sample(corner.uv); // The nearest cell's, exactly color = Color(0.5 + push.x, 0.5 + push.y, zone == 3 ? 1 : 0); } ``` - **Where a role takes it.** A grid of numbers goes into a field of its role (`wind.kept = wind.flow;`), to a helper's parameter of its role (`float2 Push([Raw(float2)] Texture flow, float2 uv)`), and as the source a draw or a `Draw.Blit` gives a frag whose `Texture` has its role. A plain `Texture`, a local, a return and a draw with no frag would read it as colors, so they're errors that say which role takes it. - **On the GPU,** pairs and fours are 16-bit floats (two or four a cell), which every device blends and makes smaller images of, as a `Grid2`'s cells are; ints and bytes are a 32-bit int a cell, read at the nearest cell, a byte as its 0 to 255. A float past what a half holds reads as 65504 or -65504. - **What changed is what's sent,** as for a grid of colors: a cell written this frame sends that much, not the grid. - Grids of other cells (bools, longs, structs) and `Grid3`s of numbers aren't textures; read their cells by place, `grid[x, y]`. ### Past the edges A texture's own pixels are where `uv` goes from 0 to 1. What a `uv` past those reads is its wrap, which a draw says after the filter: ```csharp Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], art.tile, Filter.Point, Wrap.Repeat); ``` - `Wrap.Clamp` reads the pixels at the texture's edge. It's what a texture that says nothing has. - `Wrap.Repeat` reads the texture again: 1.25 reads what 0.25 does. It's for tiles, and for what scrolls. - `Wrap.Mirror` reads the texture again, the other way round each time: 1.25 reads what 0.75 does, so no seam shows where its edges don't match. The quad below has uvs that go three times across its texture and three times down, and the white square is where they go from 0 to 1. Scroll it, and switch between the three. **A texture, past its edges** ([Run example](https://tide-engine.dev/examples/wrap/?stats)) ```tide settings { title = "Wrap"; } local scene Main { } local singleton Tiles { Grid2 tile = Grid2(8, 8); bool ready; Wrap wrap = Wrap.Repeat; bool scroll; float slide; } view Show(mut Tiles tiles) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, -0.1), 2); if (!tiles.ready) { // A frame, an L and a dot: each copy shows which way round it is. foreach (var at in tiles.tile) { bool frame = at.x == 0 || at.y == 0 || at.x == 7 || at.y == 7; bool letter = (at.x == 2 && at.y >= 2 && at.y <= 5) || (at.y == 5 && at.x >= 2 && at.x <= 5); bool dot = at.x == 5 && at.y == 2; tiles.tile[at] = letter ? Color(0.98, 0.75, 0.14) : dot ? Color(0.18, 0.83, 0.75) : frame ? Color(0.24, 0.25, 0.27) : Color(0.13, 0.13, 0.15); } tiles.ready = true; } if (tiles.scroll) tiles.slide += Frame.dt * 0.25; if (tiles.slide >= 2) tiles.slide -= 2; // Its uvs go three times across and three times down. The grid's own cells // are where they go from 0 to 1, and the wrap says what the rest reads. var first = float2(tiles.slide - 1, -1); var last = first + float2(3, 3); List corners = [ Vertex { position = float2(-1.5, 1.5), uv = first }, Vertex { position = float2(1.5, 1.5), uv = float2(last.x, first.y) }, Vertex { position = float2(1.5, -1.5), uv = last }, Vertex { position = float2(-1.5, -1.5), uv = float2(first.x, last.y) }, ]; Draw.Mesh(corners, [0, 1, 2, 0, 2, 3], tiles.tile, Filter.Point, tiles.wrap); // Where the uvs are from 0 to 1. Draw.Clip(Rect(-1.5, -1.5, 3, 3)) { Draw.WireRect(float2(-tiles.slide, 0), float2(1, 1), 0.03, Color.white); } Draw.SetScreen(); Draw.Text($"Wrap.{tiles.wrap}", float2(16, 14), 16, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40)) { GUILayout.Horizontal() { if (GUILayout.Button("Clamp")) tiles.wrap = Wrap.Clamp; if (GUILayout.Button("Repeat")) tiles.wrap = Wrap.Repeat; if (GUILayout.Button("Mirror")) tiles.wrap = Wrap.Mirror; GUILayout.Toggle("Scroll", tiles.scroll); } } } ``` - It's one wrap, for both ways across the texture, and it's written after the filter: a draw that says how it wraps says its filter too. A texture that's always wrapped one way says so where it's declared instead (below). - It's a value like the filter: a field, or `tiled ? Wrap.Repeat : Wrap.Clamp`. - It's how this draw reads the texture, and changes nothing of the image: one grid can be clamped in one draw and repeated in the next. So can a [render target's color](#doc-game--render-targets), and a texture of any size. - Blended, a cell at the edge blends with what the wrap says is past it: with `Wrap.Repeat` that's the cell at the opposite edge, which is what makes tiles meet without a seam. - `Wrap` is the engine's name: a game's own type or function takes another one, or a namespace. ### Drawn smaller A texture drawn smaller than it is has several of its pixels under each pixel of the screen. `Filter.Bilinear` reads the ones under the pixel's middle, and skips the rest: a tiled floor seen from far away shimmers as the camera moves, and a big image shown as a thumbnail looks grainy. `Filter.Trilinear` reads all of them: ```csharp Draw.Mesh(floor, faces, float4x4.identity, tiles, Filter.Trilinear, Wrap.Repeat); ``` - The engine keeps smaller copies of the texture for it, each half the size of the last, down to one pixel (its mipmaps), and the GPU blends between the two nearest the size the texture is drawn at. So a pixel is the mean of what it covers. - Drawn at its own size or bigger, it's the same as `Filter.Bilinear`. - **It's a filter like the others**: a draw's argument, a `Sample`'s in a [frag](#doc-game--shaders--textures), a declaration's `[Filter(Filter.Trilinear)]`, and what a `Texture` carries from there (below). - **Nothing to make or keep up to date.** For ordinary images, the copies are made the first time a draw reads the texture this way, and again when its pixels changed: a grid whose cells were written, a [render target](#doc-game--render-targets) that was drawn into. Automatically compressed assets and [authored DDS mipmaps](#doc-game--assets--authored-mipmaps) already contain their copies. - **What it costs**: for uncompressed textures, a third more memory on the GPU and making the copies, which is quick for an image that never changes and adds up for a big grid that changes every frame. Prepared asset mips upload with the image, including the full RGBA fallback on a device without its compressed format; selecting Trilinear adds no generation work. - It's for what's seen at a distance or at many sizes: floors and walls in 3D, a map you zoom out of, a target shown as a thumbnail. Pixel art at its own size wants `Filter.Point`. - A `Grid2` has them wherever the device can draw into floats, which is nearly everywhere (see [float images](#doc-game--render-targets--what-a-target-holds)); where it can't, it's read as `Filter.Bilinear`. ### Seen at a shallow angle Ground seen from a standing eye, a floor down a corridor, a road to the horizon: each pixel of the screen covers a long thin strip of the texture, a few of its pixels across and many along the line of sight. `Filter.Trilinear` picks its smaller copy by the strip's length, so the texture is blurred both ways, and a floor of leaves or planks that's crisp at your feet is a smooth smear a few metres on. `Filter.Anisotropic` picks the copy by the strip's width and reads several times along its length: ```csharp [Filter(Filter.Anisotropic), Wrap(Wrap.Repeat)] asset Texture planks = "art/planks.png"; Draw.Mesh(floor, faces, float4x4.identity, planks); // As its declaration says Draw.Mesh(floor, faces, float4x4.identity, tiles, Filter.Anisotropic, Wrap.Repeat); // ...or said at the draw ``` - **It's `Filter.Trilinear` and more**: the same smaller copies, made and kept the same way, and the same picture wherever a pixel covers about as much of the texture one way as the other (a wall faced head on, a sprite, anything in 2D). - **A filter like the others**: a draw's argument, a `Sample`'s and a `SampleGrad`'s in a [frag](#doc-game--shaders--textures), a declaration's `[Filter(Filter.Anisotropic)]`, and what a `Texture` carries. In a frag it has `Filter.Trilinear`'s rule for its `uv`, and with `SampleGrad` the strip is the two derivatives you give. - **Up to 8 reads along the strip**, as many as the strip is longer than it's wide; the GPU does them in hardware. A device that takes fewer does fewer, and one with none reads it as `Filter.Trilinear`: nothing to check, and no error. How a device reads along a strip is its own to decide: a software renderer (Mesa's lavapipe, as the Android emulator uses) reads a frag's `Sample` as `Filter.Trilinear` whatever the filter. - **What it costs** is those reads, only on the pixels seen at an angle: nothing on a surface faced head on, and up to 8 times the texture reads on ground running to the horizon. On a desktop GPU that's usually small beside the rest of a frame; where a frag reads many textures a pixel (ground of several blended photographs, each with its surface map), measure it, and keep it for the textures whose detail shows: the colour first, a normal map next, and `Filter.Trilinear` for what's smooth anyway (a mask, a height read many times a pixel). - It's for floors, ground, roads, water and long walls in 3D. A texture drawn in 2D, or always faced, gains nothing from it. ### Saying it once, on the texture How a texture is sampled is said in two places: on the texture, where it's made, and on the draw, for that draw. A texture that's always read one way says so where it's declared, with `[Filter(...)]` and `[Wrap(...)]`, each alone or both: ```csharp [Filter(Filter.Point), Wrap(Wrap.Repeat)] asset Texture tiles = "art/tiles.png"; [Filter(Filter.Point)] asset List frames = "art/run/*.png"; // Every one of them local singleton Art { [Filter(Filter.Point)] Grid2 canvas = Grid2(64, 64); [Filter(Filter.Point)] RenderTarget small; // Its color images Texture sprite; } view Floor(mut Art art) { Draw.Mesh(corners, faces, tiles); // Nearest, repeated: as tiles says Draw.Mesh(corners, faces, tiles, Filter.Bilinear); // Blended here, still repeated Draw.Mesh(corners, faces, tiles, Filter.Bilinear, Wrap.Clamp); // Both the draw's Draw.Mesh(corners, faces, frames[2]); // Nearest: as frames says Draw.Mesh(corners, faces, art.canvas); // Nearest: as the field says Draw.Mesh(corners, faces, art.small.color); // Nearest: as the target's field says art.sprite = tiles; Draw.Mesh(corners, faces, art.sprite); // Nearest, repeated: it's tiles } ``` - They go before an asset that's a `Texture` or a `Grid2` (one image, or a list or a map of them), and before a field that's a `Grid2`, a `Grid2` or a `RenderTarget`. - **A `Texture` carries it.** The texture made of that asset, that grid or that target is sampled as the declaration says wherever it goes: in a field, a local, a function's parameter. `art.sprite = tiles` draws as `tiles` does. So a `Texture` field takes neither attribute: it holds whichever texture it's given, which says it itself. - A texture with nothing said is blended and clamped. - What a draw says is for that draw, in the place of the texture's own, each of the two apart. In a frag, a `Sample` that says its filter or its wrap has what it says, and one that doesn't reads the texture as the texture says (see [Sampling a texture](#doc-game--shaders--textures)). ### Volumes `Texture3D` is a continuous volume, made in local code with a size in texels: ```csharp local singleton Fog { Texture3D density; } view MakeFog(mut Fog fog) { if (fog.density.contentRevision == 0) fog.density = Texture3D(int3(32, 16, 32), Format.Rgba16f); } ``` Fill it with a [compute kernel](#doc-game--shaders--writing-images). In GPU code, `density.Sample(float3(x, y, z))` blends the eight neighboring cells on all three axes. Coordinates are normalized from 0 to 1; `Filter.Point` picks the nearest cell, and an optional `Wrap.Clamp`, `Wrap.Repeat` or `Wrap.Mirror` applies on all axes. The defaults are Bilinear and Clamp. There are no volume mipmaps, so Trilinear, Anisotropic and SampleLevel are unavailable. `density[int3(x, y, z)]` reads an exact cell, with zeros outside. Volumes can also store numbers: R32f, Rgba32f and R32i hold a float, four floats or a signed integer per cell, respectively. Declare `[Raw(float)] Texture3D density;`, `[Raw(float4)] Texture3D channels;` or `[Raw(int)] Texture3D ids;`, and construct the volume with the matching Format. A kernel stores that numeric type directly; `Sample` and exact-cell reads return it without alpha conversion. A typed volume reads its nearest cell where `Sample` names no filter, and with `Filter.Bilinear` blends its eight cells around: an Rgba16f volume (all four channels as data, through `[Raw(float4)]`) and a `Grid3` through the GPU's own filtering, an R32f or Rgba32f volume as its eight cells loaded exactly and blended in the shader, the same bits on every device. An int volume reads its nearest cell only. See [Number images](#doc-game--shaders--number-images). ```tide float4 fog = cloud.channels.Sample(uvw, Filter.Bilinear); // [Raw(float4)] Texture3D of Rgba16f: four numbers, blended ``` `Grid3` and `Grid3` convert to `Texture3D` where one is wanted. A float grid supplies its value as red, with green and blue zero and alpha one. Changes upload only the changed regions, as a two-dimensional grid's texture does. A `TextureArray` keeps its layers separate; a volume blends along z too. Grid conversions are sampled views of CPU data. To write on the GPU, create an owned `Texture3D`. Copies share the volume. `Resize(int3)` replaces it with an empty image; `Dispose()` releases it; `size` is an `int3`, and `contentRevision` changes when pixels are discarded, including device loss or hot reload. Refill when that revision changes. Volumes are machine-local and cannot be match state. Each axis is at most 2048 and the image at most 128 MiB, subject to the device's limits; one that cannot fit is empty and reports the problem once. There is no volume file-asset declaration or drawing into a volume slice. ### Six of them, as a cube A `Cubemap` is six images that are read by a direction where a `Texture` is read by a `uv`: a sky, or what a mirror sees. It isn't a mesh's texture; a frag reads it, `sky.Sample(direction)`. An asset's is six files, and `Cubemap(size)` is one whose six faces are render targets, `cube.faces[0]` to `cube.faces[5]`. See [Skybox and reflections](#doc-game--shaders--skybox-and-reflections). `cube.Resize(size)` changes all six faces. Hot reload keeps their current size, including after a resize, and copies of the cube still share the same images. Their rendered contents are cleared on the web when the images are recreated. --- Source: https://tide-engine.dev/game/3d.md Draw 3D in Tide: meshes through a 3D camera, cube, sphere, cylinder and plane primitives, depth for what is solid or see-through, which side of a triangle draws, and big scenes. # Drawing in 3D [Meshes](#doc-game--meshes-and-textures--meshes) have a 3D version, which goes through a camera of its own. A corner is a `Vertex3`: ```csharp struct Vertex3 // Built in { float3 position; float2 uv; Color color = Color.white; } ``` `Draw.SetCamera(position, rotation, fieldOfView)` sets the 3D camera: where it is, which way it looks, along its rotation's `+z` with `+x` to the right and `+y` up as Unity's cameras do, and how much it sees up and down, in degrees, like Unity's `Camera.fieldOfView`. It sees from 0.3 units in front of it on, however far, and as much across as the screen's shape gives. `Draw.Mesh(vertices, indices, transform)` draws a 3D mesh through it, placed in the world by `transform`, which `float4x4.TRS(position, rotation, scale)` makes: ```csharp local singleton Scenery { List crate; List faces; Grid2 wood = Grid2(16, 16); } view Look(Viewer viewer) { Draw.Clear(Color(0.5, 0.7, 1)); Draw.SetCamera(viewer.position, viewer.rotation, 60); } // Once for each crate, and drawn for them all at once view Crates(Crate crate, Scenery scenery) { Draw.Mesh(scenery.crate, scenery.faces, float4x4.TRS(crate.position, crate.rotation, float3(1)), scenery.wood); } ``` - 3D meshes hide each other by how far they are, whatever order they're drawn in. Everything else draws over what's there, in order, through the camera it had before: a view can draw a 3D scene and then a HUD over it, with no camera call between. `Draw.Clear` clears what's in front too. - A see-through mesh blends with what's behind it, and still hides what's drawn behind it later, unless it's drawn with [`Draw.Depth(Depth.Read)`](#doc-game--3d--depth): draw see-through meshes last, the farthest first. See [Transparency](#doc-game--draw-settings--transparent-3d) for the full recipe, and [cutout holes](#doc-game--draw-settings--cutout-holes) for solid pixels with gaps between them. - A triangle is drawn from its front, the side its corners go clockwise on, and not from its back: see [Which side draws](#doc-game--3d--which-side-draws). A face that's missing is usually a triangle wound the other way. - Textures, filters and [wraps](#doc-game--meshes-and-textures--past-the-edges) work as a mesh's do: `Draw.Mesh(vertices, indices, transform, texture, filter, wrap)`. - There's no lighting built in: a pixel is its corners' colors times its texture's. A [`frag`](#doc-game--shaders) lights it your way, with normals in a vertex struct of your own, which [`instance.Normal`](#doc-game--shaders--where-the-pixel-is) gives as they are in the world. - A mesh needn't be made in code: `asset Mesh crate = "art/crate.glb";` is a model from a glTF, FBX or OBJ file, and `Draw.Mesh(crate, transform)` draws it, the mesh where its two lists would go. See [Meshes](#doc-game--assets--meshes). - Lists made in code become a `Mesh` value with `Mesh(vertices, indices)`: kept in a field, it's one mesh on the GPU wherever it's drawn, with no list read each frame. See [Meshes](#doc-game--assets--meshes). - Shapes made in code (boxes, spheres, ground cut into cells, pieces merged into one mesh) are what the [Geometry package](#doc-packages--geometry) makes, into the same two lists, for any vertex struct. - Each frame starts with the 3D camera at the origin, looking along `+z`, with a field of view of 60 degrees. A game's C draws 3D meshes too, with vertices of its own, like a model a library loaded: see [Drawing from C](#doc-c--functions--drawing-from-c). A model with bones uses `SkinnedMesh`. `Draw.SkinnedMesh(model, transform)` draws its authored rest pose, even without animation clips; pass a sampled `Pose` after the transform to animate it. See [Skinned meshes and animation](#doc-game--animation) for playback, separate animation files, blending, procedural bone edits and sockets usable by both systems and views. ## Primitives The primitives draw solid colors through the current 3D camera, with depth and no lighting, as meshes do. Cube, cylinder and plane also take a rotation before the color: ```csharp Draw.Cube(float3(0, 0, 5), float3(2, 1, 1), Color.red); Draw.Sphere(float3(3, 0, 5), 1, Color.green); Draw.Cylinder(float3(-3, 0, 5), 0.5, 2, Color.blue); Draw.Plane(float3(0, -1, 5), float2(10, 10), quaternion.identity, Color.gray); ``` Nonpositive dimensions draw nothing. Geometry is cached by shape and color; consecutive instances of the same shape and color are drawn together. Use a mesh with a frag for textures or lighting. They're solid: a cube, a sphere and a cylinder are [drawn from outside](#doc-game--3d--which-side-draws), and a plane from above, its local `+y`. A plane tipped to face the camera is turned so that its top does: `quaternion.AxisAngle(float3(1, 0, 0), -Math.PI / 2)` stands one up to face a camera that looks along `+z`. Everything below is a primitive: a plane, 81 cubes, a sphere and a cylinder, drawn again every frame through a camera that circles them. Drag to turn it yourself, and change its field of view with the slider. **Primitives through a 3D camera** ([Run example](https://tide-engine.dev/examples/draw3d/?stats)) ```tide settings { title = "3D"; } local scene Main { } local singleton Orbit { float yaw = 0.7; float pitch = 0.6; float fieldOfView = 50; float wave; } view Scenery(Devices devices, mut Orbit orbit) { // Drag to look around. Left alone, the camera circles by itself. var pointer = devices.pointer; if (pointer.press.pressed) { orbit.yaw += pointer.delta.x * 0.01; orbit.pitch = Math.Clamp(orbit.pitch - pointer.delta.y * 0.01, 0.15, 1.4); } else orbit.yaw += Frame.dt * 0.25; orbit.wave += Frame.dt * 1.5; if (orbit.wave > Math.TAU) orbit.wave -= Math.TAU; // The camera looks along its rotation's +z, from 14 units behind the middle. var rotation = quaternion.Euler(float3(orbit.pitch, orbit.yaw, 0)); Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float3(0, 1, 0) - Math.Forward(rotation) * 14, rotation, orbit.fieldOfView); // 3D draws hide each other by depth, whatever order they come in. Draw.Plane(float3(0, 0, 0), float2(11, 11), Color(0.13, 0.13, 0.15)); for (var x = -4; x <= 4; x++) { for (var z = -4; z <= 4; z++) { var height = 1.3 + Math.Sin(x * 0.8 + orbit.wave) * Math.Cos(z * 0.8) * 1.1; var shade = height * 0.3; Draw.Cube(float3(x, height * 0.5, z), float3(0.92, height, 0.92), Color(0.3 + shade, 0.22 + shade * 0.75, 0.08 + shade * 0.08)); } } Draw.Sphere(float3(0, 4.2, 0), 0.7, Color(0.18, 0.83, 0.75)); Draw.Cylinder(float3(0, 3, 0), 0.08, 1.6, Color.white); Draw.SetScreen(); Draw.Text("Drag to turn the camera", float2(16, 14), 16, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Field of view", orbit.fieldOfView, 25, 90); } ``` ## Depth 3D meshes hide each other by how far they are, whatever order they're drawn in: each one is hidden behind what's nearer, and hides what's drawn behind it later. That's `Depth.ReadWrite`, which every frame starts with, and it's right for everything solid. `Draw.Depth` says otherwise: | Mode | What a 3D mesh does | For | |---|---|---| | `Depth.ReadWrite` | Is hidden behind what's nearer, and hides what's drawn behind it later | Everything solid: the default | | `Depth.Read` | Is hidden behind what's nearer, and hides nothing | What's see-through: glass, smoke, a shadow or a mark lying on a floor | | `Depth.None` | Draws over whatever is there, and hides nothing | A marker that shows through walls, a sky drawn before everything | | `Depth.Only` | Is hidden and hides as `Depth.ReadWrite` does, and draws no color | A [depth pre-pass](#doc-game--3d--a-depth-pre-pass): the depth of what a later draw lights | | `Depth.Equal` | Shows only where its depth is the depth already there, and hides nothing | Lighting after a [depth pre-pass](#doc-game--3d--a-depth-pre-pass), each pixel once | A see-through mesh that writes depth hides what's behind it, though that should show through it. Drawn with `Depth.Read`, it's still behind the crate in front of it, and whatever is see-through behind it shows: ```csharp // What's solid, in any order view Crates(Crate crate, Scenery scenery) { Draw.Mesh(scenery.crate, scenery.faces, float4x4.TRS(crate.position, crate.rotation, float3(1))); } // Then what's see-through: behind the crates in front of it, and hiding nothing view Windows(Pane pane, Scenery scenery) { Draw.Depth(Depth.Read) { Draw.Mesh(scenery.glass, scenery.faces, float4x4.TRS(pane.position, pane.rotation, float3(1))); } } ``` - **Draw what only reads depth after what's solid.** A mesh is hidden behind what was already drawn in front of it, so the panes come after the crates: views run in the order they're declared, or in the order of their [stages](#doc-game--systems--named-phases). - **Among themselves, they go over each other in the order they're drawn,** like 2D shapes do. Where that shows, draw the farthest first. Shadows that only darken look the same in any order. - **Something flat on a surface is drawn a little off it.** A decal exactly where the floor is has the floor's own depth, and which of the two wins changes from pixel to pixel. A few millimeters above it is enough, and every decal on the floor can be at that one height, since they don't hide each other. Or draw it exactly on the floor with a [depth bias](#doc-game--shaders--depth-bias), which pulls it nearer by a few of the depth's own steps: `Draw.DepthBias(-8, -1) { Draw.Mesh(decal, faces, transform); }`. - **It's for 3D meshes of every kind:** `Draw.Mesh`, the [primitives](#doc-game--3d--primitives), meshes [through a frag or a vert](#doc-game--shaders) and `Draw.Instanced`. Instances drawn in a row with the same setting are still one draw. - **A render target has its own,** as it has its own camera: `target.Depth(Depth.Read) { target.Mesh(...); }`. `Draw.Depth` is the window's, and doesn't reach a target's meshes. - **Nothing else has depth:** shapes, text and 2D meshes draw over what's there, in order, whatever is set. `Draw.Clear` clears depth whatever is set, and [`Draw.Blit`](#doc-game--render-targets--post-processing) leaves it as it is. - **`Draw.ClearDepth()` sets depth back and nothing else.** The picture stays, and the 3D meshes drawn after it are in front of everything drawn before, however near that was: a first-person tool drawn over the world never goes into a wall. It fills the screen, or what a clip leaves of it, and leaves stencil alone. A render target has it too: `target.ClearDepth()`. ### A depth pre-pass Where many cut-out meshes stand behind each other, as the leaves of a forest do, the GPU lights every leaf before it knows whether a nearer one covers it: a frag that can [discard](#doc-game--draw-settings--cutout-holes) or [cut out](#doc-game--shaders--cut-outs) has to run before its depth is known. When the lighting is expensive, draw the meshes twice: once for depth alone, through a cheap frag that only cuts, and again lit, where each pixel's depth is already the nearest leaf's. The lit draw needs no discard, and runs once for each pixel it covers: ```csharp local singleton Forest { List leaf; List faces; List leaves; // Every leaf of every tree Texture image; } // Only what's cut: the alpha, and no lighting. Its color goes nowhere frag LeafCut(Vertex3 vertex, out Color color, Forest forest) { color = Color.white; this.Cutout(forest.image.Sample(vertex.uv).a); } // All of the lighting, with no discard and no cut frag LeafLit(Vertex3 vertex, out Color color, Forest forest) { color = forest.image.Sample(vertex.uv); // ...shadows, haze, a normal map } view Trees(Forest forest) { // The nearest leaf's depth at each pixel, at each of its samples Draw.Depth(Depth.Only) { Draw.Instanced(forest.leaf, forest.faces, forest.leaves, LeafCut); } // Lit only where that depth is its own: once a pixel Draw.Depth(Depth.Equal) { Draw.Instanced(forest.leaf, forest.faces, forest.leaves, LeafLit); } } ``` - **Draw both the same way:** the same mesh, the same instances and transforms, the same camera, and the same vert (or none). Each lands on exactly the same depth, through any two frags, and through the engine's own mesh drawing too; a vert that moves corners differently in the two, or another level of detail, leaves holes. - **`Depth.Only` writes depth and stencil as `Depth.ReadWrite` does, and no color,** in any of the target's images: its frag still runs, so `this.Discard()`, `this.Cutout` and `this.Coverage` cut its depth as they would a lit draw's. Its color is never seen; white is as good as any. - **With [samples](#doc-game--render-targets--smooth-edges), depth is each sample's.** The pre-pass's cut-out covers the samples its edge covers, and the lit draw is drawn at exactly those: a leaf's edge is as smooth as it was, without its lit frag cutting again. The lit frag can still discard or cover less; it never covers more than the pre-pass did. - **`Depth.Equal` writes no depth,** and passes only where the depth there is its own: behind the pre-pass's nearest leaf it's hidden, and so is anything the pre-pass didn't draw at all. Drawn twice, it's lit twice: it hides nothing, as `Depth.Read` doesn't. - **It pays where hidden pixels are expensive.** The pre-pass costs the meshes' corners again, and its frag: with cheap lighting, or little hidden, it can cost more than it saves. Measure with a [profile capture](#doc-tools--debug-views--finding-expensive-gpu-passes). - **On every backend:** Vulkan, WebGPU and Unity. ## Which side draws A triangle of a 3D mesh has a front and a back. Its front is the side its corners go clockwise on, in the order its indices list them, and a triangle seen from the back isn't drawn. For a closed solid mesh, this avoids shading faces turned away from the camera, which are hidden behind its near faces anyway. ```csharp // A square facing a camera that looks along +z: from there, its corners go clockwise scenery.card = [Vertex3 { position = float3(-1, 1, 0) }, Vertex3 { position = float3(1, 1, 0) }, Vertex3 { position = float3(1, -1, 0) }, Vertex3 { position = float3(-1, -1, 0) }]; scenery.faces = [0, 1, 2, 0, 2, 3]; ``` **Tip** A face that's missing is usually a triangle wound the other way. Swap two of its three indices (`0, 1, 2` becomes `0, 2, 1`) and it's back. A whole mesh that looks hollow, showing its far side's inside, has every triangle the wrong way round. That's `Cull.Back`, which every frame starts with. `Draw.Cull` says otherwise: | Side | Which triangles draw | For | |---|---|---| | `Cull.Back` | The ones seen from the front | Everything solid: the default | | `Cull.Front` | The ones seen from the back | The inside of a shell: a room seen from within, a sky dome | | `Cull.None` | All of them | What's flat or see-through: a leaf, a flag, a pane of glass | ```csharp // A leaf is one square, seen from either side view Leaves(Leaf leaf, Scenery scenery) { Draw.Cull(Cull.None) { Draw.Mesh(scenery.card, scenery.faces, float4x4.TRS(leaf.position, leaf.rotation, float3(1))); } } ``` - **A triangle's front stays its front, whatever it's drawn through.** A transform that mirrors a mesh (a scale of `-1` along one axis, to make a left hand of a right one) turns its triangles round on the screen, and the engine accounts for it: the mesh's own transform, [`Draw.Transform`](#doc-game--draw-settings--transforms) and a camera that mirrors the world, like one placed for a reflection. Mirrored and unmirrored meshes drawn in a row are drawn apart, a draw each. - **A transform that flattens a mesh leaves it no front.** Squashed onto a plane, as for a shadow lying on a floor, the triangles of its near side and of its far side land on each other, wound opposite ways. Draw it inside `Draw.Cull(Cull.None)`. - **See-through and closed, a mesh shows its near side alone.** For a glass ball's far side to show through its near one, draw it inside `Cull.None`, or twice: inside `Cull.Front` first, then as usual. - **A [`vert`](#doc-game--shaders) that turns triangles round is yours to draw for.** The engine goes by the transforms it's given: one that mirrors its mesh itself (`vertex.position.x = -vertex.position.x`) is drawn inside `Cull.Front`. - **The [primitives](#doc-game--3d--primitives) are solid,** their fronts outside. A plane has one side, its top: seen from below it isn't drawn, unless it's inside `Cull.None`. - **It's for 3D meshes of every kind:** `Draw.Mesh`, the primitives, meshes through a frag or a vert and `Draw.Instanced`. Instances drawn in a row with the same setting are still one draw. - **A render target has its own,** as it has its own depth setting: `target.Cull(Cull.None) { target.Mesh(...); }`. A triangle's front is the same side there. - **Nothing in 2D has a back:** a 2D `Draw.Mesh` draws its triangles whichever way they're wound, whatever is set. ## Frustum culling Tide skips ordinary 3D mesh instances whose bounds are completely outside the destination's camera. This is automatic for primitives, meshes from lists or assets, and meshes with a fragment shader alone. Bounds are cached with the geometry, and each instance is tested separately. A box crossing the camera's boundary stays drawn. Skinning and custom vertex shaders can move vertices beyond the original geometry. Those draws stay enabled unless you supply a conservative box containing the resulting vertices, in mesh-local space before the instance transform and `Draw.Transform`: ```csharp Draw.Bounds(float3(0, 1, 0), float3(3, 4, 3)) { Draw.SkinnedMesh(art.character, transform, pose); } ``` `size` is the box's full width, height and depth. Include all animation and shader displacement. `Draw.SetBounds(center, size)` sets it for later draws; `Draw.SetBounds()` restores automatic bounds. `Draw.Bounds() { ... }` restores them within a block. Invalid bounds keep the draw. `Draw.FrustumCulling(false) { ... }` disables the test within a block. `Draw.SetFrustumCulling(false)` disables it for later draws, and `Draw.SetFrustumCulling()` enables it again. Every frame starts with culling enabled and automatic bounds. These settings affect 3D meshes alone; `Draw.Cull` still controls triangle faces separately. Every render target uses its own settings and camera, including shadow passes. `Draw.LODCamera` changes only detail selection. An object outside the player's camera can still draw into a shadow map. Culling skips drawing, never views, operand evaluation, match simulation or network updates. Animation sampling and skin-palette capture can still run before a draw is rejected. Games with large worlds can additionally select nearby chunks before issuing draws to save that earlier work. Frustum culling doesn't test whether another object hides a mesh: occlusion culling, below, does. ## Occlusion culling A field of grass behind a hill, or a town's props behind its houses, is mostly hidden. With occlusion culling on, Tide skips the instances of a list drawn instanced that what's already drawn in the frame surely hides, tested on the GPU against the depth drawn so far: ```csharp DrawTerrain(target); // ...and the houses: whatever hides things, drawn first target.SetOcclusion(true); foreach (Patch patch in field.patches) target.Instanced(grass, patch.blades, GrassVert, GrassFrag); target.SetOcclusion(); ``` `Draw.Occlusion(true) { ... }` turns it on within a block, and `Draw.SetOcclusion(true)` for the draws that follow; every frame starts with it off. Like the other settings, the window and each render target have their own. The frame's pixels are the same as without it: an instance is left out only where every pixel it could cover already holds something nearer, so it would have failed the depth test anyway. That holds whatever was drawn before (see-through or not), however the camera or the scene moves, from the first frame. What it takes, and what it costs: - It applies to `Draw.Instanced` over a list, in 3D, through a shader, where frustum culling applies: the same [bounds](#doc-game--3d--frustum-culling), and frustum culling on. Other draws are drawn as ever, and still hide what's behind them. - Draws under a [depth bias](#doc-game--shaders--depth-bias), and frags that [write their own depth](#doc-game--shaders--writing-a-pixel-s-depth), are never tested: their depth isn't where their bounds say. They're drawn whole, and still hide what's behind them. - What hides them is what was drawn into that destination before the first of them, since the frame began or its depth was last cleared: draw the terrain, the walls and the big things first. Draws with it on don't hide each other. Where nothing was drawn into the destination since then, there's nothing to hide them and nothing is measured. - Before the first of them, Tide measures the depth drawn so far (a depth pyramid of it). Where the destination's drawing already stopped for something else since the big things were drawn (something drawn into another target, a `GPU.Run`), Tide measures it there, and what's drawn between doesn't hide them; otherwise the measure splits the destination's drawing in two. Either way it costs a little GPU time: about 0.05 ms a frame at 1920 by 1080, more into a target of several samples. Draws with it on that follow each other are tested against the same measure, other draws between them too; an instanced list drawn without it, one with it into another destination, or a clear starts another measure. So it pays where much is hidden, and it's off unless you ask for it. - The stats show how many instances it tested and hid (`--profile`'s report, `"occlusion"`). ## Big scenes `Draw.Instanced(vertices, indices, transforms)` draws the mesh at every `float4x4` in a list, without an entity for each placement; a [mesh from a file](#doc-game--assets--meshes) goes where the two lists do, `Draw.Instanced(tree, transforms)`. It can also take a list of your own instance struct, with per-item fields read by a vert or frag: see [Instances from a list](#doc-game--shaders--instances-from-a-list). The lists a 3D mesh is drawn from are kept on the GPU while frames draw them. An unchanged list needs no upload each frame, so keep meshes in fields rather than making them each frame. The GPU still processes its vertices and pixels: reuse avoids uploading the geometry, rather than making a large mesh free to render. A list that changed is sent again the next frame. A model from a file that's drawn many times, near and far, can have simpler versions made for where it's small: `[LOD]` before its asset, and each instance then draws the simplest one that looks the same there. See [Levels of detail](#doc-game--assets--levels-of-detail). A mesh your game makes gets them with `lod:` on its draw: `Draw.Mesh(vertices, indices, transform, lod: 1)`. A mesh baked for an entity of the match goes in [local fields](#doc-game--local-state--local-fields) of its component: this machine's, which the view bakes once and draws from, and which the match never carries. A list in an ordinary field is part of the match, so every player who joins downloads it, though no system reads it. ```csharp component Rock { float3 position; int seed; local List corners; local List faces; } view Rocks(mut Rock rock) { if (rock.corners.count == 0) Carve(rock); // Fills corners and faces from the seed, once Draw.Mesh(rock.corners, rock.faces, float4x4.Translate(rock.position)); } ``` A mesh many entities share, like the crate above, is one list in a singleton, or a local one. A mesh drawn again and again in a row, from the same lists, with the same texture, filter and wrap, is drawn all at once: a view that runs for each of thousands of entities and draws one mesh costs the GPU one draw. Something drawn between them, like another mesh or a camera, starts another. --- Source: https://tide-engine.dev/game/animation.md Import skinned glTF or FBX models, sample, retarget and blend deterministic poses, use bone sockets, and draw animated characters in Tide. # Skinned meshes and animation A `SkinnedMesh` holds a model's geometry, skeleton and animation clips. A `Pose` holds one character's current bone transforms. Several characters can share the same model while playing different animations. Keep a named model selection in a component with `Asset>`: ```csharp asset SkinnedMesh hero = "art/hero.glb"; component CharacterArt { Asset> model = hero; } view DrawCharacter(CharacterArt art) { Draw.SkinnedMesh(art.model.Value, float4x4.identity); } ``` `.Value` resolves the current packed model, preserving imported LODs and shared skin palettes. It exposes the declared type's dynamic catalogs; use the original asset for its inferred clip and bone names. A borrowed or decoded model value cannot supply declaration identity. References compare by named asset identity with `==` and `!=`; empty or unknown references resolve to an empty model. Storing the resolved model itself uses ordinary owned value semantics. ## Import and draw Import a glTF 2.0 `.glb` or `.gltf`, or a binary or ASCII `.fbx`, with your [vertex struct](#doc-game--assets--meshes). A model needs no animation clips to draw: leaving out the pose draws its authored rest pose. ```csharp asset SkinnedMesh hero = "art/hero.glb"; view Character() { Draw.SkinnedMesh(hero, float4x4.identity); } ``` `hero.defaultPose` makes an owned pose with the same rest transforms, ready to edit or keep in a field. `hero.skeleton.RestPose()` remains available too. The rest pose belongs to the model's skeleton, independently of its animation catalog. To animate it, sample a clip and pass the resulting pose: ```csharp asset SkinnedMesh hero = "art/hero.glb"; component Character { float3 position; float seconds; } system Animate(mut Character character, Time time) { character.seconds += time.dt; } view Characters(Character character) { var pose = hero.animations.idle.Sample(character.seconds, Playback.Loop); Draw.SkinnedMesh(hero, float4x4.Translate(character.position), pose); } ``` `Draw.SkinnedMesh(mesh, transform[, pose])` takes the same texture, vert, frag and values arguments as a [3D mesh](#doc-game--3d), and also works on a render target. The optional pose goes immediately after the transform; textures and shaders can follow the transform directly when no pose is supplied. Deformation applies before your `vert`, which receives the posed mesh-local position, normal and tangent. Each draw captures the pose as it is at that call, so later edits or samples do not change characters already drawn. The renderer can batch consecutive compatible draws of an imported model even when their poses differ. Different shaders, textures, shared values or draw settings can separate those batches. For a list of characters, pass the skinned model to `Draw.Instanced`: ```csharp struct CharacterInstance { float4x4 transform = float4x4.identity; Pose pose; Color tint = Color.white; } frag CharacterColor(Vertex3 vertex, CharacterInstance item, out Color color) { color = vertex.color * item.tint; } view Crowd() { Draw.Instanced(hero, [ CharacterInstance { pose = hero.defaultPose }, CharacterInstance { transform = float4x4.Translate(float3(3, 0, 0)), pose = hero.defaultPose, tint = Color.blue } ], CharacterColor); } ``` The optional `float4x4 transform` field follows the existing 3D instance convention; leaving the field out uses identity. The optional `Pose pose` field supplies that item's animation. Leaving the field out uses authored rest, including on a model with no clips; an explicitly invalid or incompatible pose skips its item. A `List` draws all items at rest. Pose data stays on the CPU, while shaders receive only the ordinary instance fields they read. Textures, custom vertex stages, shared values and render targets use the usual `Instanced` argument order. Each item captures its pose before the call returns. A crowd seen from afar needs fewer triangles a character: `[LOD] asset SkinnedMesh hero = "art/hero.glb";` has simpler versions of the model made as the game builds, and each draw picks one by how big the character is on screen. The pose, the bones and every lookup are the full model's; only the triangles drawn change. The model's size for the pick is its size at rest. See [Levels of detail](#doc-game--assets--levels-of-detail). A model decoded while the game runs has no declaration to mark: draw it with `lod: 1` for the same levels, made in the background. An FBX declaration works the same way: `asset SkinnedMesh hero = "art/hero.fbx";`. Import happens when the game builds, without Autodesk software. FBX axes and units become Y-up meters in Tide's coordinate system. Its animation stacks become clips beginning at zero, with their authored duration. Nonlinear transform curves are resampled at 60 samples per second into LINEAR channels, retaining source keys within the clip and stepped changes. Rotation curves are Euler angles that exporters often write wrapped (-182° then 178°, one degree apart): each key is first moved by whole turns to within half a turn of the key before it, and written as the nearer of its two equivalent triples (x + 180°, 180° − y, z + 180° is the same rotation) where all three axes are keyed together, as an Euler filter does, so resampled keys between them take the short way. Geometry and inheritance transforms may add unnamed helper bones. The packed model uses the same format and sampling APIs as a glTF import. Export polygon meshes with linear or rigid skinning. A skin 3ds Max or Unreal marks `Blend` imports as linear when none of its vertices blends in dual-quaternion skinning, as is usual. Skinned FBX imports reject dual-quaternion skinning, several skin deformers on one mesh and external vertex caches. Blend shapes (morph targets) are kept: see [Blend shapes](#doc-game--animation--blend-shapes); a channel repeated exactly on a mesh (same name and offsets, weight 0) is one shape. Static `Mesh` imports ignore those deformations and use the rest geometry. ## Blend shapes A skinned model keeps its file's blend shapes (glTF morph targets, FBX blend shapes): body shapes such as `defaultHeavy`, or facial ones such as `jawOpen`. `model.Shaped(weights)` returns the model with those weights applied, computed on the CPU, and draws, samples and stores like the model itself: ```csharp asset SkinnedMesh torso = "art/torso.fbx"; component Character { float heavy; float bakedHeavy = -1; SkinnedMesh body; } system Shape(mut Character character) { if (character.heavy == character.bakedHeavy) return; mut List weights = []; for (int i = 0; i < torso.blendShapes.count; i++) { torso.blendShapes.TryGetAt(i, out var shape); weights.Add(shape.name == "defaultHeavy" ? character.heavy : shape.weight); } character.body = torso.Shaped(weights); character.bakedHeavy = character.heavy; } view DrawCharacter(Character character) { Draw.SkinnedMesh(character.body, float4x4.identity); } ``` `model.blendShapes` lists the model's shapes in order. `count`, `TryGetAt(index, out BlendShape result)` and `TryGetByName(name, out BlendShape result)` work as the animation catalog's do; a missing, empty or unnamed name returns `false` and assigns `default`. A `BlendShape` has its original `name` and `weight`, the file's default weight, which the model's vertices already have. Weight `i` of `Shaped` is shape `i`'s weight. 0 to 1 is the authored range, and other values extrapolate. A missing weight, or one that isn't a finite number, keeps the shape's default, so `model.Shaped([])` is the model as imported. Each shape whose weight differs from its default moves the vertex fields the file fills by name, `position`, `normal` and `tangent`, by its delta times the difference; other fields, such as `uv`, `color` and fields with game defaults, are copied unchanged, as are the skeleton, animations, indices and levels of detail. Shapes apply in catalog order with plain float arithmetic, so the result is the same on every machine and can be used in match code. Normals and tangents are not renormalized. Bake a character's shapes once, when its body changes, and keep the shaped model in a field: `Shaped` copies the vertices, and drawing a shaped model sends its vertices to the GPU like other models made while playing. Shapes are not animated on the GPU, and imported shape-weight animation is not read. To keep only some of a file's shapes, and so a smaller pack, write `[BlendShapes("masculineFeminine", "default*")]` before the asset: names, or patterns where `*` is any run of characters. The others aren't imported; `[BlendShapes()]` keeps none. See [Blend shapes to keep](#doc-game--assets--blend-shapes-to-keep). ### Parts of a file Character packs often ship every outfit piece, at every level of detail, on one skeleton in one file, where a game wears a few of them. `[Parts(...)]` before a `SkinnedMesh` asset keeps only the parts it names: a part is a node holding a mesh, written by its name or a pattern where `*` is any run of characters. ```csharp [Parts("Body_Full_LOD0", "GreatHelm_LOD0", "Gambeson_LOD0")] asset SkinnedMesh knight = "art/MedievalCivil&Soldier_Complete.FBX"; ``` The other parts' meshes and skins are left out before they're read, so a file far past what one model can hold imports as the few parts it's asked for. Their nodes go with them, but every bone stays, and so do sockets and empty nodes that hold no part. An FBX geometry helper's mesh is its parent node's part. A file whose parts none of the patterns match is an error that names some of the parts it has. To retarget onto such a model, give its humanoid profile's `reference` the same list as `"parts"` (below), so the rig is that model's skeleton. In a glTF file, targets with the same name in `extras.targetNames` are one shape across all of the file's meshes, and must have the same default weight in `weights`; an unnamed target is a shape of its own, found with `TryGetAt`. POSITION, NORMAL and TANGENT targets are read, including sparse accessors. In an FBX file, each blend shape channel is a shape named after its target shape (`smile` in a channel `Blends.smile`), with the channel's default percentage as its weight. Export each channel as one target at full weight: a channel with in-between shapes is refused. The importer's own flat normals, made for a part exported without normals, don't follow shapes. ## Checked names and dynamic lookup A known asset provides animation and bone members from its source names: `Idle` becomes `idle`, `Root|Run` becomes `rootRun`, and `Right Hand` becomes `rightHand`. Separators become word boundaries; ASCII letters, digits and underscores are kept. Leading digits, keywords and catalog operation names get an underscore prefix: `123 start` becomes `_123Start`, and `count` becomes `_count`. Colliding aliases receive source ordinals, such as `jump_1` and `jump_2`; extra underscores avoid authored names. A punctuation-only name becomes `_`. Unnamed entries and bones with duplicate original names use dynamic enumeration. The editor reads the file's catalog without importing geometry or animation samples, and refreshes the names when the file changes. Invalid files and unavailable metadata have separate diagnostics; a requested clip is only reported missing after its catalog was inspected successfully. For an asset URL, the editor uses an existing local cache; a build fetches uncached content. ```csharp var model = hero; // Retains the known asset's checked catalog. var idle = model.animations.idle; var hand = model.skeleton.bones.rightHand; if (model.animations.TryGetByName("Victory Dance", out var celebration)) { var pose = celebration.Sample(0); Draw.SkinnedMesh(model, float4x4.identity, pose); } ``` `TryGetByName(name, out result)` uses the exact original name and returns a bool. Missing, empty or duplicate names return `false` and assign `default` to the result. Both `animations` and `skeleton.bones` provide `count` and `TryGetAt(index, out result)` for enumeration; an index outside the catalog also returns `false` and assigns `default`. Unnamed entries remain accessible by index. `skeleton.TryGetByName(name, out result)` also finds a bone. Contract aliases must be nonempty. An animation has its original `name` and its `duration` in seconds. A plain `SkinnedMesh` helper parameter has dynamic lookup. Declare an optional contract when a helper needs checked names: ```csharp struct Locomotion { Animation idle; Animation run; [Name("Right Hand")] Bone hand; } asset SkinnedMesh character = "art/character.glb"; Animation Running(SkinnedMesh model) { return model.animations.run; } ``` The contract requires that subset; extra clips and bones remain discoverable through `TryGetByName` and `TryGetAt`. Unaliased fields match normalized source identifiers; `[Name]` matches exact source spelling. Contracts stay available through helper parameters and collection elements. A build checks an imported asset's requirements; runtime decoding checks them before returning a model. ## Animation files For offline text-to-motion generation and learned clip transitions, see [Tide Motion](#doc-tools--motion). Its standalone native CLI exports SOMA-30 GLB animations and supports batches that reuse loaded models. Its bone-mapping retarget command exports clips for other humanoid rigs before the game imports them. A separate glTF or FBX file can supply animation clips without importing typed render geometry. For the character above: ```csharp asset AnimationCatalog movement = "art/movement.glb"; view MovingCharacter(Character character) { mut var pose = hero.defaultPose; pose.Sample(movement.run, character.seconds, Playback.Loop); Draw.SkinnedMesh(hero, float4x4.identity, pose); } ``` An `AnimationCatalog` asset holds every clip in the file and the skeleton those clips animate. A single known asset exposes its clips directly, such as `movement.run`. The editor completes these members and shows their original source names on hover, using the same rules as `hero.animations`. `movement.count`, `movement.TryGetByName("Run", out result)` and `movement.TryGetAt(index, out result)` enumerate or find clips too. Copying with `var` retains checked names; a plain `AnimationCatalog` helper parameter exposes lookup and enumeration. The file can be `.glb`, `.gltf` or `.fbx`. The importer keeps animation and skeleton data, so an animation file need not contain a mesh. A file containing several clips imports them all. Combine several files with a list, or use a glob: ```csharp asset AnimationCatalog movement = [ "kenney/survivors/walk.fbx", "kenney/survivors/run.fbx" ]; // Alternatively: asset AnimationCatalog movement = "kenney/survivors/*.fbx"; var walk = movement.rootWalk; // Original name: Root|Walk var run = movement.rootRun; // Original name: Root|Run ``` This makes one combined catalog. List entries can be constant strings or globs; list order is preserved, each glob is sorted by path, and repeated files are imported once. Clips keep their order within each source. If both files contain `Root|0.Targeting Pose`, their members become `movement.walkRoot0TargetingPose` and `movement.runRoot0TargetingPose`. Remaining collisions receive source ordinals. Hover shows the original clip name and its file. `TryGetByName` searches original names across the whole catalog and returns false for an ambiguous name, assigning `default` to its result. Each clip retains its own source skeleton; collecting clips does not retarget them. Import a single clip directly when the file contains exactly one. Select a particular clip from a multi-clip file with its exact original name: ```csharp asset Animation idle = "art/idle.fbx"; // Requires exactly one clip. [Name("Root|Run")] asset Animation run = "kenney/survivors/run.fbx"; var pose = run.Sample(seconds, Playback.Loop); ``` Missing or ambiguous selections are build errors. An `Animation` asset takes one file, while an `AnimationCatalog` asset accepts a file, a glob or a nonempty file list. `pose.Sample` binds the clip to the pose's skeleton. Use a pose from the character when you also need its bone references for edits or sockets. You can also sample the source clip with `movement.run.Sample(seconds)` and pass that pose directly to `Draw.SkinnedMesh`; the draw binds it to the character. Binding matches nodes by unique exact source names and matching parent chains; source node order and default poses can differ. This supports animation-only FBX exports whose defaults are the starting pose of a take. Required source local transforms are copied directly, including the defaults of unanimated ancestors. Sampling into a target pose binds the selected clip's animated nodes and their ancestors. Drawing a source pose binds all animated nodes declared by its source asset, any edited nodes and their ancestors, because a pose does not retain which clip was sampled. Unrelated target nodes keep their own rest transforms. A clip may animate nodes the model lacks: those are skipped, as in Unity. So one body clip drives every part of a modular character, a hair part with only the root-to-head chain as well as a torso, and a clip's IK helpers (`ik_settings`, `ik_foot_root`) need no node in any part; a part's extra chains (a cape's bones) keep their rest. A node the model has must still have the same parent: a model's `head` below `neck_01` binds a clip's `head` only where the clip's `head` is below its `neck_01` too, so a clip node below one the model lacks is refused rather than moved relative to another parent. A clip none of whose animated nodes are in the model is another rig and is refused too. An extra unnamed identity scene root, as added by FBX importing, is ignored while its pose and relevant animation channels stay at rest. Animated wrappers or deeper unnamed ancestors cannot be bound this way. A named node at the top of either hierarchy is folded into the bones below it when the other side has no node with its name. Blender writes the armature object as such a node above the skeleton's top bone, carrying the object's transform: a rig in centimetres gets a scale of 0.01. That transform, animated or not, is combined with its children's. A clip edited in Blender and exported again therefore drives a character exported elsewhere with its bones where they were authored, and a character exported from Blender plays clips exported elsewhere. The folded node's scale must be uniform, and it must be above a bone that binds. When a clip doesn't bind, the first failed sample or draw for each model and clip prints the reason on the console and names the node that differs, such as `"Hips" is below "Armature" in it but below "Root" in the model`. This supports separate files exported from the same named hierarchy. It does not retarget animation: source translations, rotations and scales are used as authored, without adapting proportions or correcting coordinate spaces. Ambiguous required names and different parent chains reject binding. An incompatible sample leaves the destination unchanged, and an incompatible draw produces no draw. Bone identity and pose blending still require identical skeleton data. ## Retarget between humanoids For imported clips, bake retargeting during the build. The result is an ordinary `Animation` on the target skeleton, so playback only samples the baked clip: ```tide asset HumanoidRig motionRig = "rigs/motion.humanoid.json"; asset HumanoidRig heroRig = "rigs/hero.humanoid.json"; [Retarget(motionRig, heroRig)] asset AnimationCatalog movement = "motion/*.fbx"; [Name("Root|Run"), Retarget(motionRig, heroRig, sampleRate: 60)] asset Animation run = "motion/run.fbx"; ``` A `.humanoid.json` profile chooses an explicit anatomical reference, then overrides automatic assignments where needed: ```json { "reference": { "file": "../art/hero.glb", "pose": "rest" }, "bones": { "LeftHand": "hand_l", "LeftToes": null }, "referenceEdits": { "upperarm_l": { "rotationOffsetDegrees": [0, 0, 5] } } } ``` Reference paths are relative to the profile. For a model imported with [`[Parts]`](#doc-game--animation--parts-of-a-file), write the same patterns in the reference, `"reference": { "file": "../art/pack.fbx", "pose": "rest", "parts": ["Body_LOD0", "Helmet*"] }`, so the rig is the skeleton the model has. To use a calibration clip instead of rest transforms, write `"reference": { "file": "reference.fbx", "clip": "T-Pose", "seconds": 0 }`. The clip name is exact and unambiguous, and seconds must lie within its duration. The calibration file may be separate from the animation export; its default pose is never guessed from the first frame. `bones` uses `HumanoidBone` names and exact source bone names. Omitted roles keep their automatic assignment; `null` explicitly unmaps a role. `referenceEdits` names exact bones and accepts `positionOffset` in local metres, `rotationOffsetDegrees` as local X/Y/Z Euler angles (applied Z, X, then Y, as `quaternion.Euler`), and a positive uniform `scaleMultiplier`. Edits apply before discovery; explicit mappings apply last. Rotation offsets postmultiply the existing local rotation. These edits calibrate anatomy; use ordinary pose edits after sampling for persistent artistic offsets. `Retarget` accepts named `rootScale`, `rootOffset`, `headingDegrees`, `spineDistribution` and `twistDistribution` with the same meaning as the runtime map below. Omitted root scale uses the leg-length ratio. Other defaults are zero offset/heading and unit distributions. `sampleRate` defaults to 60 samples per second. The baker also preserves source key times, endpoints and STEP boundaries; between samples the target clip's interpolation approximates live retargeting. Raise the rate when fast motion needs more precision. Builds cache derived clips by source content, both profiles and bake options. Changing a profile, reference model or external buffer rebuilds dependent clips. Invalid required mappings fail the build. The source imports remain unchanged, and clips retain their original names and duration. A profile asset is also an ordinary `HumanoidRig` value: inspect its statuses or copy it and edit its mapping before creating a runtime map. Each profile is a separate asset declaration. For dynamically loaded motion, prepare a map and bake once when loading it: ```csharp Animation BakeLoaded(RetargetMap mapping, Animation source, Skeleton target) fails IOError { return try mapping.Bake(source, target); } AnimationCatalog BakeLoadedCatalog(RetargetMap mapping, AnimationCatalog source, Skeleton target) fails IOError { return try mapping.Bake(source, target, sampleRate: 60); } ``` The target is the skeleton used to prepare the map, such as `hero.skeleton`. Keep the returned animation or catalog in a field and use ordinary `Sample` during playback. The baked data remains valid after the source, target and map are discarded, and later map edits do not change it. Catalog baking keeps source order, names and durations and returns a plain catalog with dynamic lookup. All its source skeletons must match the map's actual source skeleton. `Bake` defaults to 60 samples per second and uses the same sampling rules as build-time baking. Invalid inputs, incompatible skeletons, empty catalogs or excessive bake work return `IOError.InvalidData` with a diagnostic explaining the reason; a catalog failure returns no partial result. Use live pose retargeting below when the mapping or corrections need to change during playback. Runtime retargeting adapts a source humanoid's motion to a character's proportions and bone axes. It is part of Tide and does not require Tide Motion. Prepare a `RetargetMap` once, then use it for every sampled pose from that animation export. Start with a reference pose for each rig. Use an authored T-pose or A-pose that describes the character's anatomy; an animation file's defaults can be its first frame instead. Keep that calibration separate from the actual clip's skeleton: ```csharp asset SkinnedMesh sourceCharacter = "art/source-reference.glb"; asset SkinnedMesh hero = "art/hero.glb"; asset Animation run = "art/run.fbx"; RetargetMap PrepareRun() fails RetargetError { mut var sourceRig = HumanoidRig.Auto(sourceCharacter.defaultPose); mut var targetRig = HumanoidRig.Auto(hero.defaultPose); // Correct an uncertain or missing assignment with a typed bone. targetRig[HumanoidBone.LeftHand] = hero.skeleton.bones.leftHand; // Optional calibration edits belong to the reusable reference pose. var shoulder = hero.skeleton.bones.leftShoulder; targetRig.referencePose[shoulder].rotation = quaternion.identity; return try RetargetMap.Create(run.skeleton, sourceRig, targetRig); } void Animate(mut Pose destination, RetargetMap mapping, float seconds) { var source = run.Sample(seconds, Playback.Loop); if (!destination.Retarget(source, mapping)) return; // Artistic offsets are ordinary edits after retargeting. var hand = hero.skeleton.bones.leftHand; destination[hand].rotation = Math.Mul(destination[hand].rotation, quaternion.Euler(0, 0, 5deg)); } ``` Initialize `destination` from `hero.defaultPose`, and keep the successful `PrepareRun()` result in a field. Handle preparation failures with Tide's normal `fails` handling. `animation.skeleton` and `pose.skeleton` expose each value's original skeleton, with `RestPose`, `TryGetByName` and `bones` enumeration. `HumanoidRig.Auto(referencePose)` discovers roles using names, hierarchy and reference geometry. Inspect `rig.GetStatus(HumanoidBone.LeftHand)`: the result is `HumanoidBoneStatus.Automatic`, `Uncertain`, `Missing` or `Manual`. Automatic discovery can be partial. Check the assignments and improve the reference pose when a rig needs help; it does not silently rerun after an edit. `rig[role]` returns a `Bone`, or `default` when unset. Assigning a bone from that rig sets `Manual`; assigning `default` explicitly unmaps the role. A bone from another skeleton is ignored. For fully manual mapping, initialize `HumanoidRig { referencePose = yourReference }` and assign its roles. Role names follow Unity's `HumanBodyBones`: `Hips`, `Spine`, `Chest`, `UpperChest`, `Neck`, `Head`, left/right upper and lower arms and legs, hands, feet, shoulders and toes, eyes, jaw, and each finger's proximal, intermediate and distal bones. Hips, head, upper/lower limbs, hands and feet are required; other roles are optional. `RetargetMap.Create(actualSourceSkeleton, sourceRig, targetRig)` validates and freezes the mapping and reference poses. It supports source exports whose node order, scene wrappers and default transforms differ from the calibration file. Rebuild the map after changing assignments or reference transforms. Replacing a rig's reference pose with another skeleton requires a new rig. Preparation returns `RetargetError.InvalidRig`, `MissingBone`, `AmbiguousBone`, `InvalidReferencePose`, `IncompatibleSkeleton` or `UnsupportedScale` on failure. The console gives the failing role or skeleton detail. Required uncertain roles need a manual assignment. References must have finite transforms and positive scale. A node of non-uniform scale (an exporter's geometry helper, or an IK bone a little off uniform) is fine where no role is at or below it and the transfer needs nothing under it; a required role there gives `UnsupportedScale`, and an optional one is left out. Malformed hierarchies and ambiguous correspondence are rejected. These mutable settings remain available on a prepared map: | Field | Meaning | |---|---| | `rootScale` | Root travel multiplier, initially the target/source leg-length ratio; zero removes travel | | `rootOffset` | Model-space translation in metres, initially zero | | `headingDegrees` | Rotation about the target reference hips and up axis, initially zero | | `spineDistribution` | Extra spine and neck chain interpolation, from zero to one; initially one | | `twistDistribution` | Longitudinal twist transferred to helper bones, from zero to one; initially one | `destination.Retarget(source, mapping)` returns `true` on success. It preserves the target's bone lengths and skeleton identity, so its normal bone edits, sockets, blending and drawing work afterward. Invalid settings, unsupported source scale animation or a source/destination from the wrong skeleton return `false` and leave the destination unchanged. Calibration profiles and prepared maps are ordinary owned values and can be stored in match or local fields, copied and snapshotted with poses. Retargeting transfers motion without foot planting or contact correction. It transfers rotations and hips translation; other animated local translations are not copied, preserving the target's segment lengths. A palm or leaf bone with too little geometry to determine its roll may need calibration or a post-transfer rotation edit. Different body proportions can still produce foot sliding or a hand missing a prop; those need game-specific pose correction or IK. Existing `pose.Sample` binding remains useful for separate exports of the same rig. ## Sample, blend and edit Time is explicit. `Sample(seconds)` clamps to the clip's endpoints. `Playback.Loop` wraps positive and negative time; an exact loop endpoint becomes time zero. Every sample begins from the authored rest transforms, so unanimated properties never retain a previous clip's values. ```csharp mut var pose = hero.animations.idle.Sample(idleSeconds, Playback.Loop); var running = hero.animations.run.Sample(runSeconds, Playback.Loop); pose.Blend(running, moving); // Weight from 0 to 1. var head = hero.skeleton.bones.head; pose[head].rotation = Math.Mul(pose[head].rotation, lookRotation); ``` `pose[bone]` is a `BoneTransform` with parent-local `position`, quaternion `rotation` and `scale`. `pose.Sample(animation, seconds[, playback])` resamples in place and reuses its transform storage. Sampling and blending run deterministically on the CPU in match systems as well as views. A pose can be stored in an ordinary match field or a local field, with the same copy and snapshot rules as other structs containing lists. `Pose.Blend` requires identical skeleton data and does not bind across separate exports. To blend clips from separate files, start both poses from `hero.defaultPose` and sample each clip into its target pose before blending. A stored pose takes the latest tick's transforms in a view. For smoother playback, sample a view pose from the presentation time your game chooses, or blend two sampled poses explicitly. Keep an unwrapped clock when interpolating time across a loop boundary. ## Sockets and match use `pose.Model(bone)` accumulates the hierarchy into a model-space matrix. Multiply it by the character's world transform to place an attachment: ```csharp var hand = hero.skeleton.bones.rightHand; var weaponTransform = Math.Mul(characterTransform, pose.Model(hand)); Draw.Mesh(sword, weaponTransform); ``` For many bones at once, `pose.Models()` gives every bone's model matrix in one pass from the root, a `List` indexed by `bone.index`, each exactly what `Model` gives: cheaper than a `Model` call for each bone, which walks that bone's ancestors every time. Systems can use the same matrices for sockets or hitboxes. Sampling leaves entity movement to your own systems; it does not extract root-motion deltas or send animation events. Bone references carry their skeleton identity, so use the character's pose when accessing its bones. An incompatible blend leaves the destination unchanged. A `Bone` says which bone it is: `bone.index` is its place in the skeleton (`skeleton.bones.TryGetAt(bone.index, out var same)` gives it back), `skeleton.NameOf(bone)` its source name (empty for a default `Bone` or one of another skeleton), and `a == b` whether two are the same bone of the same skeleton. In text a bone shows its index, and an animation its name: ```csharp var head = rig[HumanoidBone.Head]; Debug.Log($"head is {hero.skeleton.NameOf(head)} ({head})"); // head is head (Bone { index = 93 }) ``` Imported model and animation content participates in the game's match compatibility, including assets read by its vertex defaults. Those dependencies include reads through constants, implicit struct defaults, operators and helper functions, and through another mesh's defaults. Changing their content requires the corresponding game build; a mismatched pack is refused before it replaces the running pack. Unrelated images and other visual assets can still reload without changing model compatibility. ## Crowds: baked poses A character drawn with its own `Pose` costs a sample and a palette on the CPU every frame. A crowd seen from afar doesn't need that: every pose it can show (each clip's frames, idles, the poses your own code makes) is worked out once, kept on the GPU, and each instance only says which of them it shows. Thousands of characters are then one instanced draw, with nothing sampled or uploaded per frame. **A field of 4,096 animated stalks** ([Run example](https://tide-engine.dev/examples/crowd/?stats)) ```tide settings { title = "Crowd"; } local scene Main { } // One model, read twice: as a skinned model for its skeleton and clips, and as // a mesh with its bones in each corner, which the GPU skins. asset SkinnedMesh stalkModel = "assets/crowd/stalk.glb"; asset Mesh stalk = "assets/crowd/stalk.glb"; const int ACROSS = 64; // 64 by 64: 4,096 stalks const float SPACING = 1.1; const float HEAVIEST_FROM = 30; // Metres beyond which each corner follows its heaviest bone alone struct Plant { float3 at; float phase; Color tint; float bowedAt = -100; BakedFader fader; } // A bud on a stalk's tip: where, and the stalk's frame, for its vert struct Bud { float4x4 transform; BakedFrame frame; } local singleton Field { bool made; BakedPoses poses; BakedClip sway; BakedClip bow; List plants; List stalks; List buds; List bud; List budFaces; float time; float turn; } frag Lit(BakedVertex vertex, out Color color, BakedInstance item, Instance instance) { float3 normal = instance.Normal(vertex.normal); float light = 0.35 + 0.65 * Math.Max(Math.Dot(normal, Math.Normalize(float3(0.4, 1, 0.3))), 0); float tip = Math.Saturate(vertex.position.y / 3); color = Math.Lerp(item.tint * 0.55, item.tint, tip) * light; color.a = 1; } // The bud follows the tip's socket, as the rows carry it vert OnTip(mut Vertex3 corner, Bud item, BakedPoses poses) { corner.position = Math.Mul(poses.Socket(item.frame, 0), float4(corner.position, 1)).xyz; } frag BudColor(Vertex3 corner, out Color color) { color = Color(1, 0.85, 0.35); } void Make(mut Field field) { field.made = true; // Every frame of both clips, 30 a second, posed once: 60 rows and 46 more field.poses = BakedPoses.Of(stalkModel.defaultPose); field.sway = field.poses.AddClip(stalkModel.animations.sway, 30, Playback.Loop); field.bow = field.poses.AddClip(stalkModel.animations.bow, 30); field.poses.AddSocket(stalkModel.skeleton.bones.bone5, float4x4.Translate(float3(0, 0.5, 0))); for (int z = 0; z < ACROSS; z++) { for (int x = 0; x < ACROSS; x++) { int seed = Math.Hash(int2(x, z)); float jitter = (seed & 255) / 255.0; field.plants.Add(Plant { at = float3((x - ACROSS / 2) * SPACING + jitter * 0.4, 0, (z - ACROSS / 2) * SPACING - jitter * 0.3), phase = ((seed >> 8) & 1023) / 512.0, tint = Color(0.25 + 0.2 * jitter, 0.55 + 0.25 * ((seed >> 20) & 255) / 255.0, 0.3) }); } } float s = 0.09; field.bud = [Vertex3 { position = float3(0, s, 0) }, Vertex3 { position = float3(s, 0, 0) }, Vertex3 { position = float3(0, 0, s) }, Vertex3 { position = float3(-s, 0, 0) }, Vertex3 { position = float3(0, 0, -s) }, Vertex3 { position = float3(0, -s, 0) }]; field.budFaces = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1, 5, 2, 1, 5, 3, 2, 5, 4, 3, 5, 1, 4]; } view Show(mut Field field) { if (!field.made) Make(field); float dt = Math.Min(Frame.dt, 0.1); field.time += dt; field.turn += dt * 0.08; var eye = float3(Math.Sin(field.turn) * 42, 20, Math.Cos(field.turn) * 42); Draw.Clear(Color(0.55, 0.7, 0.85)); Draw.SetCamera(eye, quaternion.LookRotation(Math.Normalize(float3(0, -2, 0) - eye), float3(0, 1, 0)), 50); Draw.Plane(float3(0, 0, 0), float2(ACROSS * SPACING + 4), Color(0.32, 0.27, 0.2)); // Each stalk sways; now and then one bows, and the fader eases it from // one clip to the other and back, where it would snap field.stalks.Clear(); field.buds.Clear(); int second = int(field.time); for (int i = 0; i < field.plants.count; i++) { mut var plant = field.plants[i]; if (field.time - plant.bowedAt > 3 && (Math.Hash(int2(i, second)) & 63) == 0) plant.bowedAt = field.time; float since = field.time - plant.bowedAt; mut var frame = since < field.bow.duration ? plant.fader.Play(field.bow, since, dt) : plant.fader.Play(field.sway, field.time + plant.phase, dt); var to = plant.at - eye; frame = frame.HeaviestBone(Math.Dot(to, to) > HEAVIEST_FROM * HEAVIEST_FROM); field.plants[i] = plant; var place = float4x4.Translate(plant.at); field.stalks.Add(BakedInstance { transform = place, frame = frame, tint = plant.tint }); field.buds.Add(Bud { transform = place, frame = frame }); } // All of them in two draws: the stalks, and the buds on their tips Draw.Instanced(stalk, field.stalks, BakedSkin, Lit, field.poses); Draw.Instanced(field.bud, field.budFaces, field.buds, OnTip, BudColor, field.poses); } ``` Read the model twice: as a `SkinnedMesh` for its skeleton and clips, and as a [mesh with bones](#doc-game--assets--meshes), whose vertices carry `joints` and `weights`, for the GPU to skin. `BakedVertex` is such a vertex struct (`position`, `normal`, `uv`, `joints`, `weights`); `[LOD]` on the mesh gives each instance its level as usual. ```csharp asset SkinnedMesh knightModel = "art/knight.fbx"; [LOD] asset Mesh knight = "art/knight.fbx"; local singleton Crowd { BakedPoses poses; BakedClip walk; BakedClip strike; List items; } void Bake(mut Crowd crowd) { crowd.poses = BakedPoses.Of(knightModel.defaultPose); crowd.walk = crowd.poses.AddClip(knightModel.animations.walk, 30, Playback.Loop); crowd.strike = crowd.poses.AddClip(knightModel.animations.strike, 15); } view DrawCrowd(mut Crowd crowd, Fighter fighter) { crowd.items.Add(BakedInstance { transform = fighter.transform, frame = crowd.walk.At(fighter.walked) }); } [After(DrawCrowd)] view DrawAll(mut Crowd crowd) { Draw.Instanced(knight, crowd.items, BakedSkin, KnightLit, crowd.poses); crowd.items.Clear(); } ``` ### Rows A `BakedPoses` is a table of rows: each row is one pose of the skeleton, kept as each bone's skinning. Make it with `BakedPoses.Of(model.defaultPose)`, then fill it once: - `poses.AddClip(clip, rate[, playback])` adds a clip's rows, `rate` a second in whole steps over its duration, and returns a `BakedClip` (`first`, `count`, `duration`, `loops`). A clip of another file plays on the model as `pose.Sample` binds it; a retargeted clip is an ordinary clip. `Playback.Loop` leaves out the row at the clip's end, which is its start. - `poses.Add(pose)` adds any pose of the model's skeleton and returns its row's number: a clip blended, layered or edited with your own IK, sampled where you like. It returns -1 for a pose of another skeleton, or once the table is full. - `poses.AddSocket(bone[, offset])` returns a socket's number: a place on a bone, such as a sword's grip in a hand, which every row then carries (below). Rows are made at load, wherever your code first fills the table: each is one `pose.Models()` and a multiply a bone, so 3,000 rows of a 64-bone character take about 19 ms. Hand the table to each draw after its frag: the GPU keeps it as long as it doesn't change, so filling it again every frame would send it every frame. ### Frames A `BakedFrame` says what an instance shows: a row, the row it's going on to and how far, and another such pair it fades from. Make one with `clip.At(seconds)` (between the two rows round that time, held at the clip's ends or wrapped where it loops), `BakedFrame.Row(row)` or `BakedFrame.Between(row, next, t)`. `frame.FadedFrom(from, shown)` shows `frame` that much (0 to 1) over `from`; `frame.HeaviestBone(true)` has each corner follow its heaviest bone alone, cheaper for instances far enough away that joints blending can't be seen. A jump between clips snaps unless it fades. Keep a `BakedFader` for each instance, in a local field, and let it fade for you: ```csharp component Fighter { local BakedFader fader; } var frame = attacking ? fighter.fader.Play(crowd.strike, sinceStrike, Frame.dt) : fighter.fader.Play(crowd.walk, walked, Frame.dt); ``` `Play` knows a clip by its first row. For rows of your own, `fader.Show(frame, kind, dt)` takes your number for what the frame is: a change of it is a jump. A jump fades from what was shown over `fadeSeconds` (0.2 by default), eased; a second jump while the first is less than half done fades from what the first was fading from. After an instance was out of sight, `fader.Cut()` makes its next frame snap. ### Your own vert, and props `BakedSkin` draws `BakedVertex` meshes for `BakedInstance` items. With a vertex or an item of your own, write the vert, which calls the same skinning: ```csharp struct Soldier { float4x4 transform; BakedFrame frame; float team; } vert Skinned(mut SoldierCorner corner, Soldier item, BakedPoses poses) { var skin = poses.SkinRows(item.frame, corner.joints, corner.weights); corner.position = skin.Point(corner.position); corner.normal = Math.Normalize(skin.Direction(corner.normal)); } ``` `SkinRows` gives the corner's skinning as the top three rows of its matrix (a `BakedBone`), whose `Point` and `Direction` move a position and a direction; `poses.Skin` gives the same as a `float4x4`. Each reads every one of the corner's four bones, as a branch on a weight costs the GPU more than the reads it would save. `poses.Socket(frame, socket)` is where a socket is in the model in that frame. A prop drawn instanced over the same items follows its bearer's hand with it: ```csharp vert InHand(mut Corner corner, Soldier item, BakedPoses poses) { corner.position = Math.Mul(poses.Socket(item.frame, SWORD), float4(corner.position, 1)).xyz; } ``` `SkinRows`, `Skin`, `BoneSkin` and `Socket` are ordinary methods, the same on the CPU: a system can ask where a far soldier's sword is from the rows it's drawn with. The poses go to helpers whole (`float4x4 Grip(BakedPoses poses, BakedFrame frame)`), as any struct that holds lists can in code the GPU runs: see [Passing on what holds a list](#doc-game--shaders--passing-on-what-holds-a-list). ### Shadows and culling Draw the same items into a shadow map's target with the same vert and no frag: `shadow.Instanced(knight, crowd.items, BakedSkin, crowd.poses)`. Skinned in a vert, instances have no bounds the engine can cull by: give the draw [`Draw.Bounds`](#doc-game--draw-settings) that hold a character in any pose, or cull them yourself before adding them. ### What it costs - **Memory:** 48 bytes a bone a row. A 65-bone character with 3,000 rows is 9.4 MB. One table holds 699,050 bones' rows (a list on the GPU is at most 1024 by 2048 pixels, three a bone): about 10,700 rows of 65 bones. Use a table for each model, or fewer rows, past that. - **Rate:** between rows the matrices blend linearly. That's smooth for most motion at 15 to 30 rows a second; a joint turning fast between two rows comes out short of its length halfway (a quarter turn between two rows shortens a limb by about 30% halfway; an eighth by 8%). More rows a second is the remedy, at their memory. A fade between two clips blends the same way. - **Bind pose:** a mesh with bones is the model at rest, so rows are right where the rest pose is the pose the model was bound in, as exported models usually are. - **GPU:** each corner reads two rows of each of its four bones, four in a fade, one bone's with `HeaviestBone`. 10,000 characters of 3,072 vertices and 64 bones took 4.4 to 4.7 ms of an RTX 4080 SUPER, where the same mesh drawn unskinned took 4.3 and each character sampled on the CPU took 10.5 ms of the CPU and 7.8 of the GPU, with 41 MB sent each frame; recording them took 0.38 ms. ## Load while playing `SkinnedMesh.Decode(bytes)` and its contracted form decode a self-contained GLB, returning a model `fails IOError`. Invalid data, external-resource references or missing contract requirements give `IOError.InvalidData`. Models and animation values can be stored after decoding. Bytes can come from anywhere, so a small file can't ask for much. A model past any of these is `InvalidData` before anything is made for it: | Limit | Most | |---|---| | Vertices (a part without normals has three a triangle) | 1,048,576 | | Triangle corners (three a triangle) | 6,291,456 | | Skeleton nodes, animations, buffers | 65,536 each | | Skins | 4,096 | | Inverse binds (skin joints, and one for each part no skin moves) | 262,144 | | Vertex influences (joint/weight sets count four a vertex each) | 8,388,608 | | Animation channels | 262,144 | | Animation key numbers (times and values) | 16,777,216 | | Blend shapes (morph targets of different names) | 4,096 | | Vertices moved by blend shapes, each shape's counted | 2,097,152 | | Numbers read from accessors, counted again for each part that names one | 67,108,864 | | JSON values in the description | 4,194,304 | | The file, and the decoded model | 512 MiB each | An accessor with no buffer view is zeros and takes no bytes, but counts as much as one with them. A model at every limit at once takes about 600 MiB to decode. These limits are the engine's, the same for every game, so every machine in a match refuses the same files; `SkinnedMesh` and `Animations` assets are held to them too. The numbers are provisional. A model refused for a limit says so on the log of each machine that decoded it, naming the limit, as `tide: SkinnedMesh.Decode refused a model: it has 2,000,000 vertices, more than the 1,048,576 a decoded model holds (TIDE_SKINNED_MAX_VERTICES)`. A build-time asset past one is an error that says the same. Get bytes with [files or Web.Fetch](#doc-game--files), separately from decoding. Files fetched on one machine are local; content that affects match bones must enter through synchronized [commands](#doc-game--commands) or other match data. Decoding itself is deterministic and can run in match code. Decoded vertices use your vertex struct's defaults too. Assets those defaults read have the same compatibility requirement even when the game declares no imported skinned model. glTF assets support multiple skins, all supplied consecutive joint/weight sets, animated non-joint parents, and STEP, LINEAR and CUBICSPLINE channels. FBX imports polygon meshes, linear skin weights, blend shapes and baked node transforms; textures remain separate assets. Animated or GPU blend shapes, IK, animation events and an automatic playback controller are not implemented. --- Source: https://tide-engine.dev/game/cameras.md Cameras in Tide views: screen and world coordinates and rays for picking, locking the cursor to look around, a projection of your own, and reading a camera back as matrices. # Cameras and coordinates A view sets its cameras with `Draw.SetCamera`: `(center, size)` is the 2D one (see [Draw functions](#doc-game--views--draw-functions)) and `(position, rotation, fieldOfView)` the 3D one (see [Drawing in 3D](#doc-game--3d)). This page is what else a camera is for: taking points between the screen and the world, turning with the mouse, any projection, and the matrices a frag needs of it. ## Screen and world coordinates The conversion helpers use the currently selected camera, including a camera set earlier in the same frame. Their screen coordinates are logical pixels from the top left, with `y` down, as `Draw.Screen` and the GUI's are. `Screen.width` and `Screen.height` are the window's size in those pixels, and `Screen.rect` is `Rect(0, 0, Screen.width, Screen.height)`, the whole screen: a background drawn over it, or a popup kept on it with `rect.MoveInside(Screen.rect)`. Both are floats, so `Screen.width / Screen.height` is the screen's shape with nothing rounded away. Views, and the functions they call, read them. `Screen.scale` is a read-only `float2`: physical pixels per logical pixel on x and y. It reflects the current window, independently of the selected render target. A custom host that supplies no scale reports `(1, 1)`; this metadata does not report whether a target lost its contents. | Function | Result | |---|---| | `Draw.WorldToScreen(float2 point)` | The point's screen position | | `Draw.ScreenToWorld(float2 point)` | Its position under the current 2D camera | | `Draw.WorldToScreen(float3 point)` | Screen `x` and `y`, and normalized depth in `z` | | `Draw.ScreenToWorld(float3 point)` | The world position at screen `x`, `y` and normalized depth `z` | | `Draw.ScreenRayOrigin(float2 point)` | The world position on the camera's near plane | | `Draw.ScreenRayDirection(float2 point)` | A normalized world direction through that pixel | In 3D, depth is the depth buffer's value: 0 at the near plane and 1 at the far limit, rather than a distance in world units. The standard perspective camera has an infinite far limit, so depth 1 has no finite world position. The ray helpers work with perspective and orthographic cameras, including custom projection matrices. Intersect the ray with your game's objects or a plane to pick a world position; a pixel alone has no unique 3D position. The devices count pixels the other way: from the bottom left, with `y` up, as Unity's Input System does. `Screen.Flip(position)` gives the same point counted from the screen's other edge, so it turns a device's position into a screen position, for these helpers, `Draw.Screen()` and a `Rect` of the GUI's. It's its own inverse: it turns a screen position into a device's too. ```csharp view Pointer(Devices devices) { var screen = Screen.Flip(devices.pointer.position); var world = Draw.ScreenToWorld(screen); Draw.WireCircle(world, 0.2, Color.yellow); var origin = Draw.ScreenRayOrigin(screen); var direction = Draw.ScreenRayDirection(screen); // Hit the world plane y = 0, when the ray points towards it. if (Math.Abs(direction.y) > 0.00001) { float distance = -origin.y / direction.y; if (distance >= 0) Draw.Sphere(origin + direction * distance, 0.1, Color.yellow); } } ``` The cameras these go through are there as matrices too: see [A camera as matrices](#doc-game--cameras--a-camera-as-matrices). On the screen (`Draw.Screen`, `Draw.SetScreen`), its conversion helpers are identity mappings. A viewport with no size, a singular camera matrix, or a point whose projection has no finite position returns zero. ## Looking around A camera that turns with the mouse wants the mouse for itself: the cursor out of sight, and no screen's edge for it to stop at. `Cursor.Lock()` asks for that. Call it every frame the game wants the mouse, as with `GUI.ShowKeyboard()`: the cursor comes back by itself once a frame goes by without it, so there's nothing to unlock. `Cursor.locked` says whether the lock holds. ```csharp input PlayerInput { float2 look; Sample(Devices devices) { if (Cursor.locked) look = devices.mouse.delta * 0.003; } } system Turn(PlayerInput input, mut Viewer viewer) { viewer.yaw += input.look.x; viewer.pitch = Math.Clamp(viewer.pitch - input.look.y, -1.5, 1.5); viewer.rotation = quaternion.Euler(float3(viewer.pitch, viewer.yaw, 0)); } local singleton Menu { bool paused; bool looking; // The window held the cursor last frame } view Look(Devices devices, Viewer viewer, mut Menu menu) { Draw.SetCamera(viewer.position, viewer.rotation, 75); if (devices.keyboard.escape.down) menu.paused = true; if (!menu.paused) Cursor.Lock(); // The lock went away on its own: show the pause menu if (menu.looking && !Cursor.locked) menu.paused = true; menu.looking = Cursor.locked; } view PauseMenu(mut Menu menu) { GUILayout.Modal(Anchor.MiddleCenter, menu.paused) { if (GUILayout.Button("Resume")) menu.paused = false; } } ``` While the cursor is locked: - It's hidden, and `devices.mouse.position` stays where it was, as does the pointer's. - `devices.mouse.delta` keeps coming, however far the mouse goes. Where the system gives it, it's the mouse's own movement, without the acceleration a cursor has, so the camera turns evenly. - The GUI sees no pointer: nothing hovers, and a click presses no widget, so it's all the game's. A finger on a touchscreen still presses what it touches. **Warning: Read `Cursor.locked`, don't assume** Asking isn't having. The system decides whether the window holds the cursor, and it differs: - **In a browser,** the lock is only given at a click or a key press, so it takes hold at the player's next one, or at once when the game asks right after one, like a Resume button's click. The browser lets the cursor go when the player presses Escape, which a page can't prevent and often never sees the key of, and when the page loses the focus. For a moment after Escape it won't lock again, and then it takes another click or key press. - **On desktop,** a window holds the cursor while it has the focus: Alt+Tab lets it go, and the lock returns with the focus if the game still asks. Escape lets it go too, as in a browser, and the game still gets the key: the cursor is the player's until they click on the window or press another key, or until the game stops asking and asks again, which locks at once. - **On Android,** it never locks, for now. So look only while `Cursor.locked`, and show the pause menu when it goes false while the game was looking, as above: that's what Escape does, in a browser and on desktop. A game with no pause menu just keeps asking, and the player's next click or key press locks the cursor again. Only views, and the functions they call, call `Cursor.Lock()`. They read `Cursor.locked`, and so does the input's `Sample`. The match can do neither: the cursor is this machine's, so what the match needs of it goes in the input. While a [modal](#doc-game--gui--modals) is up the lock isn't asked for, whatever views ask, since its widgets need the pointer. ## Any projection `Draw.SetCamera(transform, projection)` sets the 3D camera from matrices: `transform` places it in the world, looking along its `+z`, and `projection` takes what it sees to the screen, the screen's shape included. `float4x4.PerspectiveFov(verticalFov, aspect, near, far)` makes a perspective one, with the field of view in radians, and `float4x4.Ortho(width, height, near, far)` one without perspective, as isometric games have, as Unity.Mathematics' do. `Screen.width / Screen.height` is the screen's shape. ```csharp view Isometric(Viewer viewer) { var place = float4x4.TRS(viewer.position, quaternion.Euler(float3(Math.Radians(30), Math.Radians(45), 0)), float3(1)); float height = 20; Draw.SetCamera(place, float4x4.Ortho(height * Screen.width / Screen.height, height, 0.1, 1000)); } ``` ## A camera as matrices Whatever set the camera, a view reads back its world-space matrices: | Function | Result | |---|---| | `Draw.WorldToClip()` | The 3D camera as one `float4x4`, from the world to clip space | | `Draw.CameraTransform()` | Where the 3D camera is in the world, a `float4x4`: it looks along its `+z` | | `Draw.CameraProjection()` | Its projection, a `float4x4`: from what it sees to clip space | | `Draw.WorldToScreenMatrix()` | The 2D camera as a `float3x3`, from the world to the screen's pixels | - They're the camera as it's set when they're asked, in this frame: ask after `SetCamera`, or inside a `Camera` block. Before any camera is set, they're the camera each frame starts with. - A render target has the same four, for its own cameras: `target.WorldToClip()`. - `WorldToClip()` describes the world-to-clip mapping: the camera's transform undone, z turned around (a camera looks along its `+z`, and clip space along `-z`), then the projection, fitted to the shape of the window or the target. A point through it is in clip space: once divided by its `w`, `x` and `y` go from -1 to 1 across what the camera sees, `y` up, and `z` from -1 at the near plane to 1 at the far limit. It's what a frag needs to find a pixel in another camera's image, as a [shadow map](#doc-game--shaders--a-shadow-map) does with its lamp's. - `CameraTransform()` and `CameraProjection()` are the two `SetCamera(transform, projection)` takes, so `Draw.SetCamera(Draw.CameraTransform(), Draw.CameraProjection())` sets the camera there already was. A camera set with a field of view has them too, its projection with the screen's shape in it. - `WorldToScreenMatrix()` does to `float3(x, y, 1)` what `Draw.WorldToScreen` does to a `float2`. It's the identity inside `Draw.Screen`. - [`Draw.Transform`](#doc-game--draw-settings--transforms) is no part of any of them: they're the camera's alone. ```csharp view Mirror(mut Looking looking) { Draw.SetCamera(looking.eye, looking.turned, 60); looking.toClip = Draw.WorldToClip(); // Kept for a frag, in a local singleton float4 clip = Math.Mul(looking.toClip, float4(looking.target, 1)); looking.onScreen = clip.w > 0 && Math.Abs(clip.x) <= clip.w && Math.Abs(clip.y) <= clip.w; } ``` For built-in cameras and invertible affine camera transforms, automatic 3D placement and a vert's `this.clip` rebase the model around the camera before projecting it. This retains small mesh details when the camera is far from the world origin. `WorldToClip()` and CPU coordinate conversions still use the combined world-space float matrix, so their rounding can differ from GPU placement. Fragment `this.world` and `Instance.transform` stay in world coordinates. Explicit clip outputs and projective camera transforms keep their existing mapping. This does not increase depth-buffer resolution or separate genuinely coincident surfaces. Depth storage separately uses reversed 32-bit floats where supported, reversing only after clip placement. Public camera matrices, `this.clip` and CPU screen/depth conversions keep the conventions above. Forward `this.depth` and sampled-depth reads do not retain the additional far precision; see [depth textures](#doc-game--render-targets--a-target-s-depth). Devices using the forward depth fallback keep their earlier precision. --- Source: https://tide-engine.dev/game/render-targets.md Render targets in Tide: draw into an image, bring it to the window through a frag for post-processing, and pick its format, its samples for smooth edges, several colors and its depth. # Render targets and post-processing `RenderTarget` names a local drawing destination. It has every method `Draw` has, and `Draw`'s own calls draw into `Draw.window`, which is a `RenderTarget` too. Every setting belongs to the destination it's called on, and is shared across views within the frame. Switching destinations preserves color, depth and [stencil](#doc-game--draw-settings--stencil), and a clear resets all three, within that destination's clip. There are three ways to make one: ```csharp render.scene = RenderTarget.Window(); // Always the window's size, at full resolution render.blur = RenderTarget.Window(0.5); // Always half of it, each way render.card = RenderTarget(200, 300); // A size of its own, in logical pixels, at the display's resolution render.small = RenderTarget(320, 180, 1); // A size of its own, in exactly these pixels ``` A target's size is in logical pixels, like the window's, and its image is made at the display's scale. So drawing into a target is the same as drawing into the window: on a display scaled to 150%, a target of 200 by 300 has 300 by 450 pixels, its text is fitted to them, its shapes' edges are one of them wide, and `target.Screen()`, clips, conversions like `WorldToScreen` and a frag's `this.position` are all in logical pixels. A pass over the whole screen that goes through a target comes out as sharp as the window. - `RenderTarget.Window()` is for exactly that: a target that's always the window's size. `RenderTarget.Window(factor)` is always that part of it, for the smaller targets a blur or a glow goes through. The engine makes them again when the window's size changes, so there's nothing to resize and nothing to forget. What was drawn in one is lost then, which doesn't matter for a target a view draws again every frame. `Resize` on one is refused. - `RenderTarget(width, height)` is a target of a size of its own. `Resize(width, height)` changes it for every alias and discards its contents, even at the same size. - A third argument is the target's pixels per unit, where the display's isn't wanted: `RenderTarget(320, 180, 1)` is exactly 320 by 180 pixels on every display, for pixel art and anything else that must not depend on the display. `target.size` is its size in logical pixels: the window's share for one that follows it, and the size it was made or resized to otherwise. `target.valid` says whether drawing into it draws: false for a target never made (a field's default) and for one disposed, true for `Draw.window`. So a view makes one the first frame it needs it: ```csharp if (!ui.card.valid) ui.card = RenderTarget(320, 200); ``` When the display's scale changes (the window moves to another monitor, a browser zooms), the targets at the display's scale are made again, empty. One with pixels per unit of its own is left alone. There's no way to read the display's scale, and nothing here needs it. Otherwise a target's color, depth and stencil persist across frames until cleared. Copies share the image, including copies of `.color`. Call `Dispose()` when finished; every alias becomes invalid, and disposing again is harmless. A default target is invalid. Creation and lifetime methods run in views or local handlers and their helpers; field defaults cannot allocate targets. ## Post-processing For an image baked only when needed, keep its `contentRevision` in local state. This read-only `long` changes when its pixels are discarded by resizing, hot reload or device loss, including automatic window/display changes. Copies of the target share the revision. Ordinary drawing and clearing leave it unchanged. An invalid or disposed target and `Draw.window` return zero. ```csharp if (!cache.card.valid) cache.card = RenderTarget(200, 300); var revision = cache.card.contentRevision; if (cache.bakedRevision != revision) { cache.card.Clear(Color.black); // Draw the cached image here. cache.bakedRevision = revision; } ``` Store `bakedRevision` as a `long` alongside the target. Compare for equality; the revision is an invalidation token, not a count of drawing operations. ```csharp local singleton RenderState { RenderTarget scene; bool made; } enum RenderStages { Prepare, Objects, Effects } frag Present(Vertex vertex, out Color color, Texture source) { color = source.Sample(vertex.uv); } [Stage(RenderStages.Prepare)] view Prepare(mut RenderState render) { if (!render.made) { render.scene = RenderTarget.Window(); render.made = true; } render.scene.Clear(Color.black); render.scene.SetCamera(float2(0), 10); } [Stage(RenderStages.Objects)] view Objects(Body body, RenderState render) { render.scene.Circle(body.position, body.radius, Color.white); } [Stage(RenderStages.Effects)] view Show(RenderState render) { Draw.Blit(render.scene.color, Draw.window, Present); } ``` The view below draws its scene into a target, then blits it to the window through a frag that reads it in blocks. The left of the line is the image as it was drawn. Move the sliders to change the blocks' size and where the line is. **A scene through a frag** ([Run example](https://tide-engine.dev/examples/post/?stats)) ```tide settings { title = "Render targets"; } local scene Main { } local singleton Post { RenderTarget scene; // An image the GPU holds, which views draw into bool made; float blocks = 40; float split = 0.5; float turn; } // Runs for every pixel of the window, with the scene's image as its source. frag Pixelate(Vertex vertex, out Color color, Texture source, Post post) { mut var uv = vertex.uv; if (uv.x > post.split) uv = (Math.Floor(uv * post.blocks) + 0.5) / post.blocks; color = source.Sample(uv, Filter.Point); if (Math.Abs(vertex.uv.x - post.split) < 0.004) color = Color.white; } view DrawScene(mut Post post) { if (!post.made) { post.scene = RenderTarget(512, 512); post.made = true; } post.turn += Math.Min(Frame.dt, 0.05); if (post.turn > Math.TAU) post.turn -= Math.TAU; // A target has the drawing methods Draw has, and settings of its own. post.scene.Clear(Color(0.086, 0.086, 0.094)); post.scene.SetCamera(float2(0), 2); for (var i = 0; i < 7; i++) { var angle = post.turn + i * 0.9; var at = float2(Math.Cos(angle), Math.Sin(angle * 2)) * (0.5 + i * 0.18); post.scene.Circle(at, 0.16 + i * 0.03, Color(0.98 - i * 0.13, 0.75 + i * 0.013, 0.14 + i * 0.1)); } post.scene.Line(float2(-1.8, -1.6), float2(1.8, 1.6), 0.05, Color(0.98, 0.44, 0.52)); // The window gets the scene through the frag. Draw.Blit(post.scene.color, Draw.window, Pixelate); } view Controls(mut Post post) { Draw.SetScreen(); Draw.Text("As drawn", float2(16, 14), 16, Color.white); Draw.Text("Through the frag", float2(Screen.width - 16, 14), 16, Color.white, Anchor.UpperRight); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 86, Screen.width - 24, 74)) { GUILayout.Slider("Blocks", post.blocks, 8, 128); GUILayout.Slider("Split", post.split, 0, 1); } } ``` `Draw.Blit(source, destination, frag)` runs the frag on a fixed `Vertex` quad over the entire destination. It supplies the frag's first read-only `Texture` parameter from `source` (any others from the textures after it, below), replaces color and alpha, and preserves depth. It temporarily ignores camera and clip, then restores them. Its source can also be a `Grid2`, uploaded from CPU cells. Sampling the image being written is an error; use a second target between effects. What one pass needs beyond its source goes after the frag, as a struct the frag takes: `Draw.Blit(lens.bright.color, lens.spread, Blur, BlurStep { along = float2(1, 0) })` and then the same frag the other way, `BlurStep { along = float2(0, 1) }`. Those are [the Blit's values](#doc-game--shaders--values-for-one-draw), and each Blit has its own. A frag that reads more than one image takes a `Texture` parameter for each, and the Blit gives them in that order, before its destination: `Draw.Blit(scene.color, lens.glow.color, Draw.window, Combine)` for `frag Combine(Vertex vertex, out Color color, Texture scene, Texture glow)` (see [Several textures](#doc-game--shaders--several-textures)). A Blit replaces what's in its destination unless it's given a blend: `Draw.Blit(glow, frame, Blend.Add, Copy)` adds a glow onto the picture where it is. An effect that mixes two images some other way ends in a frag that reads both and writes the mix: the scene as the Blit's source, and the other image as the Texture after it, or as a `Texture` field of a singleton the frag takes. The [Duel](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/duel) example does it: its arena goes into a `RenderTarget.Window()`, the arena's bright parts are blurred through targets a quarter and an eighth of the size, and one frag puts the arena and its light in the window. Its score and menus are drawn into the window afterwards, so their text has none of that light on it. A frag can ask how many pixels a texture has, `source.size`, its physical pixels. A step of a blur is usually a logical pixel instead, `1 / Screen.width` across the screen's texture and `1 / Screen.height` down, which the view puts in a singleton for the frag, and the blur is then as wide on every display. Target color is GPU data: `.color` gives a `Texture` reference and does no readback, as `.colors[i]` does for each image of a target that holds several, and so is its depth, a `DepthTexture`. None of them is assigned: what's drawn into the target is what changes them. Neither has a constructor; CPU pixel sources remain `Grid2`, and C can supply a CPU texture reference. `Draw.window` has no sampleable color or depth and cannot be resized or disposed by the game. Texture references, depth references and targets can be stored only in local state. The GUI and stats draw onto the window. Hot reload preserves managed references, their sizes and pixels per unit, whether they follow the window, what they hold, and shared aliases, recreating their images on the web; it discards rendered contents and clears borrowed references supplied by the old build. Device loss also discards rendered contents. Drawing with an invalid or disposed target is skipped with a diagnostic; disposal also invalidates uses already recorded in the frame. ## What a target holds Every target has depth, which its 3D meshes read and write, and a color image beside it. A target says otherwise when it's made, with a `Format` after its size, and keeps what it said from then on: ```csharp lamp.map = RenderTarget(1024, 1024, 1, Format.Depth); // Depth alone, in exactly these pixels lamp.map = RenderTarget(512, 512, Format.Depth); // ...or at the display's resolution lamp.screen = RenderTarget.Window(Format.Depth); // ...or the window's size, or part of it: lamp.half = RenderTarget.Window(0.5, Format.Depth); glow.light = RenderTarget.Window(Format.Rgba16f); // A color image that keeps numbers past 1 ``` | Format | Frag output | Bytes per pixel | What it keeps | |---|---|---|---| | `Format.Rgba8` | `Color` | 4 | Four channels from 0 to 1; the default | | `Format.Rgba16f` | `Color` or `float4` | 8 | Four 16-bit floats, up to about 65,000 | | `Format.R8` | `float` | 1 | One channel from 0 to 1 | | `Format.Rg8` | `float2` | 2 | Two channels from 0 to 1 | | `Format.R16f` | `float` | 2 | One 16-bit float | | `Format.Rg16f` | `float2` | 4 | Two 16-bit floats | | `Format.R32f` | `float` | 4 | One 32-bit float | | `Format.Rgba32f` | `float4` | 16 | Four 32-bit floats | | `Format.R32i` | `int` | 4 | One signed 32-bit integer, exactly | | `Format.Depth` | No color image | — | Depth and stencil alone | A number output replaces what's in its image whatever blend is set, with no tint or alpha multiplication. In a `float4`, all four channels are independent: `float4(2, -1, 0.5, 0.25)` keeps its fourth channel without multiplying the first three by it. A `Color` output retains normal tint, alpha and blend behavior, including in `Rgba16f`. An output that does not fit the image is a compile error at the draw, naming the type to use. Read a numeric image through a declared [typed texture field](#doc-game--shaders--number-images): `[Raw(float2)] Texture velocity;` then `velocity = target.colors[1];` in local code. Its `Sample` returns a `float2`. A typed read that names no filter reads the nearest pixel. Images in `R8`, `Rg8`, `R16f`, `Rg16f` and `Rgba16f` also blend (`Filter.Bilinear`, `Filter.Trilinear`, `Filter.Anisotropic`) and have mipmaps, read with `SampleLevel` and `SampleGrad`: a blurred mask or a variance shadow map works on every device. `R32f` and `Rgba32f` blend with `Filter.Bilinear` as four exact loads blended in the shader, the same bits on every device (only some GPUs blend 32-bit floats themselves), and have no mipmaps; `R32i` reads its nearest pixel, since no GPU blends integers. Asking one of them for what it hasn't got is a compile error that names the format to draw into instead. Every number format makes array layers and cube faces: `TextureArray(256, 256, 4, Format.R16f)`, `Cubemap(256, Format.R32f)`, `TextureArray(64, 64, 8, Format.R32i)`. Draw numbers into `array.layers[i]` or `cube.faces[i]`, and read them through a `[Raw(float)] TextureArray`, `[Raw(int)] Cubemap` or other typed field. A cube of `R32f`, `Rgba32f` or `R32i` is read at its nearest pixel, exactly: a distance cube a lamp's shadow keeps to full precision, or an id per direction. ### A cube of depth alone `Cubemap(1024, Format.Depth)` is six faces of depth alone, for a lamp that shines every way. Draw each face from the lamp's place, as for any cube, and read the depth through `cube.depth`, a `DepthCubemap`, kept in a field of a component or singleton the frag takes. `Sample(direction)` gives the nearest thing's depth that way, 0 near to 1 far, and `Compare(direction, depth)` how much of what's stored around there isn't nearer than `depth`, blended within the face: 1 is lit. ```tide local singleton Lamp { Cubemap cube; DepthCubemap shadows; float3 at; bool made; } view MakeLamp(mut Lamp lamp) { if (!lamp.made) { lamp.cube = Cubemap(1024, Format.Depth); lamp.shadows = lamp.cube.depth; lamp.made = true; } // ...then each face drawn from lamp.at with float4x4.PerspectiveFov(1.5707964, 1, 0.1, 50) } // The depth a face's camera stores for a point `way` from the lamp: along the face's axis, its perspective's float LampDepth(float3 way) { float along = Math.Max(Math.Abs(way.x), Math.Max(Math.Abs(way.y), Math.Abs(way.z))); return 50 / (50 - 0.1) * (1 - 0.1 / along); } frag Lit(Vertex3 vertex, out Color color, Lamp lamp) { float3 way = this.world - lamp.at; float lit = lamp.shadows.Compare(way, LampDepth(way) - 0.0005); color = Color(lit, lit, lit); } ``` Its faces read back with `await cube.faces[i].ReadDepth()`. A cube of colors keeps no depth to read: each face draws with depth of its own, and `cube.depth` of one is a compile error where its format is known. ### Clearing each image Supply one value per image, in format order. Values have the same types as frag outputs; floats can be negative or greater than one, and an integer image takes an `int`: ```csharp render.data = RenderTarget(256, 256, 1, Format.R16f, Format.Rg16f, Format.Rgba32f, Format.R32i); render.data.Clear(2.5, float2(-1, 3), float4(2, 4, 8, 0.25), -17); ``` The clear also resets depth and stencil, within the destination's clip. The existing single-`Color` clear continues to fill every image of a target containing ordinary color formats. Number clears preserve their channels without tint, blending or alpha multiplication; byte formats clamp and quantize them to 0–1. A target of depth alone is drawn into like any other: it has its `Clear`, its cameras and its `Mesh`. A color has nowhere to go there, so the only things that leave anything are the ones that write depth, or [stencil](#doc-game--draw-settings--stencil), which it has too: - **A clear** sets its depth back to the far limit, and its stencil to 0. It takes a color like any clear, which goes nowhere. - **A 3D mesh** writes how far it is, with a frag or without. A mesh drawn with no frag has the engine's own look, as anywhere, and in this target that look's color is dropped: what a draw writes is said by where it's drawn, never by what it leaves out. A frag still runs for each pixel, as it may leave some out with `this.Discard()`, which is how a fence or a leaf casts a shadow with holes in it. - **A draw that stores stencil** stores it, whatever it is: a shape, text, a mesh. Its color goes nowhere. - **Everything else draws nothing there:** shapes, text, 2D meshes, a `Draw.Blit` into it, and 3D meshes under [`Depth.Read` or `Depth.None`](#doc-game--3d--depth). ## Smooth edges Text and the smooth shapes have smooth edges by themselves. A mesh's triangles don't: each pixel is in a triangle or out of it, so a slanted edge is a staircase. A target made with `samples` draws each of its pixels with that many samples, and a triangle's edge covers some of them, so the pixels along it are part the triangle's color and part what's behind it: ```csharp render.scene = RenderTarget.Window(samples: 4); // The window's size, 4 samples a pixel render.light = RenderTarget.Window(Format.Rgba16f, samples: 4); // ...after what it holds render.card = RenderTarget(200, 300, samples: 2); // ...or after a size of its own ``` `samples` is the last argument, and it's written with its name. It's 1, 2, 4 or 8; 1 is a target that says nothing. `R32f`, `Rgba32f` and `R32i` require one sample. A target containing any of them cannot use MSAA. The other formats resolve each channel by the mean of the samples, including numeric channels. The window itself has none. For a frame with smooth edges, draw the scene into a target of the window's size and bring it to the window: ```csharp view Scene(mut Render render) { render.scene.Clear(Color.black); render.scene.SetCamera(eye, look, 1.0); render.scene.Mesh(render.crate, render.faces, float4x4.identity); } [After(Scene)] view Show(Render render) { Draw.Blit(render.scene.color, Draw.window, Copy); // What its samples came to, one color a pixel } frag Copy(Vertex vertex, out Color color, Texture source) { color = source.Sample(vertex.uv); } ``` - **Its color is read like any target's.** `target.color` and `target.colors[i]` are what each pixel's samples come to, worked out each time drawing into the target ends. A frag or a kernel samples them, and a `Draw.Blit` reads them, as it would any other target's: between its smaller images too (`Filter.Trilinear`, `SampleLevel`), made of what the samples came to. (Unity's replay doesn't make those yet, and reads the resolved image alone there.) - **Its depth is read like any target's.** `target.depth` is one depth a pixel: one of the pixel's samples, as they are when the draw that reads it comes. It's only worked out for a target whose depth some draw reads, and again only after more was drawn into the target, so a target nothing reads the depth of costs nothing more. An edge in it is a step, as in a target with no samples. `Format.Depth` with `samples` is still an error: a target of depth alone has one sample. - **It costs memory:** as many colors and depths a pixel as it has samples, plus the color they come to. Four samples at the window's size is about four and a half times a plain target. A frag still runs once for each pixel a triangle covers, so drawing costs little more. - **A device may have fewer.** 4 is there on everything Tide draws with, for images of bytes. Where a device hasn't got what's asked, the target is drawn with the most it has under that, and the engine says so once in the game's output. WebGPU has 1 and 4 alone: 2 is 4 there, and 8 is 4. - **Everything draws into it** as into any target: shapes, text, meshes, frags, clears, [stencil](#doc-game--draw-settings--stencil). What's in it persists from frame to frame, like any target's. - **Edges a frag cuts with `this.Discard()` aren't smoothed:** the frag decides once a pixel. A frag that calls [`this.Cutout(alpha)`](#doc-game--shaders--cut-outs) has its alpha say where it's there instead, and those edges are as smooth as the triangles' (alpha to coverage). ## Several colors A target holds up to four color images, one for each format it's made with, and a frag writes them all at once: each of its `out` parameters goes to the image that's its place among them (see [Frags and verts](#doc-game--shaders--several-outputs)). ```csharp local singleton Deferred { RenderTarget scene; Texture albedo; Texture normals; Texture places; } view Make(mut Deferred deferred) { // A color as it's looked at, and beside it two images of floats deferred.scene = RenderTarget.Window(Format.Rgba8, Format.Rgba16f, Format.Rgba16f); deferred.albedo = deferred.scene.color; // Its first image, as ever deferred.normals = deferred.scene.colors[1]; // ...its second deferred.places = deferred.scene.colors[2]; // ...and its third } ``` - **`target.colors[i]` is the image at that place,** a `Texture` like `target.color`, which is the first. They're counted from 0, in the order of the formats. Which images a target has is said where it's made, so one it hasn't got is only found out as a draw samples it: that draw is passed by, with a line that says so. - **A frag's outputs go to them in order.** Its first output is the first image, its second the second; each type must fit that image's format. An output with no image in its place goes nowhere, as a color does in a target of depth alone, so the same frag draws into the window, where its first is the pixel and the rest are dropped. An image past the frag's outputs is left as it was. - **What the engine draws itself has one color,** which goes into the first image and leaves the others: shapes, text, and meshes drawn with no frag. - **A clear supplies each image's value** in order, and sets depth back; a single Color retains its broadcast behavior for ordinary color targets. - **`Draw.Blit` replaces as many images as its frag writes,** and leaves the others. - **Each Color output is blended like the pixel's color:** over what's in its own image, as the draw's [blend](#doc-game--draw-settings--blending) says, by its own alpha, after the draw's [tint](#doc-game--draw-settings--tints). Numeric outputs always replace what's there, with no tint or alpha multiplication; a float4 has four independent channels. - `Format.Depth` is said alone: every target has its depth already, and `target.depth` reads it whatever colors are beside it. The formats are the constructor's last arguments, after its pixels per unit when it says them: `RenderTarget(1024, 1024, 1, Format.Rgba8, Format.Rgba16f)`. Only [`samples`](#doc-game--render-targets--smooth-edges) comes after them. [Frags and verts](#doc-game--shaders--several-outputs) has a scene drawn this way to try: one frag fills three images, and a second lights the window from them. ## A target's depth Depth storage uses reversed 32-bit floats with stencil where supported, improving distant surface separation without changing camera or shader conventions. Clip coordinates still use OpenGL's -w to +w range. `this.depth`, depth `Sample` and `Compare` references still use 0 near and 1 far. These forward reads lose the additional far precision of internal storage; there is currently no raw or precise linear-depth read. WebGPU devices without `depth32float-stencil8`, and Vulkan devices without the required float depth support, keep the earlier forward depth path and its precision. Clear depth still means the far limit. A frag reads a target's depth as it reads its color: `target.depth` beside `target.color`. It's a `DepthTexture`, which a view keeps in local state, and a frag reads where it's a field of a component or a singleton it takes (see [Frags and verts](#doc-game--shaders--a-target-s-depth)). `target.depth.size` gives the actual physical dimensions in local CPU code, including the device's size limit, even for a depth-only target. The retained depth reference's `.size` also works in shaders. This reads metadata without allocating, resolving or reading back the image; `target.size` still gives logical dimensions: ```csharp local singleton Lamp { RenderTarget map; DepthTexture shadow; } view Make(mut Lamp lamp) { lamp.map = RenderTarget(1024, 1024, 1, Format.Depth); lamp.shadow = lamp.map.depth; // A reference, like a Texture: copies share the image } ``` Every target has one, with color or without, and `Draw.window` has none to read. A depth is how far the nearest thing drawn at a pixel is, from 0 at the camera's near plane to 1 at its far limit, and 1 where nothing was drawn since the target was cleared. A draw into a target can't read that target's depth, any more than its color: the draw is passed by, with a line that says so. Draw what reads it into another target, or the window. ## Reading pixels in local code In a local async function, `await target.Read()` returns `Grid2 fails IOError`, an owned copy of the first color image after the requested frame draws. For example: ```tide async void SavePixels(RenderTarget target) { if (await target.Read() is Grid2 pixels) { // pixels.size is the physical image size; pixels[x, y] is a straight Color. } } ``` It takes a frame or more and can fail if the device is lost or what reads hold together passes the limit. Never read it in match code. Multisampled targets read their resolved color. Float images retain colors above one, and alpha is not multiplied into RGB. Copy a grid into a field with `.Copy()`, following normal grid ownership, or keep it in the task: a task keeps a grid across its later waits as it keeps its lists, so `pixels` can still be read after another `await`. Reads share 64 slots with GPU list reads. An image of any size is read, a 4K or 5K window's too; what reads hold together, until they're let go of, is at most 512 MiB. ### A part of an image A read takes a part of the image after its number, if it has one: its first pixel and how many pixels across and down, in the image's own pixels, as the grid is. The part is clamped to the image, and the grid is what's inside it, from that part's first pixel; a part with nothing of the image in it fails. Reading one pixel under the mouse copies one pixel, and a big image can be read in tiles. ```tide local singleton Picked { RenderTarget ids; int id; } view Make(mut Picked picked) { // Its format is where it's made, as the read's type is the image's: each object is drawn into it with its number if (!picked.ids.valid) picked.ids = RenderTarget.Window(Format.R32i); } async void PickAt(mut Picked picked, int2 pixel) { if (await picked.ids.Read(pixel, int2(1, 1)) is Grid2 one) picked.id = one[0, 0]; } ``` `ReadDepth(from, size)` and a face's or a layer's reads take a part the same way. ### Which image, and as what A target that holds several images reads any of them, by its number: `await target.Read(1)` reads `target.colors[1]`. The number is a constant, as what a read gives depends on the image. An image of numbers is read as its own type, written in `<>`, with the bits it stores: | The image's format | The read | What it gives | |---|---|---| | `Rgba8`, `Rgba16f` | `Read()` | `Grid2`, alpha not multiplied in | | `R8`, `R16f`, `R32f` | `Read()` | `Grid2` | | `Rg8`, `Rg16f` | `Read()` | `Grid2` | | `Rgba32f`, `Rgba16f` | `Read()` | `Grid2`, its four numbers as stored | | `R32i` | `Read()` | `Grid2` | ```tide local singleton Picking { RenderTarget scene; Grid2 ids; Grid2 depths; } view Make(mut Picking picking) { if (!picking.scene.valid) picking.scene = RenderTarget.Window(Format.Rgba8, Format.R32i); } async void ReadIds(mut Picking picking) { if (await picking.scene.Read(1) is Grid2 ids) picking.ids = ids.Copy(); if (await picking.scene.ReadDepth() is Grid2 depths) picking.depths = depths.Copy(); } ``` - **Floats and ints come back bit for bit.** `R32f`, `Rgba32f` and `R32i` give what a frag or a clear wrote. `R16f` and `Rg16f` give the 16-bit float that was stored, and `R8` and `Rg8` the stored byte over 255. - **The compiler checks the type against the target's format,** so the target has to be made one way wherever it's assigned, with its formats written there: `Read()` of a `RenderTarget` parameter, or of a target made with `R32f` in one place and `Rg16f` in another, is an error that says so. A plain `Read()` of a target whose formats aren't known is checked as it runs, and fails where the image isn't a Color's. - **`Read()` of an `Rgba16f` image** gives its four numbers as they're stored, where `Read()` gives them as a Color, dividing its alpha out again. Use it for an image a frag wrote a `float4` into. ### Depth `await target.ReadDepth()` returns `Grid2 fails IOError`: each pixel's depth, 0 at the near plane and 1 at the far limit, as [`this.depth` and a depth's `Sample`](#doc-game--render-targets--a-target-s-depth) give it, whichever way the device stores it. Every target has one, a target of depth alone too. A multisampled target gives one depth a pixel. Where depth is stored as floats (reversed, as most devices store it), a depth a frag wrote comes back exactly when it's 0.5 or more, or a multiple of 2^-24; otherwise to the nearest such step, about 6e-8 (0.1 comes back as 0.10000002). On a device with 24-bit depth it comes back to the nearest of that format's steps. Compare with a tolerance, not `==`. ### Cube faces and array layers A [cube's face](#doc-game--meshes-and-textures) and an array's layer are targets, and are read the same way, one at a time: `await cube.faces[2].Read()`, `await array.layers[1].Read()`, and `ReadDepth()` of either. Each is one image, with its rows from the top as it was drawn, of the format its cube or array was made with: a face of a `Cubemap(256, Format.R16f)` is read with `Read()`, a layer of a `Format.Rg8` array with `Read()`, an `R32i` face or layer with `Read()`, by the table above. A face of a `Cubemap(size, Format.Depth)` has its depth alone: `ReadDepth()`. ### A volume's cells A `Texture3D` is read the same way, into a `Grid3` of its format's type: `await volume.Read()` for an `Rgba8` or `Rgba16f` volume, `Read()` for `R32f`, `Read()` for `Rgba32f`, `Read()` for `R32i`, each cell as a kernel's `volume[at]` reads it. As with a target, the volume is made with its format wherever it's assigned. A box of it is its first cell and how many along each axis, `int3`s: ```tide local singleton Fluid { [Raw(float)] Texture3D pressure; bool made; Grid3 slice; } view Make(mut Fluid fluid) { // A kernel writes its cells each frame if (!fluid.made) { fluid.made = true; fluid.pressure = Texture3D(int3(32), Format.R32f); } } async void Probe(mut Fluid fluid) { if (await fluid.pressure.Read(int3(0, 0, 8), int3(32, 32, 1)) is Grid3 slice) fluid.slice = slice.Copy(); } ``` A volume made from a `Grid3` is that grid's cells, which the CPU has already: read the grid, not the volume (its read is an error that says so, or fails as it runs where the compiler can't see what the volume was made of). ### How many images `target.colors.count` is how many color images a target holds: 0 for a target of depth alone and for one that was never made or was disposed. ### The window `Draw.window` can't be read: its image is the display's own, which the GPU doesn't hand back to a kernel, and under Unity it's Unity's. Draw the frame into `RenderTarget.Window()`, read that, and [`Draw.Blit`](#doc-game--shaders) it to the window. --- Source: https://tide-engine.dev/game/shaders.md Write Tide frag and vert shaders and compute kernels for the GPU, with textures, per-draw values, instancing, GPU lists, shadow maps and multiple render outputs. # Frags and verts A mesh's pixels and vertices can run code of yours on the GPU, written in Tide: a `frag` runs once for each pixel a mesh covers, and a `vert` once for each of its vertices. They're declarations, like [views](#doc-game--views), and a `Draw.Mesh` names them: ```csharp struct BoxVertex { float3 position; float3 normal; float2 uv; } // Once per vertex: changes it in place vert Wave(mut BoxVertex vertex, Time time) { vertex.position.y += Math.Sin(time.t * 2 + vertex.position.x) * 0.1; } // Once per pixel: the triangle's three vertices blended at that pixel, and the pixel's color, which it writes frag Shade(BoxVertex vertex, out Color color, Box box, Sun sun, Models models) { float light = Math.Max(Math.Dot(Math.Normalize(vertex.normal), -sun.direction), 0.1); color = models.wood.Sample(vertex.uv) * box.tint * light; color.a = 1; // The light dims the color, not how solid it is } view DrawBox(Box box, Models models) { Draw.Mesh(models.crate, models.faces, float4x4.Translate(box.pos), Wave, Shade); } ``` Their parameters say what they read, and the engine supplies it. There's nothing to bind, upload or declare twice, and no shader language to learn: tidec writes the shaders, for every GPU Tide draws with, and they always compile. Change the wave height to move the mesh's vertices, and the stripe count to change what each pixel computes. Both shaders read the same local singleton the sliders edit. Turn off animation to inspect a frame. **A frag and a vert** ([Run example](https://tide-engine.dev/examples/shaders/?stats)) ```tide scene Main { } struct RibbonVertex { float2 position; float2 uv; } local singleton Ribbon { List vertices; List indices; float amplitude = 0.3; float speed = 1.5; float bands = 6; float phase; bool animate = true; } // The GPU changes its copy of each vertex, leaving the mesh list untouched. vert Wave(mut RibbonVertex vertex, Ribbon ribbon) { vertex.position.y += Math.Sin(vertex.uv.x * 6.283185 + ribbon.phase) * ribbon.amplitude; } // UVs blend across each triangle, giving every pixel its own stripe color. frag Stripes(RibbonVertex vertex, out Color color, Ribbon ribbon) { float stripe = 0.5 + 0.5 * Math.Sin(vertex.uv.x * ribbon.bands * 6.283185); color = Color(0.18 + stripe * 0.8, 0.83 - stripe * 0.08, 0.75 - stripe * 0.61); } view Preview(mut Ribbon ribbon) { if (ribbon.vertices.count == 0) { // A strip of quads supplies enough vertices for the vert to bend. for (int i = 0; i <= 48; i++) { float u = i / 48.0; float x = (u - 0.5) * 3; ribbon.vertices.Add(RibbonVertex { position = float2(x, -0.2), uv = float2(u, 0) }); ribbon.vertices.Add(RibbonVertex { position = float2(x, -0.9), uv = float2(u, 1) }); if (i < 48) { int start = i * 2; ribbon.indices.Add(start); ribbon.indices.Add(start + 1); ribbon.indices.Add(start + 2); ribbon.indices.Add(start + 2); ribbon.indices.Add(start + 1); ribbon.indices.Add(start + 3); } } } GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Anchor.UpperLeft) { GUILayout.Slider("Wave height", ribbon.amplitude, 0, 0.6); GUILayout.Slider("Speed", ribbon.speed, 0, 4); GUILayout.Slider("Stripes", ribbon.bands, 1, 12); GUILayout.Toggle("Animate", ribbon.animate); } if (ribbon.animate) { ribbon.phase += Math.Min(Frame.dt, 0.05) * ribbon.speed; if (ribbon.phase > 6.283185) ribbon.phase -= 6.283185; } Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, 0.3), 2.2); Draw.Mesh(ribbon.vertices, ribbon.indices, Wave, Stripes); } ``` ## Your own vertex A mesh's vertices are a list of a struct, and the struct can be yours: - It has a `position`: a `float2` makes a 2D mesh, drawn through the 2D camera in order with the other Draw calls, and a `float3` a 3D one, which `Draw.Mesh` places with a transform. - Its other fields are whatever the mesh needs: floats, ints, their vectors and colors, 12 fields at most. The GPU reads them from the list as they are, so a vertex costs what its struct does: a struct with only a `position` is 12 bytes a vertex. `Draw.Mesh` takes a list of it, with or without a vert and a frag: ```csharp Draw.Mesh(vertices, indices); // 2D Draw.Mesh(vertices, indices, transform); // 3D Draw.Mesh(vertices, indices, transform, Shade); // A frag Draw.Mesh(vertices, indices, transform, Wave); // A vert Draw.Mesh(vertices, indices, transform, Wave, Shade); // Both: the vert first ``` With no frag, a pixel is its vertex's `color` times the draw's texture at its `uv`, as the built-in `Vertex` and `Vertex3` draw: a struct with no `Color color` draws white, and a texture needs a `float2 uv` to be read at. With no vert, the vertices are used as they are. A model from a file fills a struct of yours the same way, by those names and a few more (`normal`, `tangent`, `uv2`): `asset Mesh crate = "art/crate.glb";`, then `Draw.Mesh(crate, transform, Wave, Shade)`. See [Meshes](#doc-game--assets--meshes). Frags and verts can share a name when their parameters differ. A draw then names the one it means with its parameters' types, as [`[After]` names a system](#doc-game--systems--order): `Draw.Mesh(vertices, indices, Tint(Vertex, Color, Sun))`. ## A frag ```csharp frag Shade(BoxVertex vertex, out Color color, Box box, Sun sun) { color = box.tint * Math.Max(Math.Dot(vertex.normal, -sun.direction), 0.1); color.a = box.tint.a; } ``` - **The vertex comes first.** It's the struct the mesh's list holds, and the frag gets it blended across the triangle: at each pixel, a mix of the triangle's three vertices by how near each is. It can't change it. Its ints and int vectors don't blend: a frag reads them exactly as the triangle's first corner has them, as it reads [what a vert hands it](#doc-game--shaders--from-a-vert-to-its-frag), so a per-face material or ID is the same whole number at every pixel of the face. Each field it reads is one of the 15 values carried from the corners. - **`this` is the pixel the frag runs for.** Its read-only fields say where it is, and `this.Discard()` leaves it undrawn: see [Where the pixel is](#doc-game--shaders--where-the-pixel-is). - **`out Color color` is the pixel.** A frag writes its output through an [`out` parameter](#doc-language--functions--out-parameters), and returns nothing. What it wrote there when it ends is the pixel's color, blended over what's behind it by its alpha. - **It starts with no value, so the frag writes it.** On every path that ends, and before reading it: `color.a = 1` alone, with nothing written first, is an error, and so is a frag whose only write is inside an `if` with no `else`. It isn't the pixel already on the screen either: a GPU doesn't let a frag read that. A path that ends in [`this.Discard()`](#doc-game--shaders--where-the-pixel-is) draws no pixel, and owes it nothing. - **The draw's [settings](#doc-game--draw-settings) apply to it.** Inside `Draw.Blend(Blend.Add) { ... }` the pixel is added instead, and inside `Draw.Tint(...)` it's multiplied by the tint after the frag ran, so a faded menu fades its shaded meshes too, with nothing for the frag to do. A 2D mesh's vertices go through `Draw.Transform` after its vert, and a 3D one's transform goes through `Draw.Transform`. A 3D mesh does with depth what [`Draw.Depth`](#doc-game--3d--depth) says: inside `Draw.Depth(Depth.Read) { ... }` it's hidden behind what's nearer and hides nothing itself, which is how something see-through is drawn. And its triangles are drawn from the side [`Draw.Cull`](#doc-game--3d--which-side-draws) says, their front unless it says otherwise: a vert that mirrors its mesh, or turns it inside out, has them reach the screen the other way round, and is drawn inside `Draw.Cull(Cull.Front)`. Under [`Draw.Stencil`](#doc-game--draw-settings--stencil) it's drawn where its pixels pass the test, and it stores where it's drawn: a pixel the frag leaves out with `this.Discard()` stores nothing, which is how a mask gets the shape of a picture. - **Light the color, not its alpha.** A color times a number scales its alpha too, so `box.tint * light` alone leaves a pixel in the shade see-through, and what was drawn behind the mesh shows in it, its own far side too. The frag above sets `color.a` back. - **For intentional transparency, set `color.a` to the opacity you want.** A 3D draw also needs depth and ordering: see [Transparent 3D](#doc-game--draw-settings--transparent-3d). For solid pixels with holes, use [cutout holes](#doc-game--draw-settings--cutout-holes) instead. - A frag can write up to four outputs, each `out Color`, `out float`, `out float2`, `out float4` or `out int`: see [Several outputs](#doc-game--shaders--several-outputs). Number outputs replace the stored value without tint or alpha multiplication. **Tip: It used to be mut** A frag's color used to be `mut Color color`, which started white. That spelling is an error now, and the editor offers the change to `out`. A frag that leaned on the white writes it itself, `color = Color.white;`, which the editor offers too where a path is missing it. ### Several outputs A frag writes up to four images at once, with `out Color`, `out float`, `out float2`, `out float4` and `out int` parameters, into a [render target made to hold as many](#doc-game--render-targets--several-colors). They go to the target's color images in the order they're written: the first is the pixel's color, as ever, and each one after it goes to the next image. ```csharp // One pass over the scene leaves what it looks like, which way it faces and where it is frag Fill(Corner corner, out Color albedo, out Color normal, out Color place) { albedo = corner.color; normal = Color(corner.normal.x, corner.normal.y, corner.normal.z); place = Color(this.world.x, this.world.y, this.world.z); } // ...and a second one, over the whole screen, lights it from what the first left: its // first image is the Blit's source, and the others are Texture fields of a singleton frag Lit(Vertex vertex, out Color color, Texture source, Deferred deferred, Lamp lamp) { Color albedo = source.Sample(vertex.uv, Filter.Point); Color normal = deferred.normals.Sample(vertex.uv, Filter.Point); Color place = deferred.places.Sample(vertex.uv, Filter.Point); float3 toward = lamp.position - float3(place.r, place.g, place.b); float facing = Math.Max(Math.Dot(float3(normal.r, normal.g, normal.b), Math.Normalize(toward)), 0); color = Color(albedo.r * facing, albedo.g * facing, albedo.b * facing); } view Show(Models models, Deferred deferred) { deferred.scene.Clear(Color.black); deferred.scene.Mesh(models.room, models.faces, float4x4.identity, Fill); Draw.Blit(deferred.scene.color, Draw.window, Lit); } ``` - **Each is owed on every path,** as the pixel's color is: a frag that can end without writing its second output is an error that names it, and `this.Discard()` owes none of them anything. - **They're matched by their order,** not their names: `out Color albedo, out Color normal` writes a target's first image and its second, whatever the frag calls them, and wherever they are among its other parameters. - **A `Color` is four floats,** with its fourth channel used as alpha. What's kept of it is the image's to say: a [`Format.Rgba8`](#doc-game--render-targets--what-a-target-holds) image keeps each channel from 0 to 1, and a `Format.Rgba16f` one keeps it as it is, which is what a normal, a place or light brighter than white needs. - **`Color(x, y, z)` has an alpha of 1.** Each Color output is blended over what's in its image by its own alpha, as the draw's blend says, so an output that's data is written with an alpha of 1, or inside `Draw.Blend(Blend.Replace) { ... }`. - **Where there's no image for it, an output goes nowhere.** Drawn into the window, or into a target of one color image, such a frag is its first output alone; into a target of depth alone, none of them. So one frag serves a pass that fills three images and a pass that only casts a shadow. - **A target's other images are left alone** by a frag with fewer outputs than the target has images, and by everything the engine draws itself, which has one color. - A frag reads the images another draw wrote as it reads any texture, through a `Texture` field of a singleton or a component it takes: `deferred.normals = deferred.scene.colors[1];` in a view, then `deferred.normals.Sample(uv)` in the frag. It can't read an image of the target it's drawn into. The scene below is drawn once, by a frag that leaves three images: each pixel's paint, which way it faces and where it is. A second frag, over the whole window, lights every pixel from those three, with a lamp that follows the pointer, so moving the lamp draws nothing of the scene again. The slider raises the lamp, and the buttons show each image as the first pass left it. **Three images from one frag** ([Run example](https://tide-engine.dev/examples/outputs/?stats)) ```tide settings { title = "Several colors"; } local scene Main { } // A vertex of our own: the engine has no lighting, so the normal is ours. struct Corner { float3 position; float3 normal; } // One for each thing drawn: where it is, and its color. struct Block { float4x4 transform; Color paint; } local singleton Stage { RenderTarget scene; // Three color images, each the window's size Texture normals; // The second, as the frag that lights reads it Texture places; // ...and the third List cube; List faces; List blocks; float2 at; // Where the lamp is on the screen float3 lamp; // ...and in the world float height = 1.2; float turn; int show; // 0: lit. 1 to 3: one of the images, as it is bool moved; // Not before the pointer was ever on this window } // One pass over the scene, and each pixel leaves three things: its paint, which // way it faces, and where it is. Each `out Color` goes to the target's image // that's its place among them. The last two aren't colors: their images are floats. frag Fill(Corner corner, out Color paint, out Color normal, out Color place, Instance instance, Block block) { float3 facing = instance.Normal(corner.normal); paint = block.paint; normal = Color(facing.x, facing.y, facing.z); place = Color(this.world.x, this.world.y, this.world.z); } // A second pass, over the whole window, with nothing of the scene drawn again: // each pixel is lit from what the first left there. The Blit's source is the // first image, and the other two are the singleton's. frag Light(Vertex vertex, out Color color, Texture source, Stage stage) { Color paint = source.Sample(vertex.uv, Filter.Point); Color normal = stage.normals.Sample(vertex.uv, Filter.Point); Color place = stage.places.Sample(vertex.uv, Filter.Point); float3 toLamp = stage.lamp - float3(place.r, place.g, place.b); float facing = Math.Max(Math.Dot(float3(normal.r, normal.g, normal.b), Math.Normalize(toLamp)), 0); float reach = 1 / (1 + Math.Dot(toLamp, toLamp) * 0.15); // Dimmer the further the lamp is float shade = 0.3 + 1.6 * facing * reach; color = Color(paint.r * shade, paint.g * shade, paint.b * shade); if (stage.show == 1) color = paint; // A normal's parts go from -1 to 1, so half of each, from the middle if (stage.show == 2) color = Color(normal.r * 0.5 + 0.5, normal.g * 0.5 + 0.5, normal.b * 0.5 + 0.5); // A place is in meters, and goes much further: an eighth of each, from the middle if (stage.show == 3) color = Color(place.r * 0.125 + 0.5, place.g * 0.125 + 0.5, place.b * 0.125 + 0.5); } // A unit cube's side: four corners that share a normal, and two triangles, // their corners clockwise as they're seen from outside: a triangle is drawn // from that side alone. void AddSide(mut Stage stage, float3 normal, float3 right, float3 up) { int first = stage.cube.count; stage.cube.Add(Corner { position = (normal - right - up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal + right - up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal + right + up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal - right + up) * 0.5, normal = normal }); stage.faces.Add(first); stage.faces.Add(first + 2); stage.faces.Add(first + 1); stage.faces.Add(first); stage.faces.Add(first + 3); stage.faces.Add(first + 2); } view Show(mut Stage stage, Devices devices) { if (stage.cube.count == 0) { AddSide(stage, float3(1, 0, 0), float3(0, 0, 1), float3(0, 1, 0)); AddSide(stage, float3(-1, 0, 0), float3(0, 0, -1), float3(0, 1, 0)); AddSide(stage, float3(0, 1, 0), float3(1, 0, 0), float3(0, 0, 1)); AddSide(stage, float3(0, -1, 0), float3(1, 0, 0), float3(0, 0, -1)); AddSide(stage, float3(0, 0, 1), float3(-1, 0, 0), float3(0, 1, 0)); AddSide(stage, float3(0, 0, -1), float3(1, 0, 0), float3(0, 1, 0)); // A color as it's looked at, and beside it two images of floats stage.scene = RenderTarget.Window(Format.Rgba8, Format.Rgba16f, Format.Rgba16f); stage.normals = stage.scene.colors[1]; stage.places = stage.scene.colors[2]; } stage.turn += Math.Min(Frame.dt, 0.05) * 0.6; if (stage.turn > Math.TAU) stage.turn -= Math.TAU; // A floor that goes past every edge of the picture, and blocks on it and over it var spin = quaternion.AxisAngle(float3(0, 1, 0), stage.turn); stage.blocks.Clear(); stage.blocks.Add(Block { transform = float4x4.TRS(float3(0, -0.1, 0), quaternion.identity, float3(80, 0.2, 80)), paint = Color(0.29, 0.29, 0.31) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(-1.6, 0.6, 0.4), spin, float3(1.2)), paint = Color(0.98, 0.75, 0.14) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(1.3, 0.4, -0.6), quaternion.identity, float3(0.8)), paint = Color(0.18, 0.83, 0.75) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(1.3, 1.5 + Math.Sin(stage.turn * 2) * 0.4, -0.6), spin, float3(1.4, 0.2, 1.4)), paint = Color(0.98, 0.44, 0.52) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(-0.2, 0.25, -2.2), quaternion.identity, float3(2.6, 0.5, 0.5)), paint = Color(0.5, 0.5, 0.54) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(0.4, 1, 2.6), quaternion.identity, float3(0.5, 2, 0.5)), paint = Color(0.5, 0.5, 0.54) }); // The first pass: a clear fills every image, and one draw writes all three var eye = float3(0, 6.5, -9.5); stage.scene.Clear(Color.black); stage.scene.SetCamera(eye, quaternion.LookRotation(Math.Normalize(float3(0, -1.6, 0) - eye), float3(0, 1, 0)), 45); stage.scene.Instanced(stage.cube, stage.faces, stage.blocks, Fill); // The lamp follows the pointer, and goes round by itself until there is one. // It's on the ray through its pixel, where that's as high over the floor as the slider says. var pointer = Screen.Flip(devices.pointer.position); if (Math.LengthSq(devices.pointer.delta) > 0 || devices.pointer.press.pressed) stage.moved = true; if (!stage.moved) stage.at = float2(Screen.width * (0.5 + Math.Cos(stage.turn * 2) * 0.3), Screen.height * (0.34 + Math.Sin(stage.turn * 2) * 0.14)); else if (pointer.y < Screen.height - 132) stage.at = pointer; var from = stage.scene.ScreenRayOrigin(stage.at); var along = stage.scene.ScreenRayDirection(stage.at); if (along.y < -0.01) stage.lamp = from + along * ((stage.height - from.y) / along.y); // The second pass: the window gets the three images through the frag that lights Draw.Blit(stage.scene.color, Draw.window, Light); // The lamp, and the spot on the floor right under it Draw.SetScreen(); var under = stage.scene.WorldToScreen(float3(stage.lamp.x, 0, stage.lamp.z)); Draw.Line(float2(under.x, under.y), stage.at, 1, Color(0.64, 0.64, 0.68)); Draw.Circle(stage.at, 7, Color(0.086, 0.086, 0.094)); Draw.Circle(stage.at, 5, Color(0.98, 0.75, 0.14)); mut string shown = "Lit, from all three images"; if (stage.show == 1) shown = "The first image: paint"; if (stage.show == 2) shown = "The second image: which way it faces"; if (stage.show == 3) shown = "The third image: where it is"; GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 124, Screen.width - 24, 112)) { GUILayout.Label(shown); GUILayout.Slider("Lamp height", stage.height, 0.3, 3); GUILayout.Horizontal() { if (GUILayout.Button("Lit")) stage.show = 0; if (GUILayout.Button("Paint")) stage.show = 1; if (GUILayout.Button("Normals")) stage.show = 2; if (GUILayout.Button("Places")) stage.show = 3; } } } ``` ### Number images Use numeric outputs for masks, IDs, velocity, positions, moments and other data. Their types must fit the destination's [formats](#doc-game--render-targets--what-a-target-holds): ```csharp frag Data(Vertex vertex, out float mask, out float2 velocity, out float4 channels, out int id) { mask = vertex.uv.x; velocity = vertex.uv * 2 - 1; channels = float4(2, -1, 0.5, 0.25); id = 16777217; } ``` Draw this frag into a target made with `Format.R8`, `Format.Rg16f`, `Format.Rgba32f` and `Format.R32i`, in that order. A `float` goes into R8, R16f or R32f; a `float2` into Rg8 or Rg16f; a `float4` into Rgba16f or Rgba32f; an `int` into R32i. `Color` goes into Rgba8 or Rgba16f. A mismatch is a compile error at the draw, with the accepted type in the message. Outputs beyond the target's images are dropped, and later images without an output are left alone, as with color outputs. Numbers always replace what's there, whatever `Draw.Blend` says. `Draw.Tint` does not change them, and no channel multiplies any other. In particular, all four channels of a `float4` are free, including in Rgba16f. Each output must still be assigned on every path that ends; `this.Discard()` owes none. `this.Cutout` and `this.Coverage` require a Color as the first output, whose alpha supplies coverage. Use `this.Discard()` to cut holes in a frag with only numeric outputs. Declare the type of an image when retaining its reference. This is a role on the existing `Texture` type: ```csharp local singleton Buffers { RenderTarget target; [Raw(float)] Texture mask; [Raw(float2)] Texture velocity; [Raw(float4)] Texture channels; [Raw(int)] Texture ids; } view Keep(mut Buffers buffers) { if (!buffers.target.valid) buffers.target = RenderTarget.Window(Format.R8, Format.Rg16f, Format.Rgba32f, Format.R32i); buffers.mask = buffers.target.colors[0]; buffers.velocity = buffers.target.colors[1]; buffers.channels = buffers.target.colors[2]; buffers.ids = buffers.target.colors[3]; } frag Show(Vertex vertex, out Color color, Buffers buffers) { float2 velocity = buffers.velocity.Sample(vertex.uv); int id = buffers.ids.Sample(vertex.uv, Filter.Point); color = Color(velocity.x, velocity.y, float(id & 255) / 255); } ``` `Sample` returns exactly the role's `float`, `float2`, `float4` or `int`. With no filter named, a typed image reads its nearest pixel. Clamp, Repeat and Mirror still control coordinates outside the image. Float images in `R8`, `Rg8`, `R16f`, `Rg16f` and `Rgba16f` blend too, and have mipmaps made of what was drawn: ```csharp float soft = images.mask.Sample(vertex.uv, Filter.Bilinear); // Between pixels float wide = images.mask.SampleLevel(vertex.uv, 3); // A smaller image: a cheap blur float2 moments = images.velocity.Sample(vertex.uv, Filter.Trilinear); // Between pixels and levels ``` `Filter.Anisotropic` and `SampleGrad` work as they do for a color. `R32f` and `Rgba32f` blend too, with `Filter.Bilinear`: a GPU only blends 32-bit floats with an optional feature, so tidec loads the four pixels around the uv exactly and blends them in the shader, and the picture is the same bits on every device. They have no mipmaps, so `Filter.Trilinear`, `Filter.Anisotropic`, and a `SampleLevel` or `SampleGrad` that reads between levels, on one are a compile error naming `R16f` or `Rgba16f`. Their one level is the image itself: a `SampleLevel` or `SampleGrad` naming `Filter.Point` reads its nearest pixel, one naming `Filter.Bilinear` blends the four, and `SampleLevel(uv, 0)` blends them too. A cube's `R32f` and `Rgba32f` faces are only read at their nearest pixel: its `SampleLevel` names `Filter.Point`, even at level 0. `R32i` is always exact: a GPU blends no integers. Bare `[Raw]` retains its existing four-channel behavior. ```csharp float distance = images.distances.Sample(vertex.uv, Filter.Bilinear); // An R32f image: four exact loads, blended ``` The typed role goes on `Texture` and `Texture3D` fields, on `TextureArray` and `Cubemap` fields (any number format makes layers and faces: `[Raw(int)]` for `R32i`), and on read-only image parameters of synchronous GPU helpers. An array of `R32f` or `Rgba32f` is read at its nearest pixel as an exact load, and blends with `Filter.Bilinear` as above. A cube of `R32f`, `Rgba32f` or `R32i` is read at its nearest pixel: the face the direction points at and the pixel nearest it, loaded exactly. A caller supplies an image with the same role: ```csharp float Height([Raw(float)] Texture image, float2 uv) { return image.Sample(uv); } ``` An ordinary Texture parameter still samples Color; the explicit role keeps numeric types through helper chains. A frag's direct image source can carry the role too, such as `[Raw(int)] Texture source`; give that frag a matching numeric image in the draw's Texture argument. A CPU grid of numbers is an image of its role as well: a `Grid2` reads through `[Raw(float)]` (or as a color's `r`), a `Grid2` through `[Raw(float2)]`, a `Grid2` through `[Raw(float4)]`, and a `Grid2` or `Grid2` through `[Raw(int)]`. It goes into a field, a helper's parameter or a frag's or vert's Texture parameter of that role (any of the textures a draw gives), and a frag samples it by its name as those numbers (see [Grids of other numbers](#doc-game--meshes-and-textures--grids-of-other-numbers)): ```csharp local singleton Wind { Grid2 flow = Grid2(128, 128); Grid2 zones = Grid2(128, 128); } float2 Push([Raw(float2)] Texture flow, float2 uv) { return flow.Sample(uv, Filter.Bilinear); } frag Drift(Vertex vertex, out Color color, Wind wind) { float2 push = Push(wind.flow, vertex.uv); int zone = wind.zones.Sample(vertex.uv); color = Color(push.x, push.y, zone == 3 ? 1 : 0); } ``` R8, Rg8, R16f and Rg16f support multisampling and resolve each channel by its mean. R32f, Rgba32f and R32i require a single-sample target. Numeric `float4` into Rgba16f supports that format's ordinary mean resolve. ## A vert ```csharp vert Wave(mut BoxVertex vertex, Time time) { vertex.position.y += Math.Sin(time.t * 2 + vertex.position.x) * 0.1; } ``` A vert takes its vertex `mut` and changes it in place: where it is, and anything else the pixels read of it. The engine then places it with the draw's transform and the camera, and the frag gets the changed vertex, blended. The mesh's list isn't touched: the GPU changes its own copy, each frame. ### From a vert to its frag What a vert works out for the pixels needn't be a field of every vertex in the mesh. A vert writes a struct of its own, an `out` parameter, and the frag it's drawn with reads it, blended across the triangle as its vertex is: ```csharp struct FromLamp { float3 toward; // From the corner to the lamp float reach; // How much of the lamp's light gets there } vert Place(mut Corner corner, out FromLamp lamp, Lamp light, Instance instance) { float3 place = Math.Transform(instance.transform, corner.position); lamp.toward = light.position - place; lamp.reach = Math.Saturate(1 - Math.Length(lamp.toward) / light.range); } frag Look(Corner corner, FromLamp lamp, out Color color) { float facing = Math.Max(Math.Dot(Math.Normalize(corner.normal), Math.Normalize(lamp.toward)), 0); color = Color.white * (0.1 + facing * lamp.reach); color.a = 1; } view DrawRoom(Models models) { Draw.Mesh(models.room, models.faces, float4x4.identity, Place, Look); } ``` - **The draw pairs them.** A vert and a frag stay declarations of their own, and one vert can be drawn with several frags. A frag's struct is found by its type among what the draw's vert writes: a frag that reads a `FromLamp` in a draw whose vert writes none, or that names no vert, is an error at the draw. - **The vert writes all of it.** The struct starts with no value: each field is written on every path, a field at a time or all at once (`lamp = FromLamp { ... };`), before it's read. - **Floats, their vectors and colors blend.** Ints, int vectors, bytes, bools and enums are carried unchanged from the triangle's first corner, counted in the index list's order. Unity's OpenGL Core replay uses its last corner instead. Each read field still counts as one of the 15 carried values. There is no annotation for making floats flat. - **Only what the frag reads is carried.** A field no frag reads costs nothing between the two, and a vert drawn with no frag, or with one that takes none of its structs, just doesn't hand them on. A GPU carries 15 values from a mesh's corners to its pixels: each field read of the vertex or of such a struct is one. - A vert can write several structs, and a frag take any of them, each by its type. A frag can also take what its vert wrote beside an [instance's struct](#doc-game--shaders--instances-from-a-list), as long as the two are different types. ### Where a vertex lands After a vert, the engine places its vertex: the draw's transform, then the camera. A vert that wants a say in where its vertex lands in the frame takes that place as an `out` parameter, a `float4`, and writes it itself. `this.clip` is where the engine would have put it: ```csharp local singleton Lens { float2 size = float2(480, 270); // The frame's pixels, across and down } // Each corner moved onto the nearest pixel of a small frame, as a console that kept no fractions of a pixel drew vert Snap(mut Corner corner, out float4 clip, Lens lens) { float4 at = this.clip; float2 half = lens.size * 0.5; clip = float4(Math.Round(at.xy / at.w * half) / half * at.w, at.z, at.w); } ``` - **`this.clip` is where the engine would put the vertex**, read-only. It follows the vertex: it's where the transform and the camera put `corner.position` as the vert has it at that line, so a vert that also moves its vertex does that first. - **`out float4` is where the vertex goes instead.** It starts with no value, as a frag's color does: the vert writes it on every path, and `clip = this.clip;` leaves the vertex where it was. A vert takes one, and a vert with none is placed by the engine. - **Both are in clip space**, where [`Draw.WorldToClip()`](#doc-game--cameras--a-camera-as-matrices) ends: `x / w` and `y / w` go from -1 to 1 across what's drawn into, left to right and bottom to top, and `z / w` from -1 at the camera's near plane to 1 at its far limit. `w` is 1 under a camera with no perspective, and grows with distance under one that has it, which is why `Snap` divides by it and multiplies it back. - **Its depth goes with it:** a vert that writes another `z` is drawn in front of, or behind, what its place in the world says. - **The frag's `this.world` is still the vertex's own place in the world**, wherever its vert put it in the frame, so light and shadows worked out from it don't move with it. `this.position` and `this.depth` are where the pixel was drawn. - A 2D mesh's is through the 2D camera or the screen, with [`Draw.Transform`](#doc-game--draw-settings) in it. `this` in a vert has that one field, and it can't be assigned: what a vert writes is `out`. An ordinary function a vert calls has no `this`: pass it `this.clip` as a value. ## Drawing from a helper An ordinary synchronous function can name a frag or vert with the same draw syntax: ```csharp void DrawBox(List vertices, List indices, Box box, Sun sun) { Draw.Mesh(vertices, indices, float4x4.identity, Shade); } ``` If `Shade` takes `Box` and `Sun`, the function must take exactly one input parameter of each type. Pass them explicitly from the view, and forward them through other helpers normally. A missing input, two parameters of the same required type, or only an `out` parameter is an error. Read-only inputs use their passed values; a `mut` input supplies its current value. When a shader reads attached local fields, pass the actual bound parameter, as for [other local-field helpers](#doc-language--functions--functions). This also works for a target's draws, `Draw.Instanced`, `Draw.SkinnedMesh` and `Draw.Blit`. Textures, per-draw values and instance lists keep their usual syntax. The function draws in its caller's frame and follows the existing drawing restrictions. ## Configured shaders A frag or vert can take typed [function parameters](#doc-language--functions--function-values). Bind them by name using an initializer: ```csharp float Circle(float2 position) { return Math.Length(position) - 0.5; } frag ShapeLook(Vertex vertex, out Color color, Func distance) { float d = distance(vertex.uv * 2 - float2(1)); color = Color(1, 1, 1, Math.Saturate(0.5 - d)); } view DrawShape(Geometry geometry) { var fragment = ShapeLook { distance = Circle }; Draw.Mesh(geometry.vertices, geometry.indices, fragment); } ``` `Geometry` above is the game's local geometry storage. The initializer configures the shader; it doesn't execute it. Every required function slot must be named once with a matching function signature. Vertex data, outputs and ordinary draw inputs continue to come from the draw. Positional function binding such as `ShapeLook(Circle)` isn't supported. The declaration's name is also the type of its configured values: ```csharp component Appearance { local ShapeLook fragment; } ``` Views can assign and draw `appearance.fragment`, and helpers can take or return `ShapeLook`. Different bindings of the same declaration share this type. A default binding with missing function targets draws nothing. These values belong to local state, like textures. Captured values are owned copies; GPU programs and pipelines remain the renderer's resources. A callback can change an explicit GPU-local argument using `mut`: ```csharp void Bend(mut Vertex vertex) { vertex.position.y += Math.Sin(vertex.position.x); } vert Deform(mut Vertex vertex, Func deform) { deform(vertex); } // In a view: var vertexShader = Deform { deform = Bend }; Draw.Mesh(geometry.vertices, geometry.indices, vertexShader, fragment); ``` The callback changes this vertex, and helper calls forward the same mutable value. The ordinary GPU rules apply: changing local shader data grants no access to CPU state or writable instance inputs. Captured values remain read-only. ### Functions in instance data A function can also be a field of an instance struct: ```csharp struct ShapeItem { float2 center; Func distance; } vert PlaceShape(mut Vertex vertex, ShapeItem shape) { vertex.position = shape.center + vertex.position * 8; } frag FillShape(Vertex vertex, out Color color, ShapeItem shape) { float d = shape.distance(vertex.uv * 2 - float2(1)); if (d > 0) this.Discard(); color = Color.white; } ``` `Draw.Instanced(vertices, indices, shapes, PlaceShape, FillShape)` draws one quad per `ShapeItem`. Its shaders take the current item, not the whole list. Items can select different distance functions and carry different captures inside one instance run. The compiler stores a target tag with the captures and generates a switch in the shader. A new target is compiled with the game; changing a captured numeric value doesn't compile another shader. Normal batching boundaries still apply: targets, settings, shared uniforms and texture bindings must be compatible, and drawing order is preserved. The usual GPU attribute and uniform limits also apply to callable capture data. The initial capture layout reserves fields for the targets of each Func signature; many large capture variants can exceed those limits. ## What they read After the vertex, and what each writes (a frag's color, the structs a vert hands its frag, where a vert puts its vertex), a frag or vert takes the game's state, as a view does: - **Components** are those of the entity the view that draws runs for. `box.tint` in the frag above is the tint of the box being drawn: a view that runs for a thousand boxes draws them all at once, each with its own. In a drawing helper, they come from its explicit parameters instead. - **Singletons**, the match's or [local](#doc-game--local-state) ones, and `Time`. `time.t`, the match's seconds, is blended between ticks like every float a view sees, so what moves by it moves every frame. - None is `mut` or `out`: the GPU reads the game's state, and changes none of it. - A [`local` field](#doc-game--local-state) of the match's component or singleton is read like any other: `box.highlight`, which a view set for the entity under the mouse. - With [`Draw.Instanced`](#doc-game--shaders--instances-from-a-list), an ordinary struct parameter takes the current item of the instance list. It is read-only too. (A frag's struct of a type its draw's vert writes is [the vert's](#doc-game--shaders--from-a-vert-to-its-frag) instead.) - An ordinary struct parameter also takes [the values a draw gives](#doc-game--shaders--values-for-one-draw) after its vert and frag: `Draw.Blit(source, destination, Blur, BlurStep { along = float2(1, 0) })`. - Read-only `Texture` parameters receive the explicit images passed to `Draw.Mesh`, `Draw.Instanced`, a target's `Mesh` or `Instanced`, or [`Draw.Blit`](#doc-game--render-targets--post-processing), in order: the frag's first, then the vert's own, and a vert's and a frag's of one name are the one image (see [Several textures](#doc-game--shaders--several-textures)). `source.Sample(vertex.uv[, Filter.Point[, Wrap.Repeat]])` uses the same top-left UVs as grid sampling. Local component and singleton `Texture` fields can be sampled too. The view needn't take them itself. It has to run for entities that have the components, so `with Box` is enough, and it's an error at the mesh draw when it doesn't: ```csharp view DrawBoxes(with Box, Models models) { Draw.Mesh(models.crate, models.faces, float4x4.identity, Shade); // Shade reads Box and Sun } ``` What a frag sees of the match is what a view sees: [blended between ticks](#doc-game--views--smooth-at-any-tick-rate), so it's smooth at any tick rate. A frag takes no loose numbers. What it needs lives in a component, a singleton, the instance struct supplied to `Draw.Instanced`, or [a struct the draw gives it](#doc-game--shaders--values-for-one-draw). A local singleton is the place for what only this machine's drawing cares about, and every draw of the frame shares: ```csharp local singleton Look { float fog = 0.02; Color sky = Color(0.5, 0.7, 1); } frag Fog(BoxVertex vertex, out Color color, Look look) { float clear = Math.Exp(-this.depth * look.fog * 1000); color = Color.white * clear + look.sky * (1 - clear); } ``` Only the fields the code reads go to the GPU: a component's with each entity drawn, and a singleton's once for the draw. A big component costs nothing for the fields a frag doesn't name. ## Values for one draw A singleton is the same for every draw of a frame. What differs from one draw to the next, with the same frag, is a struct the draw gives after the vert and the frag it names. The frag, the vert or both take it as a read-only parameter of that struct's type: ```csharp struct BlurStep { float2 along; // From one sample of the blur to the next } frag Blur(Vertex vertex, out Color color, Texture source, BlurStep step) { var near = step.along * 1.3846; var far = step.along * 3.2308; var sum = source.Sample(vertex.uv) * 0.227 + (source.Sample(vertex.uv + near) + source.Sample(vertex.uv - near)) * 0.3162 + (source.Sample(vertex.uv + far) + source.Sample(vertex.uv - far)) * 0.0703; color = Color(sum.r, sum.g, sum.b, 1); } view PaintLight(Lens lens) { // Across, then down: one frag, and each Blit says its own direction Draw.Blit(lens.bright.color, lens.spread, Blur, BlurStep { along = float2(lens.pixel.x * 4, 0) }); Draw.Blit(lens.spread.color, lens.bright, Blur, BlurStep { along = float2(0, lens.pixel.y * 4) }); } ``` That's [Duel](https://github.com/Tide-Engine/tide-engine/tree/dev/examples/duel)'s blur. Without it, the direction would be a field of a singleton that the view writes between the two Blits. - It goes last, after the vert and the frag, in `Draw.Mesh`, `Draw.Instanced`, [`Draw.Blit`](#doc-game--render-targets--post-processing) and a target's `Mesh` and `Instanced`: `Draw.Mesh(vertices, indices, transform, Wave, Shade, Swell { height = 2 })`. Any expression of the struct's type will do: a literal, a local, a field, a function's result. - It's found by its type, as a component is, whatever the parameter is called. A draw gives one struct. Group what the vert and the frag each need in it: each reads the fields it wants. - It's sent once for the draw, with what the code reads of singletons, and only the fields the vert and the frag read. A field neither reads costs nothing, and needn't be a type a GPU has. - Draws in a row with the same mesh, the same vert and frag and the same values are still one draw call. Other values start another. - With [`Draw.Instanced`](#doc-game--shaders--instances-from-a-list), a frag can take both: the list's struct, which each instance has its own of, and the draw's, which they share. The two have to be different types, and neither can be the type the draw's vert [writes for its frag](#doc-game--shaders--from-a-vert-to-its-frag). - It holds no texture to sample. A draw's image is its `Texture` argument, or a field of a component or singleton. - It's where an animated value goes: `Glow { amount = GUI.Animate(lit ? 1.0 : 0.0, 0.2) }`, worked out on the CPU once a frame (see [Animated values in GPU code](#doc-game--gui--animated-values-in-gpu-code)). It's an error at the draw when its frag or vert takes a struct that nothing supplies (not the draw's vert, its instances or its values), and when the draw gives a struct neither takes. ## Lists and arrays A frag or a vert reads a list that's a field of what it takes (a component's, a singleton's, or the values a draw gives) or a `List` [asset](#doc-game--assets) by its name. It reads an element by its place, how many there are, and all of them with `foreach`: ```csharp struct Light { float3 position; Color color; float reach; } local singleton Lights { List items; } frag Lit(BoxVertex vertex, out Color color, Lights lights) { mut var sum = Color(0.1, 0.1, 0.1); foreach (var light in lights.items) { var far = Math.Length(light.position - this.world); if (far < light.reach) sum += light.color * (1 - far / light.reach); } color = Color(sum.r, sum.g, sum.b); } ``` - `lights.items[i]` is an element, `lights.items.count` how many, and `foreach` goes through them in order. A list has no fixed size: it's as long as the view left it, thousands of elements if it likes, and the frag loops over what's there. - An element past the end, or before the start, is zeros, as it is on the CPU. - Elements are what the GPU has values of: numbers, bytes, vectors, colors, matrices, enums, bools, structs of those, and [arrays](#doc-game--shaders--arrays) in them. Not text, longs, entities or other lists. - The GPU reads a list, and changes none: there's no `Add` there. A view or a system fills it. - A local can name it, and a function can take it, as anywhere: see [Naming a list and passing it on](#doc-game--shaders--naming-a-list-and-passing-it-on). - Each list a draw's code reads is one of its 16 textures, as that's how its numbers travel: an image of numbers, read by an element's place. - **Only what's read is sent.** Of an element, the GPU gets the fields that some frag or vert of the game reads, and no others: a `Light` with a dozen fields of which the frags read `position` and `color` costs those two. It's the same whether the code writes `lights.items[i].color`, reads it off a `foreach`'s variable, or off a local that holds an element (`var light = lights.items[i];`). A struct inside an element counts field by field. Handing a whole element to a function, or returning one, reads all of it. - **Only what changed is sent again.** A list that didn't change since the last frame costs nothing. In one that did, the elements that changed go to the GPU and the rest stay as they are there, so a few lights moving in a list of thousands cost those few. A list that's only counted (`items.count`) sends nothing at all. - A component's list is its entity's own, so entities with lists are drawn one by one, not all in one draw call. What many entities share belongs in a singleton, with each entity saying where its part starts. - The struct [`Draw.Instanced`](#doc-game--shaders--instances-from-a-list) takes for each instance can't hold a list the code reads: a draw sends one list for all of them. ### A grid's cells A grid is read the same way, a cell by its place, beside [sampling it](#doc-game--shaders--textures) as a picture: `cells[x, y]`, `cells[at]` for an `int2`, and `cells.size`; for a `Grid3`, `cells[x, y, z]`, `cells[at]` for an `int3`, and a `size` of three. It's the cell as the grid has it, exactly, of any type the GPU has values of, where `Sample` gives a color blended between cells. ```csharp local singleton Board { Grid2 owner = Grid2(64, 64); } frag Tiles(BoxVertex vertex, out Color color, Board board) { var at = int2(int(vertex.uv.x * board.owner.size.x), int(vertex.uv.y * board.owner.size.y)); color = board.owner[at] == 1 ? Color.red : Color.blue; } ``` - A cell outside the grid is zeros. The grid is a field of what the frag or vert takes, or an [asset](#doc-game--assets) by its name, and counts as one of the draw's 16 textures, once more if it's also sampled. - As with a list, only the fields of a cell that the code reads are sent, and when cells change, only those cells go to the GPU again. - An asset's grid, and an asset's list, are read by name in the functions a frag or vert calls too. - A grid with no size on an axis is read like any other: its cells are wherever they were set, before 0 too, `size` is 0 on that axis as it is on the CPU, and a cell nothing set is zeros. - What's sent is the box around the cells that were set, never the whole space a grid spans. (A grid keeps its cells in chunks, 64 by 64 or 16 by 16 by 16 of them for a cell of one number, and the box is the chunks that have something in them, within the grid's size.) It travels as one image of numbers, a `Grid3`'s layers side by side in it. - So how big a grid the GPU reads goes by that box. One of 256 by 256 by 256 cells of one number each (an int, a float, a byte, an enum), or 128 by 128 by 128 colors, fits an image 2,048 pixels a side, which every GPU has. The most is an image of 16,777,216 pixels and 16,384 a side, on a GPU that has textures so big: 256 by 256 by 256 colors, or a `Grid2` of 16,384 by 4,096 numbers. A box past that isn't sent, the code reads zeros, and the game says so once in its output; two cells set a million apart in a grid with no size are such a box. - `foreach` over a grid's cells isn't there yet: write the loop over the places you read, `for (int y = 0; y < cells.size.y; y++)`. ### Maps and sets A `Map` or a `Set` that's such a field is read by its keys, as it is anywhere: ```csharp local singleton Land { Grid2 ground = Grid2(64, 64); Map paint; // By a tile's number Set lit; } frag Tiles(BoxVertex vertex, out Color color, Land land) { var at = int2(int(vertex.uv.x * land.ground.size.x), int(vertex.uv.y * land.ground.size.y)); var tile = land.ground[at]; var known = land.paint.TryGet(tile, out var paint); var shown = known ? paint : Color.gray; color = land.lit.Has(tile) ? shown : shown * 0.5; color.a = 1; } ``` - `map[key]` is the key's value, or zeros when the key isn't there. `map.Has(key)` and `set.Has(key)` say whether it is, and `map.TryGet(key, out var value)` says so and gives the value, or the value type's default. `count` is how many keys there are. - `foreach (var entry in map)` goes through a map's entries, each with its `key` and its `value`, and `foreach (var key in set)` through a set's keys: in the order the keys were added, without the ones removed since, as on the CPU. - Keys are ints, bytes, chars or enums. A map keyed by text, a `long`, an `Entity` or a `PlayerID` stays on the CPU, and reading one in a frag is an error that says why: keep a second map keyed by a number for what the GPU reads. - Values are what the GPU has values of, as a list's elements are. - Read-only, as lists are: a view or a system fills the map. There's no `Get` there either, as it gives a value that may be missing: `TryGet` asks the same. - `TryGet`'s `out` argument is a local, `out var value` or a variable declared before. - A lookup reads a pixel or two of an index the engine sends beside the entries, however many keys the map has, so it costs about what reading two list elements does. - A map or a set is one of the draw's 16 textures, and isn't sent again while it doesn't change. Of its values, only the fields the code reads are sent, as a list's elements'. The other rules are a list's: a local can name one and a function can take one ([below](#doc-game--shaders--naming-a-list-and-passing-it-on)), a component's is its entity's own, and none in an instance's struct. ### Naming a list and passing it on A local can name a list or a grid, and a function can take one, so the code that goes through a list is written once: ```csharp float Brightest(List lights, float3 at) { mut var most = 0.0; foreach (var light in lights) { most = Math.Max(most, 1 - Math.Length(light.position - at) / light.reach); } return most; } int Owner(Grid2 owner, float2 uv) { return owner[int(uv.x * owner.size.x), int(uv.y * owner.size.y)]; } frag Lit(BoxVertex vertex, out Color color, Lights lights, Board board) { var items = lights.items; var glow = Brightest(items, this.world); color = Owner(board.owner, vertex.uv) == 1 ? Color(glow, 0, 0) : Color(0, 0, glow); } ``` - A function that takes a `List` is the same function a system or a view calls: it compiles for both. - On the GPU the list isn't handed over as the code runs. Which list a name stands for is settled as the shader is written, and a function is written once for each list it's called with. It costs nothing while it runs, and it's why a name there is for one list, for good: - A list's or a grid's local isn't `mut`, and it's given a list by its name: a field of what the frag or vert takes, an asset, another such local, or a parameter. Not one picked as the code runs, like `flag ? a.items : b.items`: read each under its own name, and pick between what was read. - A function reads the list or grid it takes: no `mut` or `out`, and none is returned, made, or kept in a struct. - A function that takes a grid is the GPU's alone: frags, verts and the functions they call call it. On the CPU a grid's cells are read through its component or singleton, `board.owner[x, y]`. A grid's local is in a frag, a vert or such a function. - A function samples the texture it takes too, a grid among them: see [In a function](#doc-game--shaders--in-a-function). ### Passing on what holds a list A struct, a singleton or a component that holds lists, grids, maps or sets goes to a function whole, and its methods are called on it, so the code that reads it needn't name each list: ```csharp struct Poses { int bones; List rows; float4 Row(int row, int bone) { return rows[row * bones + bone]; } } float4 Hips(Poses poses, int row) { return poses.Row(row, 0); } vert Play(mut Corner corner, Item item, Poses poses) { corner.position += Hips(poses, item.row).xyz; } ``` - It's the one the frag or vert was given, by its name: its own parameter (the draw's values, a singleton, a component), or a function's parameter that stands for one. Nothing is handed to the function for it: its fields are read where the frag or vert reads them, and only the fields some code reads are sent. - It's read, never changed: a `mut` method or parameter is an error. It isn't kept in a local, made, returned or picked between there, as a list isn't. - A struct that holds no list is a value as before, passed and kept like any other. ### Arrays An [array of a fixed length](#doc-language--text-and-lists--arrays) is a value like a vector: `float[8]`, `Stop[4]`. As a field of a component, a singleton or a draw's values it's sent with the other fields the code reads, and in code it's a local, a parameter or a function's result like any other value: ```csharp local singleton Ramp { Color[4] stops; } frag Shade(BoxVertex vertex, out Color color, Ramp ramp) { mut float[3] sums = [0, 0, 0]; foreach (var stop in ramp.stops) sums[0] += stop.r; color = ramp.stops[int(vertex.uv.x * 4)] * sums[0]; } ``` - `a[i]` reads an element, zeros past the ends; `a[i] = v` writes one, and does nothing past the ends; `a.count` is its length; `foreach` goes through it. - An array is sent whole, with a draw's other values: those hold 3,984 bytes in 2D (249 float4s) or 3,968 bytes in 3D (248 float4s), for everything a draw reads of singletons. Past a few dozen elements, a list is the better fit. - An array of arrays is one too: `float[4][8] rows`, with `rows[i][j]` read and written by the same rules at each index, and `rows[i]` a row to keep, pass on, assign or `foreach` through. - `?:` picks between arrays, as between structs and matrices: `var stops = night ? ramp.dark : ramp.light;`. Both sides are worked out, as everywhere on the GPU. - A `for`'s step can write an element (`for (var k = 0; k < 6; counts[k % 3]++)`), and a `continue` still comes to it. ## Textures `Sample` reads a [texture](#doc-game--meshes-and-textures--textures) at a `uv`, and gives its color there. A frag samples the textures it can name three ways: ```csharp frag Shade(Corner corner, out Color color, Models models, Texture source) { color = models.wood.Sample(corner.uv) // A field of a component or singleton it takes * tiles.Sample(corner.uv) // An asset, by its name * source.Sample(corner.uv); // The texture its draw gives it } view Crates(Models models) { Draw.Mesh(models.crate, models.faces, models.label, Shade); // models.label is Shade's `source` } ``` - **A field**: a `Texture`, a `Grid2` or a `Grid2` of a component or a singleton the frag takes (and a grid of other numbers, read as [its numbers](#doc-game--shaders--number-images)). - **`Sample` gives the color itself**, with its alpha beside it, blended between pixels so that a clear pixel counts for none of the color (see [Alpha](#doc-game--draw-settings--alpha)). A pixel with no alpha reads as `Color(0, 0, 0, 0)`. What a frag writes is a color as it is too: `Color(1, 0, 0, 0.5)` is red, half clear. - **An asset**, by its name, with no parameter for it: `asset Texture tiles = "art/tiles.png";` and then `tiles.Sample(uv)` (see [Assets](#doc-game--assets--images-to-draw-with)). - **Its own `Texture` parameters**, as many as it takes, which are whatever textures the draw gives after its mesh, in order: an asset, a target's color, a grid, a `Texture` a field holds. A [`Draw.Blit`](#doc-game--render-targets--post-processing)'s source is its frag's first (see [Several textures](#doc-game--shaders--several-textures)). `uv` is as a mesh's: (0, 0) is the outer corner of the texture's first pixel and (1, 1) the outer corner of its last. Verts sample too. A `Grid2` gives its number as the color's `r`, with `g` and `b` 0 and `a` 1 (see [One channel](#doc-game--meshes-and-textures--one-channel)). How it's read is the texture's own to say, and the `Sample`'s where it says: ```csharp color = models.wood.Sample(corner.uv); // As `wood` says: blended and clamped, if it says nothing color = models.wood.Sample(corner.uv, Filter.Point); // The nearest pixel color = models.wood.Sample(corner.uv * 4, Filter.Point, Wrap.Repeat); // Four times across, and four down ``` Past 0 and 1, `uv` reads what the [wrap](#doc-game--meshes-and-textures--past-the-edges) says: the pixels at the edge (`Wrap.Clamp`), the texture again (`Wrap.Repeat`), or again the other way round each time (`Wrap.Mirror`). A frag is where a wrap earns its keep, since it works its `uv` out: `corner.uv * 4` tiles a floor, and `corner.uv + float2(time.t * 0.1, 0)` scrolls one. - What a `Sample` leaves out is the texture's: what its declaration says ([`[Filter]` and `[Wrap]`](#doc-game--meshes-and-textures--saying-it-once-on-the-texture)), and blended and clamped with nothing said. A `Texture` carries that with it, so a frag's `source` is read as whichever texture the draw gave says, and a `Texture` field as whichever it holds: the same frag draws `tiles` repeated and `hero` clamped, in two draws. - A draw can say it for that draw, after the texture: `Draw.Mesh(corners, faces, tiles, Filter.Bilinear, Wrap.Clamp, Shade)` gives `source` blended and clamped, whatever `tiles` says. - A filter and a wrap written at a `Sample` are written out, `Filter.Point` and `Wrap.Repeat`, never read from a variable: the GPU is told how a texture is read before any pixel runs. Where they come with the texture, the engine tells it for each draw. - A wrap comes after a filter, so a `Sample` that says how it wraps says both. The names work too: `Sample(uv: corner.uv, filter: Filter.Bilinear, wrap: Wrap.Repeat)`. - One texture can be read several ways in one frag, clamped here and repeated there. It counts once among the 16 textures a draw reads, however it's read. Each way of reading takes a sampler, and a draw has 16 of those too: textures read the same way share one, and the same way twice is one. A `Texture` parameter or field whose `Sample` leaves its filter or wrap to the texture has a sampler of its own for that, since the texture says how at each draw; so there, a `Sample` that says nothing and one that says the default are two samplers. - A draw gives as many textures as its frag and vert take, and none to a frag that takes none: `Draw.Mesh(corners, faces, models.wood, Shade)` is an error where `Shade` has no `Texture` parameter, and so is a draw that gives fewer or more than its frag takes. ### Several textures A frag takes as many `Texture` parameters as it reads, and the draw gives them in the same order after its mesh. A material of three images is one frag, drawn with each part's images: ```csharp frag Lit(PartVertex vertex, out Color color, Texture colour, Texture normal, Texture orm, Look look) { float3 n = normal.Sample(vertex.uv).rgb * 2 - 1; Color orms = orm.Sample(vertex.uv); color = colour.Sample(vertex.uv) * look.tint * Math.Saturate(n.z) * (1 - orms.g); } view Parts(Kit kit) { kit.target.Mesh(kit.barrel, kit.transform, kit.metalColour, kit.metalNormal, kit.metalOrm, Lit, Look { tint = kit.metal }); kit.target.Mesh(kit.stock, kit.transform, kit.woodColour, kit.woodNormal, Filter.Point, kit.woodOrm, Lit, Look { tint = kit.wood }); } ``` `Look` is a struct, `struct Look { Color tint; }`, given as [the draw's values](#doc-game--shaders--values-for-one-draw) after the frag. - **In the frag's order.** The first texture after the mesh's arguments (a 3D mesh's transform, an `Instanced` draw's list) is the frag's first `Texture` parameter, and so on. Every draw form takes them so: `Mesh`, `Instanced`, `SkinnedMesh` and a target's own, over the CPU's lists or a GPU list's. - **A filter and a wrap go after the texture they're for**, and are that texture's alone for this draw: above, the wood's normal map is read at its nearest pixels, and its colour and ORM as they say. A texture with nothing after it is read as it says itself, or as the frag's `Sample` says. - **A vert takes them too.** Its `Texture` parameters are the draw's as well: one of the same name as a frag's is that one texture, and one of its own comes after all of the frag's. `vert Raise(mut PartVertex vertex, Texture normal, Texture height)` drawn with `Lit` takes `colour, normal, orm, height`. With no frag, the first texture is what the mesh's pixels are drawn with. - **A blit gives them before its destination**: `Draw.Blit(source, lut, Draw.window, Grade)` for `frag Grade(Vertex vertex, out Color color, Texture source, Texture lut)`. It takes no filter or wrap; its frag's `Sample` says those. - **A [`[Linear]`](#doc-game--shaders--linear-light-color) image goes to a `[Linear] Texture` parameter**: `frag Lit(PartVertex vertex, out Color color, [Linear] Texture colour, Texture normal, Texture orm, Look look)` takes the material's marked albedo from the draw beside the unmarked normal and ORM maps. A marked image given to an unmarked parameter is an error, since it would lose its mark, and so is an unmarked one given to a marked parameter (a `Grid2` goes to either). A `[Linear]` field of a component or singleton the frag takes, or that a [function it calls is handed](#doc-game--shaders--in-a-function), works too. - **Each is a texture of the draw's own**, among the 16 it reads, with samplers of its own where its `Sample` leaves the filter or wrap to the texture. A draw that gives fewer or more textures than its frag and vert take is an error that names the ones they take, in order. `Filter.Trilinear` reads between the texture's smaller copies too, so it's smooth where the texture ends up [smaller than it is](#doc-game--meshes-and-textures--drawn-smaller): ```csharp frag Ground(Corner corner, out Color color, Land land) { var uv = corner.uv * land.tiling; // Worked out from what the frag is given color = Color.black; if (corner.height > 0) { color = land.grass.Sample(uv, Filter.Trilinear, Wrap.Repeat); // In a branch, as any Sample } } ``` The GPU picks which copies to read by how fast the `uv` changes from one pixel to the next, and it only knows that before any branch or loop. So a frag works such a `uv` out a first time as it starts, asks there, and reads with the answer wherever the `Sample` is. You write nothing for it, and the `Sample` goes where it would anyway: in a branch, in a loop, after `this.Discard()`. What it asks of you is a `uv` it can work out as it starts: - **Made of** the frag's parameters (its vertex, what its vert wrote for it, components, singletons, the draw's values), the pixel's fields through `this`, constants, `Math`, constructors, your own functions that take everything by value, another texture read at its own pixels, and variables declared with `var` that are never assigned again. - **Not of** a variable that changes (`mut var`, one a loop counts): `tiles.Sample(corner.uv + float2(i * 0.01, 0), Filter.Trilinear)` in a loop is an error, which says so. Sample those with `Filter.Bilinear`, or work each `uv` out before the loop. - Where the filter is the texture's to say (a frag's `Texture` parameter, a `Texture` field) and the `uv` can't be worked out as the frag starts, the `Sample` reads the texture's own pixels, as `Filter.Bilinear` would, whatever the texture says, and tidec warns about it: write `Filter.Bilinear` there to say that's what you want, or make the `uv` one the frag can work out as it starts. - A vert has no pixels to compare, so there `Filter.Trilinear` reads the texture's own pixels. `Filter.Anisotropic` is `Filter.Trilinear` for a surface [seen at a shallow angle](#doc-game--meshes-and-textures--seen-at-a-shallow-angle): where a pixel covers a long strip of the texture, it reads along the strip, so ground and floors keep their detail into the distance. Everything above holds for it as it does for Trilinear (the `uv` a frag can work out as it starts, the warning, a vert's and a function's own pixels), and a texture, a `TextureArray`'s layer and a `Cubemap` all take it. When a UV changes in a loop or needs a different sampling footprint, give its derivatives explicitly with `Texture.SampleGrad`: ```tide var dx = this.Ddx(vertex.uv); var dy = this.Ddy(vertex.uv); mut var uv = vertex.uv; // Adjust uv here, including in branches or loops. color = source.SampleGrad(uv, dx, dy, Filter.Trilinear, Wrap.Repeat); ``` `SampleGrad(float2 uv, float2 dx, float2 dy[, filter[, wrap]])` takes the UV change per destination pixel to the right and down. It uses those values as given, without working the UV out again as the frag starts. Compute derivatives of the original UV with `this.Ddx` and `this.Ddy`, then pass them alongside the adjusted UV when that is the footprint you want. It works in a frag and in its GPU helper functions, including after a discard and inside varying branches or loops. A helper takes the derivatives as ordinary `float2` parameters. The optional filter and wrap follow `Sample`'s rules and default to the texture's own. `Filter.Point` and `Filter.Bilinear` still read only its base image; `Filter.Trilinear` uses the supplied derivatives to choose its smaller images, and for `Filter.Anisotropic` they are the strip the pixel covers: the GPU reads along the longer of the two and picks the smaller image by the shorter. So give them as they are (ground textured by its world position: `this.Ddx(p) * scale` and `this.Ddy(p) * scale`); derivatives made longer or equal on purpose, to blur, leave it nothing to read along. Ordinary colors and `[Raw] Texture` fields keep their usual channel behavior. `SampleGrad` is for `Texture`; verts, CPU code, grids, cubemaps and depth textures do not expose it. ### In a function A function a frag or a vert calls samples too: a texture it takes as a parameter, which is the one its call names, or an asset by its name. So a lookup that several frags share is written once: ```csharp // Four reads around a place, a pixel apart: a blur Color Soft(Texture image, float2 uv, float2 pixel) { return (image.Sample(uv + float2(-pixel.x, -pixel.y)) + image.Sample(uv + float2(pixel.x, -pixel.y)) + image.Sample(uv + float2(-pixel.x, pixel.y)) + image.Sample(uv + float2(pixel.x, pixel.y))) * 0.25; } frag Shade(Corner corner, out Color color, Models models, Texture source) { color = Soft(models.wood, corner.uv, models.pixel) // A field of what the frag takes * Soft(tiles, corner.uv, models.pixel) // An asset * Soft(source, corner.uv, models.pixel); // The texture its draw gave it } ``` - **The parameter is a `Texture`**, which a `Grid2` and a `Grid2` are too, a [`DepthTexture`](#doc-game--shaders--a-target-s-depth) or a [`Cubemap`](#doc-game--shaders--skybox-and-reflections), and the function reads it as a frag would: `Sample`, with a filter and a wrap or without, a depth's `Compare`, a cube's `Sample(direction)`. - **The call names the texture**: a field of a component or a singleton the frag or vert takes, its own `Texture`, an asset, or in a function, a parameter of its own, passed on. Not one picked as the code runs, like `flag ? models.wood : models.stone`: sample each under its own name, and pick between the colors. - **It isn't handed over as the code runs.** No GPU passes a texture to a function, so which texture a name stands for is settled as the shader is written, and the function is written once for each texture it's called with, as it is for [a list](#doc-game--shaders--naming-a-list-and-passing-it-on). It costs nothing while it runs. A function reads the texture it takes: no `mut` or `out`, and none is returned, kept in a local or in a struct. - **What a `Sample` there leaves out is still the texture's**: `Soft(tiles, ...)` reads `tiles` as its declaration says, and `Soft(source, ...)` as the texture the draw gave says. Each way each texture is read counts among the draw's 16. - **A function that samples is the GPU's alone**: frags, verts and the functions they call call it. A view or a system that calls one is an error that says so, as nothing on the CPU reads a texture's pixels. A function that only takes a texture and passes it to C, say, is still everyone's. - **A function's `Sample` reads the texture's own pixels, never between its smaller copies.** `Filter.Trilinear` is for a frag's own `Sample`, of a `uv` the frag can work out as it starts, and a function's `uv` is its call's. In a function a frag reaches, it's an error where the `Sample` says `Filter.Trilinear` or leaves its filter to a texture that says it, and a warning where it leaves it to a `Texture` that may (a field, the frag's own): write `Filter.Bilinear` there, sample in the frag, or use `SampleGrad` with explicit derivatives passed from the frag. - **A [`[Raw]`](#doc-game--shaders--textures-that-are-numbers) source keeps numeric sampling through GPU helpers.** Pass the original Raw asset, Raw texture field or Raw grid field expression to the helper's `Texture` parameter. The compiler specializes the helper for that source; this does not allow a Raw texture to escape through an ordinary CPU `Texture` value. A function can take the component or the singleton that holds the textures, too, and sample its fields, so a lighting helper reads a stage's shadows and sky without a parameter for each: ```csharp local singleton Stage { RenderTarget near; DepthTexture shadow; Cubemap sky; float4x4 toLamp; float3 sun; Color Above(float3 way) { return sky.Sample(way); } // A method samples its own fields } float3 Sunlit(Stage stage, float3 world, float3 normal) { float3 at = FromLamp(world, stage.toLamp); float lit = stage.shadow.Compare(at.xy, at.z - 0.001); return stage.sun * lit * Math.Saturate(normal.y) + stage.Above(normal).rgb * 0.25; } frag Ground(Corner corner, out Color color, Stage stage) { float3 light = Sunlit(stage, this.world, corner.normal); color = Color(light.x, light.y, light.z); } ``` - **What the frag or vert was given, by its name**: its own component or singleton parameter, or a function's parameter that stands for one, as for [what holds a list](#doc-game--shaders--passing-on-what-holds-a-list). Nothing is passed for it while it runs: each texture of it is the shader's, by its type and its field, and the function is written once however many calls it has. - **Everything a function does with its own `Texture` it does with a field**: `Sample`, `SampleLevel` and `SampleGrad` with or without a filter and a wrap, a depth's `Compare`, a cube's, an array's and a volume's reads, `.size`, a kernel helper's store into an image, and passing `stage.shadow` on to a function that takes a `DepthTexture`. A method of the singleton samples its fields by their names, `sky.Sample(way)`, and calls its other methods on the same one. A component's textures and fields are each entity's, as a frag reads them, from its vert and from its frag alike. - **Local fields go with it.** A frag or vert hands such a function the local fields of the match's component or singleton it reads, as a view hands its own functions. One that holds no texture and no list goes to a function as a value of its match fields, as it did, so a function that reads its local fields is an error there: read the local field in the frag and pass what it holds. - **It's still a name, not a value**: a copy of the singleton in a local, `var kept = stage;`, is an error, as it is for one that holds a list. One whose textures are all `local` fields of a match component or singleton is a value of its other fields, as before, in a frag and in a function alike: the copy has none of its textures, and goes nowhere the one it was made of goes. A plain struct carries no texture to the GPU, so a function that samples a struct's field is an error that says to take the component or singleton, or the texture itself; and a texture in a struct the singleton holds, `stage.lamps.shadow`, isn't sampled in a function yet. - **It's the GPU's alone**, as any function that samples is: a view that calls `Sunlit` is an error. ### Linear-light color Mark color images used by lighting with `[Linear]`. Their stored RGB is display-encoded sRGB; GPU reads decode it to linear light before filtering, including `SampleGrad` and `SampleLevel`. Alpha stays coverage. Leave normal maps, masks and other numeric images unmarked or `[Raw]`. ```csharp [Linear] asset Texture wood = "art/wood.png"; frag Lit(Vertex vertex, out Color color) { Color surface = wood.Sample(vertex.uv); color = surface * Color(0.5, 0.5, 0.5); // Lighting uses linear values } ``` Keep copied references in `[Linear] Texture`, `[Linear] TextureArray` or `[Linear] Cubemap` fields. Sample these by their field or asset name. Read-only GPU helpers can borrow their source with an ordinary resource parameter. The mark goes on a glob's list or map too, every image marked (`[Linear] asset List albedos = "art/albedo/*.png";`, read by element or `foreach`), through a local that isn't `mut`, a `?:` or switch whose every side is marked, a function's `[Linear] Texture` parameter and a frag's `[Linear] Texture` source. An unmarked field, `mut` local or parameter, a return, or the engine's own draw would lose the mark, so the compiler refuses those escapes. `[Raw, Linear]` is an error. A marked Texture field can take a `Grid2` or an RGBA8 target's `.color`; a marked TextureArray field can take a `Grid3` or a runtime RGBA8 array, and a marked Cubemap field can take a runtime RGBA8 cube. Float and single-channel formats have no sRGB form. The compiler follows where the target comes from, into a field or a local alike: an assignment, a struct's `{ target = RenderTarget(...) }`, and what a function assigns a target it's handed as `out` or `mut`, a recursive one too. Every way a field or local is given an image counts, so one made two ways has no one format. One C, a built-in or a `virtual` function makes has no format the compiler can see, and is an error that names the function. A marked read of an image that turns out not to be RGBA8 draws nothing and says so. A rendered image is copied for its marked reads when it has been drawn into, not every frame. The mark changes only the sampled image: CPU grid cells, `Decode`, the original target and `target.Read()` keep their values. It does not convert a frag's output or the screen. For a final display pass, tone-map linear light first and use `Math.ToDisplay`; for an unmarked input that needs explicit conversion, use `Math.ToLinear`. Both take `float`, `float3` and `Color`; Color alpha is preserved. In Unity, marked images work in either color space. A Linear project uses Unity's sRGB formats; a Gamma project, which has none, reads them through a copy decoded to linear light, at twice an RGBA8 image's memory. Tide never changes the project's settings. ### Textures that are numbers A texture is colors, each with how much of it there is: where a pixel's alpha is 0 it has no color, and a `Sample` there gives `Color(0, 0, 0, 0)` (see [Alpha](#doc-game--draw-settings--alpha)). That's wrong for an image whose channels are four numbers of their own: a mask in alpha beside a roughness in red, a lookup table, a flow map. `[Raw]` says so where the texture is declared: ```csharp [Raw] asset Texture masks = "art/masks.png"; // Kept as the file has it local singleton Terrain { [Raw] Grid2 blend = Grid2(64, 64); // ...or as code wrote its cells [Raw] Texture mask; // A retained numeric texture } view BindTerrain(mut Terrain terrain) { terrain.mask = masks; // Raw asset into a Raw field } Color ReadMask(Texture image, float2 uv) { return image.Sample(uv, Filter.Bilinear); // Keeps its source's Raw sampling } frag Ground(Vertex vertex, out Color color, Terrain terrain) { Color mask = ReadMask(terrain.mask, vertex.uv); // Four numbers, as they are Color weights = terrain.blend.Sample(vertex.uv); // Blended between cells as numbers color = Color(mask.r * weights.r, mask.g, mask.b * weights.a); } ``` - It goes before an asset that's one `Texture`, a `TextureArray`, a `Cubemap` or one `Grid2`, and on a `Texture`, `TextureArray`, `Cubemap`, `Grid2` or `Grid3` field. A match component uses an attached local field, such as `[Raw] local Texture mask;`, because textures belong to this machine. A grid of floats needs none: it has no alpha. - Arrays and cubes follow the same rules as `Texture`: a `[Raw] TextureArray` field takes a `[Raw]` array asset, another `[Raw] TextureArray` field or a `[Raw] Grid3`, and a `[Raw] Cubemap` field a `[Raw]` cube asset or another such field. Their `Sample` gives the numbers as they are. - A `[Raw] Texture` field accepts `default`, a singular `[Raw] Texture` asset, another `[Raw] Texture` field, or a `[Raw] Grid2` field or asset. A grid-backed texture still names the grid's cells, with the [same lifetime rules](#doc-game--meshes-and-textures--a-texture-is-a-value). Assigning an ordinary color texture to a Raw field is an error. - A frag or a vert samples the Raw asset or field by name, directly or through a [GPU texture helper](#doc-game--shaders--in-a-function). Samples preserve the channel numbers, including where alpha is zero. The Raw field declaration determines numeric sampling; there is no separate Raw texture type or runtime Raw marker carried by arbitrary `Texture` values. - **The role goes where the compiler can see it go.** A glob's list or map takes the mark for every image (`[Raw] asset List normals = "art/normals/*.png";`), and `normals[i]`, a `foreach`'s variable and a map entry's `value` are Raw images. A local that isn't `mut` keeps the role of what it's given, and so does a `?:` or a switch whose every side is Raw. A function takes one as a `[Raw] Texture` parameter (or a whole glob as `[Raw] List`), whose argument must be Raw, and a frag takes one as its `[Raw] Texture` source, which a draw gives it: ```csharp [Raw] asset List normals = "art/normals/*.png"; local singleton Material { [Raw] Texture normal; int kind; } void Use(mut Material m, [Raw] Texture normal) { m.normal = normal; } frag Copy(Vertex vertex, out Color color, [Raw] Texture source) { color = source.Sample(vertex.uv); } view Pick(mut Material m) { var chosen = m.kind < normals.count ? normals[m.kind] : normals[0]; // Raw, as both sides are Use(m, chosen); Draw.Blit(normals[0], Draw.window, Copy); } ``` - Raw sources cannot become ordinary `Texture` fields, `mut` locals or unmarked parameters, be returned, or be drawn by the engine's own shader (a draw with no frag). These uses are errors, and so is a `?:` with a Raw side and a color side, or a `[Raw]` side and a `[Linear]` one: a value has one role, never one added or dropped along the way. - Each typed role, `[Raw(float)]`, `[Raw(float2)]`, `[Raw(float4)]` and `[Raw(int)]`, is a role of its own: it goes through a local that isn't `mut`, a choice whose every side has it, and a function's parameter of that role (`int2 Size([Raw(int)] Texture ids)`), on the CPU too, but not into a bare `[Raw]` parameter or one of another type, and a `?:` between two of them is an error. A frag draws a typed local's image as its typed source. - Each texture a draw gives goes to the frag parameter that reads it, and is held to that one's role alone: a frag taking a `[Linear] Texture` and a plain one is given a `[Linear]` image and an ordinary one. A vert's Texture and a frag's of one name are one texture, so they take the same role, and a vert's takes neither `[Raw]` nor `[Linear]`. - `rawField.size` is available as ordinary texture metadata, including `int2(0)` for a default or unavailable image; pack reload follows the currently bound asset. Reading its size does not read or convert its pixels. - The same file can be declared twice, once `[Raw]` and once not: they're two textures. Where `[Raw]` changes nothing, as for an image with no transparency, the pack and the GPU keep one copy for both. - A Raw `Texture` asset is [compressed](#doc-game--assets--gpu-compression) as a color one is, when it's big enough: BC1 or BC3, its channels as the file has them, each a little off. For numbers that must be exact, a lookup table or a flow map, add `[Lossless]`: `[Raw, Lossless] asset Texture flow = "art/flow.png";`. - `[Filter]` and `[Wrap]` go beside Raw assets and grid fields as on other textures. A `Texture` field retains the bound texture's filter/wrap settings; those attributes do not go on the field itself. Code reads a `[Raw]` grid's cells as it reads any grid's. ## A target's depth Depth storage uses reversed 32-bit floats with stencil where supported, improving distant surface separation without changing camera or shader conventions. Clip coordinates still use OpenGL's -w to +w range. `this.depth`, depth `Sample` and `Compare` references still use 0 near and 1 far. These forward reads lose the additional far precision of internal storage; there is currently no raw or precise linear-depth read. WebGPU devices without `depth32float-stencil8`, and Vulkan devices without the required float depth support, keep the earlier forward depth path and its precision. Clear depth still means the far limit. A [render target](#doc-game--render-targets--what-a-target-holds) keeps how far the nearest thing drawn at each of its pixels is, and a frag reads that as it reads a color: `target.depth`, a `DepthTexture`, which a view keeps in a field of a singleton or a component the frag takes. ```csharp local singleton Lamp { RenderTarget map; DepthTexture shadow; float4x4 toLamp; } view Make(mut Lamp lamp) { lamp.map = RenderTarget(1024, 1024, 1, Format.Depth); lamp.shadow = lamp.map.depth; } ``` A frag reads it two ways: ```csharp float far = lamp.shadow.Sample(uv); // The depth stored there float lit = lamp.shadow.Compare(uv, depth); // How much of what's stored there isn't nearer than `depth` ``` - **`Sample(uv)`** gives the depth as a number: 0 at the camera's near plane, 1 at its far limit, as [`this.depth`](#doc-game--shaders--where-the-pixel-is) is, and 1 where nothing was drawn since the target was cleared. It's the nearest pixel's, with no filter to pick: a depth blended between two pixels would be neither's. - **`Compare(uv, value)`** compares what's stored with a number of yours, and gives a number from 0 to 1: 1 where what's stored isn't nearer than `value`, 0 where it is, and in between along an edge, as the GPU compares the pixels around `uv` and blends what that gives. `value` is kept between 0 and 1, so what's past the far limit counts as at it. - **`size`** gives the depth image's width and height as an `int2` of physical pixels, on the CPU and GPU. It follows target resize, display scale and the device's size limit; missing or disposed depth gives `int2(0)`. Reading dimensions copies no pixels and uses no texture binding. For pixel-sized shadow offsets, use `float2 texel = 1.0 / float2(lamp.shadow.size)` after checking that the size is nonzero. `uv` is a color's: (0, 0) is the target's top left corner. Past the target's edges, both read the pixels at the edge: a depth takes no `Wrap`. Verts read a depth too. A depth is one of its draw's [16 textures](#doc-game--shaders--what-the-gpu-runs) however it's read: sampled and compared, it's one texture through two samplers. A function reads a depth it takes as a parameter the same two ways, so every frag that's lit shares one lookup. The frag names the depth where it calls: ```csharp // How much of the lamp's light gets to a place in its image: four looks around it, which soften a shadow's edge float Sunlight(DepthTexture depth, float2 uv, float far) { return (depth.Compare(uv + float2(-SOFT, -SOFT), far) + depth.Compare(uv + float2(SOFT, -SOFT), far) + depth.Compare(uv + float2(-SOFT, SOFT), far) + depth.Compare(uv + float2(SOFT, SOFT), far)) * 0.25; } frag Wall(Corner corner, out Color color, Lamp lamp) { float sun = Sunlight(lamp.shadow, uv, depth); // `uv` and `depth`: where the pixel is in the lamp's image, below ... } ``` It's written for the depth each call names, as a function that samples [a texture](#doc-game--shaders--in-a-function) is, and the same rules hold: the call names a field of a component or a singleton the frag takes, a function passes its own parameter on, and one that reads a depth is the GPU's alone. ### A shadow map That second read is what a shadow is. Draw what casts into a target of depth alone, through a camera where the lamp is, and that target holds how far the lamp sees along each of its pixels. A frag that lights a pixel then asks whether the lamp sees that far: it works out where its pixel is in the lamp's image, and compares how far the pixel is from the lamp with what's stored there. The scene below does it. **Lamp** turns the lamp, **Soft edges** takes four comparisons around the pixel where one would do, and **The lamp's depth** shows the lamp's own image in the corner: near is dark, and what nothing was drawn on is white. **A shadow map** ([Run example](https://tide-engine.dev/examples/shadows/?stats)) ```tide settings { title = "Shadows"; } local scene Main { } // A vertex of our own: the engine has no lighting, so the normal is ours. struct Corner { float3 position; float3 normal; } // One for each thing drawn: where it is, and its color. struct Block { float4x4 transform; Color paint; } local singleton Stage { RenderTarget map; // What's nearest the lamp: depth alone, 1024 pixels a side on any display DepthTexture shadow; // ...as the frags read it float4x4 toLamp; // From the world to the lamp's clip space float3 lampDirection; List cube; List faces; List blocks; List corner; // Where the lamp's depth is shown float turn; float lampAngle = 0.9; bool soft = true; bool showDepth; } // Once for each pixel: its own light, and whether the lamp sees it. frag Lit(Corner corner, out Color color, Instance instance, Block block, Stage stage) { float3 normal = instance.Normal(corner.normal); float facing = Math.Max(Math.Dot(normal, -stage.lampDirection), 0); // Where this pixel is in the lamp's image, and how far from the lamp float4 seen = Math.Mul(stage.toLamp, float4(this.world, 1)); float2 uv = float2(seen.x * 0.5 + 0.5, 0.5 - seen.y * 0.5); // A little nearer than it is, so what the lamp sees isn't in its own shadow float depth = seen.z * 0.5 + 0.5 - 0.003; // 1 where nothing is nearer the lamp, 0 in shadow: the GPU blends the edge mut float lit = stage.shadow.Compare(uv, depth); if (stage.soft) { // ...and four of those, a pixel of the lamp's image apart, blend it wider float step = 1.5 / 1024; lit = (stage.shadow.Compare(uv + float2(-step, -step), depth) + stage.shadow.Compare(uv + float2(step, -step), depth) + stage.shadow.Compare(uv + float2(-step, step), depth) + stage.shadow.Compare(uv + float2(step, step), depth)) * 0.25; } float shade = 0.22 + 0.78 * facing * lit; color = Color(block.paint.r * shade, block.paint.g * shade, block.paint.b * shade); } // The lamp's image itself: near is dark, and what nothing was drawn on is white. frag LampDepth(Vertex vertex, out Color color, Stage stage) { float depth = stage.shadow.Sample(vertex.uv); color = Color(depth, depth, depth); } // A unit cube's side: four corners that share a normal, and two triangles, // their corners clockwise as they're seen from outside: a triangle is drawn // from that side alone. void AddSide(mut Stage stage, float3 normal, float3 right, float3 up) { int first = stage.cube.count; stage.cube.Add(Corner { position = (normal - right - up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal + right - up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal + right + up) * 0.5, normal = normal }); stage.cube.Add(Corner { position = (normal - right + up) * 0.5, normal = normal }); stage.faces.Add(first); stage.faces.Add(first + 2); stage.faces.Add(first + 1); stage.faces.Add(first); stage.faces.Add(first + 3); stage.faces.Add(first + 2); } view Show(mut Stage stage) { if (stage.cube.count == 0) { AddSide(stage, float3(1, 0, 0), float3(0, 0, 1), float3(0, 1, 0)); AddSide(stage, float3(-1, 0, 0), float3(0, 0, -1), float3(0, 1, 0)); AddSide(stage, float3(0, 1, 0), float3(1, 0, 0), float3(0, 0, 1)); AddSide(stage, float3(0, -1, 0), float3(1, 0, 0), float3(0, 0, -1)); AddSide(stage, float3(0, 0, 1), float3(-1, 0, 0), float3(0, 1, 0)); AddSide(stage, float3(0, 0, -1), float3(1, 0, 0), float3(0, 1, 0)); // Depth alone: nothing looks at this target but the frags that read its depth stage.map = RenderTarget(1024, 1024, 1, Format.Depth); stage.shadow = stage.map.depth; stage.corner = [Vertex { position = float2(12, 12) }, Vertex { position = float2(108, 12), uv = float2(1, 0) }, Vertex { position = float2(108, 108), uv = float2(1, 1) }, Vertex { position = float2(12, 108), uv = float2(0, 1) }]; } stage.turn += Math.Min(Frame.dt, 0.05) * 0.6; if (stage.turn > Math.TAU) stage.turn -= Math.TAU; // A floor, and blocks on it and over it: one of them turns, one bobs var spin = quaternion.AxisAngle(float3(0, 1, 0), stage.turn); stage.blocks.Clear(); stage.blocks.Add(Block { transform = float4x4.TRS(float3(0, -0.1, 0), quaternion.identity, float3(9, 0.2, 9)), paint = Color(0.24, 0.25, 0.27) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(-1.6, 0.6, 0.4), spin, float3(1.2)), paint = Color(0.98, 0.75, 0.14) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(1.3, 0.4, -0.6), quaternion.identity, float3(0.8)), paint = Color(0.18, 0.83, 0.75) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(1.3, 1.5 + Math.Sin(stage.turn * 2) * 0.4, -0.6), spin, float3(1.4, 0.2, 1.4)), paint = Color(0.98, 0.44, 0.52) }); stage.blocks.Add(Block { transform = float4x4.TRS(float3(-0.2, 0.25, -2.2), quaternion.identity, float3(2.6, 0.5, 0.5)), paint = Color(0.64, 0.64, 0.68) }); // The lamp looks down at the middle from 12 away, and sees a box 12 by 12 with no perspective stage.lampDirection = Math.Normalize(float3(Math.Cos(stage.lampAngle), -1.2, Math.Sin(stage.lampAngle))); var lamp = float4x4.TRS(stage.lampDirection * -12, quaternion.LookRotation(stage.lampDirection, float3(0, 1, 0)), float3(1)); var sees = float4x4.Ortho(12, 12, 0.1, 30); // What casts, through the lamp's camera: no frag, as there's no color to write there stage.map.Clear(Color.white); stage.map.SetCamera(lamp, sees); // ...and that camera as a matrix, from the world to the lamp's clip space, for the frag that lights stage.toLamp = stage.map.WorldToClip(); stage.map.Instanced(stage.cube, stage.faces, stage.blocks); // Then the picture: every pixel asks the lamp's image whether the lamp sees it Draw.Clear(Color(0.086, 0.086, 0.094)); var eye = float3(0, 6.5, -9.5); Draw.SetCamera(eye, quaternion.LookRotation(Math.Normalize(float3(0, -1.6, 0) - eye), float3(0, 1, 0)), 45); Draw.Instanced(stage.cube, stage.faces, stage.blocks, Lit); Draw.SetScreen(); if (stage.showDepth) Draw.Mesh(stage.corner, [0, 1, 2, 0, 2, 3], LampDepth); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 124, Screen.width - 24, 112)) { GUILayout.Slider("Lamp", stage.lampAngle, 0, Math.TAU); GUILayout.Toggle("Soft edges", stage.soft); GUILayout.Toggle("The lamp's depth", stage.showDepth); } } ``` - **What casts is drawn with no frag,** and has the engine's own look, as anywhere: in a target of depth alone, a color has nowhere to go, and how far each pixel is, is what's kept. A caster with holes in it names a frag that calls `this.Discard()` for them. - **The lamp's camera is an ordinary one:** `target.SetCamera(transform, projection)`, with `float4x4.Ortho` for a lamp that's far away, like a sun, and `float4x4.PerspectiveFov` for one that's near. - **Where a pixel is in the lamp's image is yours to work out,** from the matrix that takes the world to the lamp's clip space. That's the lamp's camera, which the target gives back as the GPU has it: [`target.WorldToClip()`](#doc-game--cameras--a-camera-as-matrices), asked once the camera is set, and kept where the frag reads it: ```csharp lamp.map.SetCamera(transform, projection); lamp.toLamp = lamp.map.WorldToClip(); ``` ```csharp float4 seen = Math.Mul(lamp.toLamp, float4(this.world, 1)); float2 uv = float2(seen.x * 0.5 + 0.5, 0.5 - seen.y * 0.5); // From the image's top left corner float depth = seen.z * 0.5 + 0.5; // From 0 to 1, as what's stored is ``` Under a perspective, divide `seen.xyz` by `seen.w` first. - **Compare a little nearer than the pixel is,** `depth - 0.003`: a surface the lamp sees is exactly as far as what's stored there, to the rounding, and would be in its own shadow in stripes. How much it takes goes with how slanted the surface is to the lamp and how few pixels the lamp's image has across what it sees. - **A target with pixels of its own** (`RenderTarget(1024, 1024, 1, ...)`) casts the same shadows on every display. The fewer pixels it has across what the lamp sees, the blockier a shadow's edge. - **The target that's read isn't the one drawn into.** A draw into a target that reads that target's depth is passed by, with a line that says so. - **The target that's read has no `samples`.** A target made with [`samples`](#doc-game--render-targets--smooth-edges) keeps several depths a pixel, which no frag reads: a draw that reads its depth is passed by the same way. ## Skybox and reflections A `Cubemap` is six square images, the faces of a cube, which a frag reads by a direction from the cube's middle: the color of whatever is that way. It's how a sky is drawn, and what a mirror reads. ```csharp asset Cubemap sky = "art/sky_??.png"; frag Sky(Corner corner, out Color color) { color = sky.Sample(corner.position); } ``` - **`Sample(direction)`** takes a `float3` of any length, in the world's axes. One face goes on in the next, so there's no edge, and nothing to [wrap](#doc-game--meshes-and-textures--past-the-edges). - **`Sample(direction, filter)`** says how it's read between its pixels, written there like a texture's: `Filter.Bilinear` when left out, `Filter.Point` for the nearest pixel, and `Filter.Trilinear` between its [smaller images](#doc-game--shaders--textures) too, in a frag, of a direction the frag can work out as it starts. - **The cube is an asset by its name,** or a field of a component or a singleton the frag takes, where a view put one. Verts read one too, and so does a function that takes a `Cubemap`, which reads the one its call names (see [In a function](#doc-game--shaders--in-a-function)). It's one of its draw's [16 textures](#doc-game--shaders--what-the-gpu-runs), and each filter it's read with is one of its 16 samplers. - A cube that was never set reads as black. There are two kinds, and a frag reads both the same way. **An asset's** is six files that a glob matches, each named for its face by how its name ends before the extension: `px`, `nx`, `py`, `ny`, `pz` and `nz`, the faces `+x`, `-x`, `+y`, `-y`, `+z` and `-z` point at. Each is a PNG, a square, and all six are one size (see [Assets](#doc-game--assets--cubemaps)). **One a view draws into** is `Cubemap(size)`: six images of `size` pixels a side, each a [render target](#doc-game--render-targets) to draw into. ```csharp local singleton Room { Cubemap around; bool made; } view Reflect(mut Room room) { if (!room.made) room.around = Cubemap(256); room.made = true; for (var face = 0; face < 6; face++) { var into = room.around.faces[face]; into.SetCamera(float3(0), Facing(face), 90); into.Clear(Color.black); into.Mesh(corners, faces, transform, Look); } } ``` - **`cube.faces[0]` to `cube.faces[5]`** are `RenderTarget`s, in the order `+x`, `-x`, `+y`, `-y`, `+z`, `-z`. Each has everything a target has: its own camera, clip and settings, `Clear`, `Mesh`, `Instanced` and the rest, and depth of its own. - **A face that's drawn again each frame is cleared first.** Its color and its depth stay from frame to frame, as any target's do: without a `Clear`, what was nearest in the frames before hides what's drawn now. - **A face is what a camera at the cube's middle sees along the face's axis,** with a field of view of 90: `+y` is up for the four around, and for the one above and the one below, `-z` and `+z`. That's six rotations, which the example below has as `Facing`. - `Cubemap(size, Format.Rgba16f)` holds floats, which keep what's brighter than 1, where the device draws into them. A [number format](#doc-game--shaders--number-images) holds numbers, and `Cubemap(size, Format.Depth)` depth alone, for a lamp that shines every way: its frag reads `cube.depth`, a `DepthCubemap` kept in a field, with `Sample(direction)` and `Compare(direction, depth)` (see [A cube of depth alone](#doc-game--render-targets--a-cube-of-depth-alone)). - **`cube.SampleLevel(direction, level)`** reads a smaller image, between the two nearest it: a blurred reflection's roughness, `room.around.SampleLevel(reflected, roughness * 5)`. - Its size is in pixels, whatever the display. `cube.Resize(size)` gives it another, with empty images, and `cube.Dispose()` lets it go. Copies share it, as a target's do. - **A draw into a face doesn't read that face's cube.** It's passed by, with a line that says so. What reflects itself in itself takes two cubes. - A face has no `color` or `depth` of its own to hand out: the cube is what's read. The scene below has both. The sky is the asset, drawn on a ball around the camera. The ball in the middle reads a cube that's drawn again each frame from where it is: the sky and the three moons, a face at a time. **Reflect the moons** switches it to the sky's own files, which have no moons in them. Drag to look around. **A sky, and a ball that reflects what's around it** ([Run example](https://tide-engine.dev/examples/skybox/?stats)) ```tide settings { title = "Skybox and reflections"; } local scene Main { } // Six files, a face each, which the glob matches: sky_px.png is the face +x // points at, sky_nx.png the one behind it, then py, ny, pz and nz. asset Cubemap sky = "art/sky_??.png"; // A vertex of our own: the engine has no lighting, so the normal is ours. struct Corner { float3 position; float3 normal; } // One for each ball that goes round: where it is, and its color. struct Moon { float4x4 transform; Color paint; } local singleton Room { Cubemap around; // What the ball in the middle sees, drawn again each frame List ball; List faces; List moons; float3 eye; float turn; float look = 0.5; float tilt = 0.2; bool live = true; } // The sky: a ball around the camera, each pixel read towards where it is. frag Sky(Corner corner, out Color color) { color = sky.Sample(corner.position); } // A moon: lit from where the sky is brightest, and by the sky above it. frag Painted(Corner corner, out Color color, Instance instance, Moon moon) { float3 normal = instance.Normal(corner.normal); float lit = Math.Max(Math.Dot(normal, Math.Normalize(float3(0.45, 0.35, 0.82))), 0); Color above = sky.Sample(normal); color = Color(moon.paint.r * (0.25 + 0.75 * lit) + above.r * 0.3, moon.paint.g * (0.25 + 0.75 * lit) + above.g * 0.3, moon.paint.b * (0.25 + 0.75 * lit) + above.b * 0.3); } // The mirror: each pixel reads the cube towards where a ray from the eye bounces. frag Mirror(Corner corner, out Color color, Room room) { float3 from = Math.Normalize(this.world - room.eye); float3 away = Math.Reflect(from, corner.normal); // The cube a view drew, with the moons in it, or the sky's own files mut Color seen = sky.Sample(away); if (room.live) seen = room.around.Sample(away); float edge = Math.Pow(1 - Math.Max(Math.Dot(-from, corner.normal), 0), 3); color = Color(seen.r * (0.82 + 0.18 * edge), seen.g * (0.82 + 0.18 * edge), seen.b * (0.82 + 0.18 * edge)); } // The way a camera looks to fill a face: along the face's axis with +y up, // and for the faces above and below, with -z and +z up. quaternion Facing(int face) { if (face == 0) return quaternion.LookRotation(float3(1, 0, 0), float3(0, 1, 0)); if (face == 1) return quaternion.LookRotation(float3(-1, 0, 0), float3(0, 1, 0)); if (face == 2) return quaternion.LookRotation(float3(0, 1, 0), float3(0, 0, -1)); if (face == 3) return quaternion.LookRotation(float3(0, -1, 0), float3(0, 0, 1)); if (face == 4) return quaternion.LookRotation(float3(0, 0, 1), float3(0, 1, 0)); return quaternion.LookRotation(float3(0, 0, -1), float3(0, 1, 0)); } view Show(Devices devices, mut Room room) { if (room.ball.count == 0) { // A sphere of rings, built once: each corner's normal is its position. for (var ring = 0; ring <= 24; ring++) { for (var step = 0; step <= 48; step++) { float across = step * Math.TAU / 48; float down = ring * Math.PI / 24; var at = float3(Math.Sin(down) * Math.Cos(across), Math.Cos(down), Math.Sin(down) * Math.Sin(across)); room.ball.Add(Corner { position = at, normal = at }); if (ring < 24 && step < 48) { int first = ring * 49 + step; room.faces.Add(first); room.faces.Add(first + 1); room.faces.Add(first + 49); room.faces.Add(first + 1); room.faces.Add(first + 50); room.faces.Add(first + 49); } } } // Six images of 256 pixels a side, each a target to draw into room.around = Cubemap(256); } room.turn += Math.Min(Frame.dt, 0.05) * 0.5; if (room.turn > Math.TAU * 6) room.turn -= Math.TAU * 6; // Three moons go round the middle, each its own way room.moons.Clear(); for (var i = 0; i < 3; i++) { float angle = room.turn * (1 + i * 0.5) + i * 2.1; var at = float3(Math.Cos(angle) * 2.5, Math.Sin(angle * 0.5 + i) * 0.9, Math.Sin(angle) * 2.5); var paint = i == 0 ? Color(0.98, 0.75, 0.14) : i == 1 ? Color(0.18, 0.83, 0.75) : Color(0.98, 0.44, 0.52); room.moons.Add(Moon { transform = float4x4.TRS(at, quaternion.identity, float3(0.42)), paint = paint }); } // What the middle sees, a face at a time: the sky, from inside its ball, and the moons var all = float4x4.TRS(float3(0), quaternion.identity, float3(20)); for (var face = 0; face < 6; face++) { var into = room.around.faces[face]; into.SetCamera(float3(0), Facing(face), 90); // A face keeps its depth from frame to frame, and the last frame's moons would hide this one's into.Clear(Color.black); into.Cull(Cull.Front), into.Depth(Depth.None) { into.Mesh(room.ball, room.faces, all, Sky); } into.Instanced(room.ball, room.faces, room.moons, Painted); } // Then the picture. A drag looks around var pointer = devices.pointer; if (pointer.press.pressed) { room.look -= pointer.delta.x * 0.01; room.tilt = Math.Clamp(room.tilt + pointer.delta.y * 0.01, -1.2, 1.2); } else { room.look += Math.Min(Frame.dt, 0.05) * 0.12; } room.eye = float3(Math.Sin(room.look) * Math.Cos(room.tilt), Math.Sin(room.tilt), -Math.Cos(room.look) * Math.Cos(room.tilt)) * 5.2; Draw.SetCamera(room.eye, quaternion.LookRotation(Math.Normalize(-room.eye), float3(0, 1, 0)), 50); // The sky is behind everything: its ball is around the eye, seen from inside, and writes no depth Draw.Cull(Cull.Front), Draw.Depth(Depth.None) { Draw.Mesh(room.ball, room.faces, float4x4.TRS(room.eye, quaternion.identity, float3(1)), Sky); } Draw.Instanced(room.ball, room.faces, room.moons, Painted); Draw.Mesh(room.ball, room.faces, float4x4.TRS(float3(0), quaternion.identity, float3(1.3)), Mirror); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40)) { GUILayout.Toggle("Reflect the moons", room.live); } } ``` - **The sky is a ball around the eye,** drawn from inside (`Cull.Front`) and with `Depth.None`, so everything else is in front of it. Its frag reads the cube towards each corner's own position. - **A reflection is `Math.Reflect`:** the way from the eye to the pixel, bounced off the pixel's normal, is the way the mirror reads. - **Six passes a frame is what a live reflection costs.** A cube that only holds what doesn't move is drawn once and kept: its images stay from frame to frame, like any target's. - **`Filter.Trilinear` reads a cube's smaller images,** which the renderer makes of what was last drawn into it when a draw reads them. That's what keeps a reflection of something far away from shimmering. A rough surface's blurred reflection picks a smaller image itself with `cube.SampleLevel(direction, level)`, above. ## Texture arrays Images of one size in layers are a `TextureArray`, read by a uv and a layer. An asset's is a glob's files, in their paths' order, or a list of them in its own: ```tide asset TextureArray ground = ["art/grass.png", "art/rock.png", "art/sand.png"]; frag Ground(Vertex3 vertex, out Color color, Terrain terrain) { int material = int(terrain.splat.Sample(vertex.uv).r * 2.99); // Any int, which can differ from pixel to pixel color = ground.Sample(vertex.uv * 16, material, Filter.Trilinear, Wrap.Repeat); } ``` - The layer is an int. One past the layers reads the nearest one. - The filter and the wrap are written at the `Sample`, as a cube's filter is, or on the asset (`[Filter]`, `[Wrap]`). An array that says none is read blended and clamped. `SampleGrad(uv, dx, dy, layer)` takes its derivatives as a texture's does. - An array is one of a draw's [16 textures](#doc-game--shaders--what-the-gpu-runs), however many layers it has. A view makes one to draw into, a layer at a time: `TextureArray(width, height, layers)`, sized as a [render target](#doc-game--render-targets) is, with a `Format` last when a layer holds anything but `Format.Rgba8`. `array.layers[i]` is a `RenderTarget`, and `array.depth` is a `DepthTextureArray`, each layer's depth, which a frag reads as a [target's depth](#doc-game--shaders--a-target-s-depth) with a layer: `Sample(uv, layer)` and `Compare(uv, layer, value)`. Shadow cascades are layers of depth alone: ```tide local singleton Lamp { TextureArray maps; DepthTextureArray cascades; } view Shadows(mut Lamp lamp) { if (lamp.maps.count == 0) { lamp.maps = TextureArray(2048, 2048, 3, 1, Format.Depth); lamp.cascades = lamp.maps.depth; } for (int c = 0; c < 3; c++) { var into = lamp.maps.layers[c]; into.Clear(Color.white); // ...each cascade's camera and casters } } frag Lit(Vertex3 vertex, out Color color, Lamp lamp, Sun sun) { int cascade = Cascade(this.world, sun); // Your own choice of cascade, per pixel float lit = lamp.cascades.Compare(ToLamp(this.world, sun, cascade), cascade, Depth(this.world, sun, cascade)); color = Color(lit, lit, lit); } ``` `array.size` and `array.count` say a layer's pixels and how many there are, in a view or a frag. `array.Resize(width, height)` and `array.Dispose()` are the whole array's. An asset's layers are compressed as a [`Texture` asset's](#doc-game--assets) are, where they're big enough; `[Lossless]` before it keeps them exact. A `Grid3` or a `Grid3` is an array wherever one goes, its z its layers, as a `Grid2` of them is a texture: the GPU gets the parts whose cells changed. ```tide local singleton Terrain { Grid3 paint = Grid3(256, 256, 4); TextureArray layers; } view Paint(mut Terrain terrain) { terrain.paint[10, 20, 2] = Color.red; // Layer 2, sent as that part alone terrain.layers = terrain.paint; } ``` ## Where the pixel is The engine supplies the draw's transform through `Instance instance`, and the pixel a frag runs for through `this`: ```csharp frag Lit(BoxVertex vertex, out Color color, Instance instance, Sun sun) { float3 normal = instance.Normal(vertex.normal); float3 toLight = Math.Normalize(sun.position - this.world); color = Color.white * Math.Max(Math.Dot(normal, toLight), 0.1); color.a = 1; } ``` The sphere below has a vertex of its own, with a normal, and a frag that lights each pixel from it: the normal as it is in the world, from `instance.Normal`, against a light the slider moves. **Squash** flattens the sphere through the draw's transform, and its light stays right. **Bands** rounds the light to steps, in the same frag. **Lighting, in a frag** ([Run example](https://tide-engine.dev/examples/lighting/?stats)) ```tide settings { title = "Lighting"; } local scene Main { } // A vertex of our own: the engine has no lighting, so the normal is ours. struct Corner { float3 position; float3 normal; } local singleton Globe { List corners; List faces; float turn; float lightAngle = 0.8; float squash = 1; bool bands; } // Once for each pixel: its normal, blended across the triangle, against a light. // instance.Normal gives the normal as it is in the world, however the draw's // transform scales the mesh: squash the globe, and its light stays right. frag Lit(Corner corner, out Color color, Instance instance, Globe globe) { float3 normal = instance.Normal(corner.normal); float3 toLight = Math.Normalize(float3(Math.Cos(globe.lightAngle), 0.6, -Math.Sin(globe.lightAngle))); mut float diffuse = Math.Max(Math.Dot(normal, toLight), 0); if (globe.bands) diffuse = Math.Floor(diffuse * 4) / 4; // Steps, as a cartoon's float3 halfway = Math.Normalize(toLight + float3(0, 0, -1)); float glint = Math.Pow(Math.Max(Math.Dot(normal, halfway), 0), 40); // A checker from where the pixel is on the mesh, so its turning shows. float tile = Math.Floor(corner.position.y * 3) + Math.Floor(Math.Atan2(corner.position.z, corner.position.x) * 6 / Math.PI); Color paint = Math.Frac(tile * 0.5) < 0.25 ? Color(0.98, 0.75, 0.14) : Color(0.8, 0.52, 0.08); color = paint * (0.12 + diffuse * 0.88) + Color(1, 1, 1, 0) * glint; // A color times a number scales its alpha too, and a pixel is blended by // its alpha: left so, the dark side would be see-through. color.a = 1; } view Show(mut Globe globe) { if (globe.corners.count == 0) { // A sphere of rings, built once. Each corner's normal is its position. // A triangle is drawn from the side its corners go clockwise on, so // each is listed that way round as it's seen from outside. for (var ring = 0; ring <= 16; ring++) { for (var step = 0; step <= 32; step++) { float across = step * Math.TAU / 32; float down = ring * Math.PI / 16; var at = float3(Math.Sin(down) * Math.Cos(across), Math.Cos(down), Math.Sin(down) * Math.Sin(across)); globe.corners.Add(Corner { position = at, normal = at }); if (ring < 16 && step < 32) { int first = ring * 33 + step; globe.faces.Add(first); globe.faces.Add(first + 1); globe.faces.Add(first + 33); globe.faces.Add(first + 1); globe.faces.Add(first + 34); globe.faces.Add(first + 33); } } } } globe.turn += Math.Min(Frame.dt, 0.05) * 0.4; if (globe.turn > Math.TAU) globe.turn -= Math.TAU; Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float3(0, -0.32, -4.4), quaternion.identity, 45); var spin = quaternion.AxisAngle(float3(0, 1, 0), globe.turn); Draw.Mesh(globe.corners, globe.faces, float4x4.TRS(float3(0), spin, float3(1, globe.squash, 1)), Lit); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(12, Screen.height - 124, Screen.width - 24, 112)) { GUILayout.Slider("Light", globe.lightAngle, 0, Math.TAU); GUILayout.Slider("Squash", globe.squash, 0.25, 1); GUILayout.Toggle("Bands", globe.bands); } } ``` - `Instance instance`, in a frag or a vert, is how the mesh was drawn: - `instance.transform` is the `float4x4` the draw was given: `Math.Transform(instance.transform, vertex.position)` is a corner's place in the world. - `instance.Normal(vertex.normal)` is a normal of the mesh as it is in the world, of length 1, however the transform scales the mesh. Nothing more is sent for it: the GPU works it out from the transform, once a vertex. - **A normal isn't turned like a direction.** `Math.Rotate(instance.transform, vertex.normal)` is right only for a mesh scaled the same every way. On a ball drawn as an egg, or a cylinder drawn as a flat disc, it leans the normals the wrong way, and the lighting is subtly off with nothing to say why. `Normal` is right for those, for a mesh turned inside out by a scale under 0 (its normals still point out of it), and for one flattened to nothing along an axis (they're along that axis). - A vert that moves its mesh's corners itself (a wave, a bend) changes its normals in ways only the game knows: `Normal` goes by the draw's transform. - In a frag, `this` is the pixel it runs for, as `this` in a system is its entity. It needs no parameter, and its fields are read-only: - `this.world`, a `float3`: where on the mesh the pixel is, in the world. - `this.position`, a `float2`: where it is in the destination's logical pixels from the top left, as [`Draw.Screen`](#doc-game--views--on-the-screen)'s. - `this.depth`: how far it is, from 0 at the camera's near side to 1. - `this.front`, a read-only bool: whether the pixel is on the triangle's front by `Draw.Cull`'s winding, including mirrored model and camera transforms, even under `Cull.None`. In 3D it uses one of the 15 carried values; in 2D it reports rasterized winding. Pass the bool to a helper that needs it. - `this.Discard()` leaves the pixel undrawn, and ends the frag there: for holes. Nothing is written for it: no color, no depth and no [stencil](#doc-game--draw-settings--stencil). For an edge cut out of a texture, [`this.Cutout`](#doc-game--shaders--cut-outs) is smoother. - `this.Cutout(alpha)` and `this.Coverage(share)` say how much of the pixel the frag covers: see [Cut-outs](#doc-game--shaders--cut-outs). - `this.Ddx(v)`, `this.Ddy(v)` and `this.Fwidth(v)` say how fast a value changes across the pixel: see [How fast a value changes](#doc-game--shaders--how-fast-a-value-changes). `this` is context accessed through its fields and methods: it can't be copied, stored or passed whole. It belongs to the frag itself: a vert has no pixel yet (its `this` is its vertex, [as it's placed](#doc-game--shaders--where-a-vertex-lands)), and an ordinary function a frag calls has no implicit `this`. Pass any pixel coordinates a helper needs as ordinary values. An old built-in `Pixel pixel` parameter is an error that says to remove it and use `this`; a game can still declare a type of its own named `Pixel`. ```csharp frag Leaves(BoxVertex vertex, out Color color, Models models) { color = models.leaves.Sample(vertex.uv); if (color.a < 0.5) this.Discard(); } ``` The camera isn't given: keep where yours is in a singleton, where the view that calls `Draw.SetCamera` reads it too, and take that. ### How fast a value changes `this.Ddx(v)` is how much `v` changes from this pixel to the next one across, `this.Ddy(v)` to the next one down, and `this.Fwidth(v)` the two's sizes added: `Math.Abs(this.Ddx(v)) + Math.Abs(this.Ddy(v))`. `v` is a `float`, a float vector or a `Color`, and what comes back is of its type. It's how a frag knows how big a pixel is in its own units, wherever the mesh is, however it's turned, scaled or far away. A signed distance over it is an edge one pixel wide: ```csharp frag Ring(Vertex3 vertex, out Color color) { var d = Math.Abs(Math.Length(vertex.uv - float2(0.5)) - 0.4) - 0.02; // Under 0 on the ring var edge = Math.Saturate(0.5 - d / this.Fwidth(d)); // 1 inside, 0 outside, a pixel between color = Color(1, 1, 1, edge); } ``` The GPU answers by comparing each pixel with its neighbors, and it only can before any branch or loop: a neighbor in another branch has no value to compare. So the frag works `v` out a first time as it starts, asks there, and the call has that answer wherever it is: in an `if`, in a loop, after `this.Discard()`. You write nothing for it. What it asks of you is a `v` the frag can work out as it starts, as a [`Sample` between smaller images](#doc-game--shaders--textures) does: made of the frag's parameters, `this`, constants, functions of them, textures read, and variables declared with `var` and never assigned again. A `v` made of a variable that changes, or one a loop counts, is an error that says so. - `this.Ddy` goes down the destination's rows, as `this.position` counts them, on every backend and in a target too. - A `v` the frag works out as it starts costs working it out twice, on pixels a branch would have skipped too. ### Cut-outs An edge `this.Discard()` cuts is decided once a pixel, so it's a staircase however many [samples](#doc-game--render-targets--smooth-edges) the target has: leaves, grass, hair and fences alias where the triangles around them are smooth. `this.Cutout(alpha)` says the frag is there where `alpha` is 0.5 or more, in place of the discard: ```csharp frag Leaves(BoxVertex vertex, out Color color, Models models) { color = models.leaves.Sample(vertex.uv); this.Cutout(color.a); // There where its alpha is 0.5 or more } ``` - **Its edge is as smooth as its target's samples.** The engine sharpens the alpha to a pixel by how fast it changes (`(alpha - 0.5) / this.Fwidth(alpha) + 0.5`), and the GPU makes it the share of each pixel's samples the frag covers (alpha to coverage): an edge pixel is part the leaf's color and part what's behind it, as a triangle's edge is. A texture's soft or blurred alpha, or its smaller images far away, still give an edge one pixel wide. - **Into a target of one sample, it's cut at 0.5**, as the discard would: in the window, in a target without `samples`, and in a [shadow map](#doc-game--shaders--a-shadow-map), whose casters with holes can be the same frag as the scene's. - **What it covers, it covers wholly.** A cut-out isn't see-through: its color's own alpha isn't read, and it's drawn as if it were 1. It writes its depth and [stencil](#doc-game--draw-settings--stencil) at the samples it covers and nowhere else, so it needs no sorting and no `Depth.Read`. Under `Blend.Alpha`, which is every draw's at first, a covered sample is replaced; `Blend.Add` and `Blend.Multiply` add and multiply its color whole there. With samples, the target's alpha at an edge pixel's covered samples is how much the frag covered: a scene drawn over an opaque clear stays opaque inside, and close to it along its edges. - **The tint's alpha fades it the same way:** under `Draw.Tint` with an alpha of 0.5, the share is halved, so a cut-out fades out by covering less, not by blending. - **Anywhere in the frag:** in a branch too, and more than once, the last it reaches counting. A pixel whose path says nothing is covered whole. It's a statement of its own, in the frag itself. - **The pixel's color says what's covered, for all of a frag's [outputs](#doc-game--shaders--several-outputs);** the others are finished as any frag's are. `this.Discard()` still discards. `this.Coverage(share)` is the same, with the share as it's given, from 0 to 1, and nothing sharpened: with 4 samples, `this.Coverage(0.5)` covers two of them, which dithers a fade or a soft edge where blending would need sorting. Into a target of one sample, it's there from 0.5. A frag sharpens its own way with `this.Fwidth`, at another cutoff, say: ```csharp frag Hair(Vertex3 vertex, out Color color, Strands strands) { color = strands.color; var alpha = strands.mask.Sample(vertex.uv).a; this.Coverage(Math.Saturate((alpha - 0.3) / this.Fwidth(alpha) + 0.5)); // Cut at 0.3, a pixel wide } ``` A frag says how much it covers one way: `this.Cutout` and `this.Coverage` in one frag is an error. ## What the GPU runs Code for the GPU is ordinary Tide, less what a GPU doesn't have: - **It has** bools, bytes, ints, chars (ints there, their code points), floats, vectors, quaternions, matrices, colors, enums, structs of those and [arrays](#doc-game--shaders--arrays) of them; locals, `if`, `?:`, `switch` on an int, a char or an enum, `for`, `while` and `foreach`, with `break` and `continue`; [lists and grids](#doc-game--shaders--lists-and-arrays) that are fields of what it takes, read by an element, a count or `foreach`; your functions, methods and operators; all of [`Math`](#doc-game--shaders--math), and what builds its types; [`Random`'s rolls](#doc-game--shaders--random-numbers); and sampling a grid, a texture or a target's depth, 16 of them to a draw and 16 [ways of reading them](#doc-game--shaders--textures), anywhere in the code: in a branch, in a loop, in a vert. - **It doesn't have** text, entities, spawning and sending, `Draw`, the GUI, `Devices`, `Debug`, C, tasks, errors, or recursion. It makes and changes no list, map or set. A frag's `this` is its pixel; verts and ordinary functions have no `this`. A `long` has no place there, as a GPU's ints are 32 bits. Each of those is an error where it's written, which says what to do instead. A function a frag calls has to fit too, and the error says which frag reaches it; the same function still runs on the CPU for the code that calls it there. ``` error: string can't go to the GPU: text is the CPU's = note: frag 'Shade' runs on the GPU, and 'Label' with it, as it calls it ``` A loop that never ends hangs the GPU as it hangs a system: nothing stops it for you. ### Math Everything in [`Math`](#doc-language--math) is there unless it makes no sense on a GPU, with the types it works on and what builds them: vectors, quaternions (`Math.Mul`, `Rotate`, `Slerp`, `quaternion.AxisAngle`, `Euler`, `LookRotation`), matrices (`Math.Inverse`, `Determinant`, `float4x4.TRS`, `PerspectiveFov`) and `Math.Hash`. A function gives the same answer in a system, in a view and in a frag, up to how the GPU rounds. - **`Math.Hash` is exact.** It's integers, so a frag gets the number a system gets: a pattern made from a cell's hash is the same on every GPU. ```csharp frag Stars(BoxVertex vertex, out Color color) { // About one cell in thirty has a star, the same cells on every machine int2 cell = int2(Math.Floor(vertex.uv * 64)); color = Math.Hash(cell) % 30 == 0 ? Color.white : Color.black; } ``` - **Noise is the match's cells.** `Math.Perlin`, `Simplex` and `Cellular` take each cell's gradient or feature point from `Math.Hash`, so a frag shades a tile with the noise the match computed for it, up to the GPU's rounding of the floats between. [Noise](#doc-language--math--noise) shows them, drawn by a frag. - **Floats come out as the GPU rounds them.** `Sin`, `Pow`, a quaternion's `Slerp` and a matrix's `Inverse` follow the same formulas as on the CPU, and each GPU rounds them its own way. Big numbers lose the most: the sine of a number in the thousands is wherever that GPU's rounding puts it, so the old trick of a hash made from a sine comes out striped on some machines. `Math.Hash` is what that's for. - **It's as forgiving as on the CPU** (see [Forgiving with bad values](#doc-language--math--forgiving-with-bad-values)): `Normalize` gives zero for a vector with no direction and the identity for a quaternion with none, `Min` and `Max` with one NaN give the other, and `Clamp` and `Saturate` always give a value in range. - **It gives a number wherever the CPU does.** A GPU's own functions leave some answers open, and Tide's don't: a whole power of a number under 0 (`Math.Pow(-2, 2)` is 4), anything to the power of 0 (1), `Math.Atan2(0, 0)` (0), and `Math.SmoothStep` from an edge down to a lower one (it falls where the other way around rises). Where the CPU has no number to give either (the square root of a number under 0, the inverse of a matrix that has none), the GPU gives whatever it gives. What's left out is left out for a reason, and its error says what to write instead. There's one: | Not on the GPU | Why | Instead | |---|---|---| | `Math.Hash` of a `long` | A GPU's ints are 32 bits, so no `long` gets there | `Math.Hash(int2(low, high))` is the same number, for the long's halves: `int(x)` and `int(x >> 32)`, split on the CPU and kept in fields the frag reads | A `Random` of your own isn't there either: its state is 64 bits. [Rolls on the type](#doc-game--shaders--random-numbers) are. **Warning: The GPU's numbers aren't the match's** Every machine's GPU rounds a little differently, so what a frag or a vert works out never reaches the match: they're local code, as views are, and what `Math` makes of floats there is that GPU's own. Only its integers, `Math.Hash`, are the same everywhere. Anything the match depends on is worked out in a system. ### Random numbers [`Random`'s rolls](#doc-language--math--random-numbers) work in a frag and in a vert, with the same calls as anywhere: `Random.NextFloat()`, `Random.NextInt(6)`, `Random.NextFloat2Direction()` and the rest. ```csharp // Film grain over the frame: a blit's frag, which rolls for each pixel frag Grain(Vertex vertex, out Color color, Texture source) { var seen = source.Sample(vertex.uv); var speck = (Random.NextFloat() - 0.5) * 0.08; color = Color(seen.r + speck, seen.g + speck, seen.b + speck); } ``` There's nothing to set up and nothing to pass: a function a frag calls rolls too. - **A pixel rolls its own numbers, and so does a vertex.** Each time a frag runs, it has a generator made for that pixel: from where the pixel is in what's drawn into (the window's own pixels, or a target's), and which instance of its draw it belongs to. A vert's is made from which vertex of the mesh it is, and which instance. Rolls in the same run follow each other, as in a system. - **Every frame is other numbers.** The frame rolls one number with this machine's generator, the one [views roll with](#doc-language--math--where-rolls-work), and every pixel's and vertex's generator is made with it. So grain moves, static flickers, and a sparkle is somewhere else the next frame. - **To hold still, hash.** `Math.Hash(int2(this.position))` is the same number for a pixel every frame, and `Math.Hash` of a cell is the same for the cell wherever it's drawn. [Noise](#doc-language--math--noise) is that, smoothed. - **Two frags roll apart.** Which frag or vert is rolling goes into the generator too, so two that draw over the same pixel don't roll the same there. - **Draws still join.** The frame's number is the same for every draw of the frame, so rolling doesn't split [instances drawn in a row](#doc-game--shaders--many-at-once) into draws of their own. Two draws that don't join each count their instances from the first, so where they cover the same pixel through the same frag, they roll the same there. - **`Random.seed` is the match's seed**, as in a view: 0 with no match. With it a frag draws what the match made from its seed, like `Math.Perlin(cell, Random.seed)`. **Grain and sparks, rolled by the GPU** ([Run example](https://tide-engine.dev/examples/grain/?stats)) ```tide settings { title = "Grain"; } local scene Main { } struct FilmVertex { float2 position; float2 uv; } local singleton Film { List corners; List faces; float grain = 0.35; float sparks = 0.02; bool still; } // Every pixel of the quad: a sky in the site's colors, with grain and sparks rolled for the pixel. frag Develop(FilmVertex vertex, out Color color, Film film) { float3 dark = float3(0.086, 0.086, 0.094); float3 warm = float3(0.98, 0.75, 0.14); mut float3 rgb = Math.Lerp(dark, warm, vertex.uv.y * vertex.uv.y * 0.6); // A roll is another number at each pixel, and at each frame. A hash of the pixel's place is the same // number every frame: it holds still. float rolled = Random.NextFloat(); float hashed = float(Math.Hash(int2(this.position)) % 4096) / 4095; float speck = film.still ? hashed : rolled; rgb += (speck - 0.5) * film.grain; // About one pixel in fifty lights up, another fifty the next frame if (!film.still && Random.NextFloat() < film.sparks) rgb = float3(0.18, 0.83, 0.75); color = Color(rgb.x, rgb.y, rgb.z, 1); } view Show(mut Film film) { if (film.corners.count == 0) { film.corners = [FilmVertex { position = float2(-1, -1.55), uv = float2(0, 0) }, FilmVertex { position = float2(1, -1.55), uv = float2(1, 0) }, FilmVertex { position = float2(1, -0.1), uv = float2(1, 1) }, FilmVertex { position = float2(-1, -0.1), uv = float2(0, 1) }]; film.faces = [0, 1, 2, 0, 2, 3]; } Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0, -0.6), 1.25); Draw.Mesh(film.corners, film.faces, Develop); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Anchor.UpperLeft) { GUILayout.Slider("Grain", film.grain, 0, 1); GUILayout.Slider("Sparks", film.sparks, 0, 0.2); GUILayout.Toggle("Hold still (a hash)", film.still); } } ``` What's different from rolling on the CPU: - **They aren't the CPU's numbers.** A GPU's ints are 32 bits, so its generator is a smaller one than a system's. What each roll gives is the same: `NextInt(6)` is 0 to 5, `NextFloat()` never gives 1, and a range with nothing in it gives its start. - **Order is a statement's.** Rolls on separate lines come in that order. Two rolls in one expression come in whichever order that GPU works the expression out, so where it matters which is which, give each a line. (`NextFloat2()` and the other vectors always roll x first.) A `?:` with a roll in it makes the rolls of both its sides, whichever it picks. - **A `Random` you keep doesn't go there.** A field, a local or a parameter of type `Random` is the CPU's: its state is 64 bits. On the GPU, roll on the type. - **`Filter.Trilinear` can't sample at a place a roll made.** The frag works such a place out once more as it starts, to ask the GPU how fast it changes, and a roll made twice is two numbers. Sample there with `Filter.Bilinear`. - **A frag that rolls carries one more value** from the mesh's corners to its pixels, of the 15 a draw has: which instance. The generator is whole numbers, so `Random.NextInt` gives a pixel the same number on every GPU, for the same frame. Like everything a frag works out, it never reaches the match. ## Many at once Instances of one mesh drawn in a row through the same vert and frag are one draw, each with its own transform and its own components' fields. A view that runs for each entity and draws one mesh draws them all at once: ```csharp view DrawBoxes(Box box, Models models) { Draw.Mesh(models.crate, models.faces, float4x4.Translate(box.pos), Shade); } ``` What's the same for every entity belongs in a singleton, which is sent once. A GPU has room for so much with each vertex: its struct's fields, the transform, and the components' fields the code reads, 4 floats or 4 ints to a slot, 16 slots in all. A draw that reads more is an error at the mesh draw, which counts what it reads. 2D meshes have no transform, so their instances would land on each other: a vert puts each where its component says. ```csharp vert Place(mut Sprite vertex, Body body) { vertex.position += body.position; } ``` ### Instances from a list `Draw.Instanced(vertices, indices, instances)` and `Draw.Instanced(vertices, indices, instances)` draw one mesh for every item in a list, without needing an entity for each. Grass, scenery and visual particles can live in a local list instead. For a 3D mesh, a `List` supplies its transforms: ```csharp Draw.Instanced(models.crate, models.faces, scenery.transforms); Draw.Instanced(models.crate, models.faces, scenery.transforms, models.wood, Filter.Point); Draw.Instanced(models.crate, models.faces, scenery.transforms, models.wood, Filter.Point, Wrap.Repeat); Draw.Instanced(models.crate, models.faces, scenery.transforms, Wave, Shade); ``` For data of your own, use a `List` of an ordinary struct. A vert or frag takes that struct after its vertex (and the frag's color), and receives the current list item. Either shader can take it, or both can: ```csharp struct Blade { float4x4 transform = float4x4.identity; Color tint = Color.green; float bend; } local singleton Foliage { List blades; } vert Bend(mut BoxVertex vertex, Blade blade) { vertex.position.x += vertex.position.y * blade.bend; } frag Grass(BoxVertex vertex, out Color color, Blade blade, Sun sun) { color = blade.tint * Math.Max(Math.Dot(vertex.normal, -sun.direction), 0.1); color.a = blade.tint.a; } view GrassField(Foliage foliage, Models models) { Draw.Instanced(models.blade, models.faces, foliage.blades, Bend, Grass); } ``` - A 3D instance struct's `float4x4 transform` places the mesh and is available as `Instance.transform`. Without that field, the engine uses identity. Set its default to `float4x4.identity` when it has one: an uninitialized matrix is zero. - For a 2D mesh, the instance list holds an ordinary struct and a vert places its vertices, as `Place` does above. A field named `transform` is ordinary data there; the engine doesn't apply it, and `Instance.transform` remains identity. - Components still come from the calling view's entity, and singletons are shared by the draw. The list items don't have to be entities and don't add any. - Only the instance fields the shaders read are sent, beside the 3D transform. Unread fields take no GPU space. The fields that are read follow the same GPU type and attribute limits as components. - Textures, filters, wraps, verts and frags go after the instance list, in the same order as `Mesh`: `Draw.Instanced(vertices, indices, instances[, texture[, filter[, wrap]]...][, vert][, frag])`. A frag can sample fields of its parameters, or receive the draw's explicit textures through its read-only `Texture` parameters, in order (see [Several textures](#doc-game--shaders--several-textures)). - An empty instance list draws nothing. Items draw in list order, in one instanced draw; adjacent compatible calls can join the same run. Every mote below is an item of a list, and none is an entity. A vert places the quad's four corners for each, with that mote's own center, size and phase, and a frag makes a soft dot of it in its tint. The slider changes how many the list holds: they're one draw either way. **A list of motes, in one draw** ([Run example](https://tide-engine.dev/examples/instances/?stats)) ```tide settings { title = "Instances"; } local scene Main { } struct Corner { float2 position; float2 uv; } // One of these for each copy of the mesh. No entities are involved. struct Mote { float2 center; float size; float phase; Color tint; } local singleton Swarm { List quad; List faces; List motes; Random random; int count = 600; float clock; } // The GPU runs this for each corner of each mote, with that mote's own fields. vert Place(mut Corner corner, Mote mote, Swarm swarm) { float angle = swarm.clock + mote.phase; float2 drift = float2(Math.Cos(angle), Math.Sin(angle * 1.7)) * 0.25; corner.position = mote.center + drift + corner.position * mote.size; } // And this for each pixel: a soft dot, from how far the pixel is from the middle. frag Glow(Corner corner, out Color color, Mote mote) { float away = Math.Length(corner.uv - 0.5) * 2; color = mote.tint; color.a = Math.Saturate(1 - away) * Math.Saturate(1 - away); } view Show(mut Swarm swarm) { if (swarm.quad.count == 0) { swarm.quad = [Corner { position = float2(-1, -1), uv = float2(0, 0) }, Corner { position = float2(1, -1), uv = float2(1, 0) }, Corner { position = float2(1, 1), uv = float2(1, 1) }, Corner { position = float2(-1, 1), uv = float2(0, 1) }]; swarm.faces = [0, 1, 2, 0, 2, 3]; } // The list is ordinary state: add to it and the next frame draws more. while (swarm.motes.count < swarm.count) { swarm.motes.Add(Mote { center = swarm.random.NextFloat2(float2(-1.8, -1.6), float2(1.8, 1.9)), size = swarm.random.NextFloat(0.05, 0.16), phase = swarm.random.NextFloat(Math.TAU), tint = Color(1, swarm.random.NextFloat(0.45, 0.85), swarm.random.NextFloat(0.1, 0.4)) }); } while (swarm.motes.count > swarm.count) swarm.motes.RemoveAt(swarm.motes.count - 1); swarm.clock += Math.Min(Frame.dt, 0.05); if (swarm.clock > Math.TAU * 10) swarm.clock -= Math.TAU * 10; Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetCamera(float2(0), 2.2); // One draw, however many. Its colors add to what's there, as light does. Draw.Blend(Blend.Add) { Draw.Instanced(swarm.quad, swarm.faces, swarm.motes, Place, Glow); } Draw.SetScreen(); Draw.Text($"{swarm.motes.count} motes, in one draw", float2(16, 14), 16, Color.white); GUI.SetTheme(GUITheme { radius = 6 }); GUI.IntSlider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Motes", swarm.count, 1, 5000); } ``` A struct parameter that's meant as an instance's is supplied by `Draw.Instanced` and a list of that type. With `Mesh`, or a list of another type, the draw is an error, unless it gives a struct of that type as [its values](#doc-game--shaders--values-for-one-draw), which every instance then shares. ## Compute A `compute` declaration is code the GPU runs that isn't tied to a draw: a kernel. `GPU.Run` runs it over a count or a size, from a view or a function it calls, and what it writes goes to GPU lists, which draws after it read. Culling, scattering, simulating particles and counting all fit. ```csharp struct Blade { float3 root; float height; } local singleton Meadow { GPUList blades; // Every blade, filled once GPUList shown; // This frame's, in order float reach; } [Group(64)] compute CullBlades(Meadow meadow, Eye eye) { Blade blade = meadow.blades[this.index]; if (Math.Distance(blade.root, eye.position) < meadow.reach) meadow.shown.Add(blade); } view DrawMeadow(Meadow meadow, Models models) { meadow.shown.Clear(); // In frame order: before the run adds to it GPU.Run(CullBlades, meadow.blades); // Once for each blade the GPU has Draw.Instanced(models.blade, models.faces, meadow.shown, Sway, Grass); // As many as it kept } ``` A kernel takes what a frag does: components of the entity the calling view runs for, singletons, and one struct of values, which `GPU.Run` gives after what it runs over. It returns nothing, changes nothing it takes, and writes GPU lists. What a frag's code can do, a kernel's can: math, noise, lists, grids, maps, functions, `Sample` at a texture's own level and `SampleLevel` at the level it picks (see [Reading images](#doc-game--shaders--reading-images)). ### Which invocation A kernel's `this` is the invocation it runs as: | | | | --- | --- | | `this.index` | Its place in the whole run, an `int`: `x + y * count.x + z * count.x * count.y` | | `this.at` | Where it is in the run's size, an `int3` | | `this.local` | Where it is in its group, an `int3` | | `this.group` | Which group it's in, an `int3` | | `this.count` | The run's size, an `int3` | `GPU.Run(kernel, over[, values])` runs it over: - an `int`, `int2` or `int3`: that many invocations along each axis; - a `List`: its count; - a `GPUList`: its count on the GPU, as the GPU has it when the run happens. Nothing is read back, so kernels chain: one fills a list and the next runs over it. Invocations run in groups, 64 when the kernel says nothing: `[Group(64)]`, `[Group(8, 8)]` or `[Group(4, 4, 4)]` before it says how many along each axis, at most 256 in all and 64 along z, what every GPU runs. Invocations past the run's size don't run its body: a kernel over 200 needs no `if (this.index >= 200) return;`. ### GPU lists A `GPUList` is a list that lives on the GPU. It's this machine's, as a `RenderTarget` is, never the match's: a local field or a local singleton keeps it, and local code makes it with its capacity, the most elements it holds. ```csharp view Setup(mut Meadow meadow) { if (meadow.blades.capacity == 0) { meadow.blades = GPUList(100000); meadow.shown = GPUList(100000); } } ``` - Its elements are GPU values: numbers, vectors, colors, quaternions, float matrices, bools, enums, and fixed arrays and structs of those. - Its contents and count stay from frame to frame until something writes them. Copies share the list, and writing it needs no `mut`: it's a handle. - Kernels, frags and verts read `list[i]`, `list.count`, `list.capacity` and `foreach`. Past the count, an element is zeros. - Kernels write `list[i] = value` (past the capacity it goes nowhere, and the count stays as it was), `list.Add(value)` and, on a `GPUList`, atomics. - Local code sends a list's elements with `list.Set(items)`, sets the count with `list.Clear()` and `list.SetCount(n)`, in frame order with the draws and runs around them; `list.Resize(capacity)` makes it empty at another capacity, and `list.Dispose()` lets it go. - `list.contentRevision` changes when the list was made again empty: a lost device, a `Resize`, or a hot reload that changed its element. A game that filled it once fills it again then. - A frag, vert or kernel can name up to 64 GPU lists, and a kernel can `Add` to as many as it names. Lists live side by side in the GPU's memory; one can never read or change another's elements. Functions the GPU runs take a GPU list as a parameter, `GPUList`, as they take a `List`: the call names one by its field, or passes on its own parameter. What a kernel can do to a list, a function it calls can do to the one it's given, and the kernel then does it to the list it passed: write elements, `Add` and atomics. ```csharp float Tallest(GPUList blades) { mut float most = 0.0; foreach (var blade in blades) most = Math.Max(most, blade.height); return most; } void Keep(GPUList into, Blade blade) { into.Add(blade); } [Group(64)] compute CullBlades(Meadow meadow) { Blade blade = meadow.blades[this.index]; if (blade.height * 2 > Tallest(meadow.blades)) Keep(meadow.shown, blade); } ``` - A GPU list isn't a value there: it's named where it's used, so a local can't keep one, nor can a function return one or `?:` pick between two. - A function that writes, adds to or uses atomics on a GPU list is a kernel's: a frag or a vert calling it is an error, as the CPU calling one is. The CPU can't read a GPU list as it draws: `count` there is an error. Local async code reads one back, a copy, once the frame drawn next is done on the GPU: ```csharp local singleton Census { int shown; } async void Count(Meadow meadow, mut Census census) { if (await meadow.shown.ReadCount() is int count) census.shown = count; } ``` `await list.Read()` gives a `List` of its elements, and `await list.ReadCount()` its count, each failing with `IOError` where the device was lost before the read was done. A run without a window (`--capture`, `--frames`, `--script`) has each read done at the next frame's start, so its frames repeat exactly. ### Adding in order `list.Add(value)` in a kernel keeps invocation order: what invocation 3 adds comes before what invocation 7 adds, whatever order the GPU ran them in, and the count goes up by how many were added. Captures stay the same from run to run. Past the capacity, nothing more is added. - An invocation adds to a list once at the most, on any path, and never in a loop: "'CullBlades' can add to 'shown' twice". To add several, run over more invocations, or count places with an atomic and write them by index. - A call of a function that adds to a list counts as an `Add` of it: once on a path, not in a loop, and a statement of its own. - A kernel that adds has a group of one axis, `[Group(64)]`: this.index's order is then the groups' order, even over a size of two or three axes. ### Atomics On a `GPUList`, `AtomicAdd(i, value)`, `AtomicSub`, `AtomicMin`, `AtomicMax`, `AtomicAnd`, `AtomicOr`, `AtomicXor` and `AtomicExchange` change element `i` at once for every invocation, and give what it was; `AtomicCompareExchange(i, compare, value)` puts `value` there where it's `compare`. Only ints: no GPU has portable float atomics. What an atomic gives depends on which invocation came first, so results that depend on it can differ from one run to the next (GPU results are visual only). ```csharp compute Histogram(Meadow meadow, Bins bins) { int bin = int(meadow.blades[this.index].height * 10); bins.counts.AtomicAdd(bin, 1); } ``` ### Within a group `shared int[64] sums;` at the top of a kernel's body is a local its whole group shares: one copy a group, zeroed as the group starts, any GPU value or fixed array of them, 16 KiB at most. `GPU.Barrier()` waits until every invocation of the group reaches it, with what they wrote to shared memory and to GPU lists seen. ```csharp [Group(64)] compute Sum(Values values) { shared float[64] partial; int i = this.local.x; partial[i] = values.items[this.index]; GPU.Barrier(); for (var step = 32; step > 0; step /= 2) { if (i < step) partial[i] += partial[i + step]; GPU.Barrier(); } if (i == 0) values.sums[this.group.x] = partial[0]; } ``` - Every invocation reaches a barrier: it's in no `if`, `switch` or `while`, in `for` loops only from a constant to a constant that nothing leaves early, and after no `return`. A kernel with a barrier runs its body for every invocation of its groups, those past the run's size too, so it checks `this.index` itself. - Atomics work on a `shared int[N]`'s elements too: `seen.AtomicAdd(0, 1)`. - One place of shared memory written by every invocation of a group, each with its own value, is a race: some invocation's value is left, and which isn't said. To have one known value, have one invocation write it, `if (this.local.x == 0) ...`, and the others read it after a barrier. It runs everywhere, Unity's Direct3D 11 too. ### Drawing what a kernel made `Draw.Instanced(vertices, indices, list, vert, frag)` over a GPU list draws as many instances as the list has on the GPU, each read there: one indirect draw, with nothing read back. Its element is the instance struct, as a list's is, its `float4x4 transform` too where it has one. No culling or level picking happens on the CPU, which has no instances to test: the kernel that filled the list does that. A game draws one list a level, each filled by the kernel that picks them. Inside `Draw.Transform`, each instance's transform goes through it, as a `List`'s instances' do. An instance whose own transform mirrors its mesh is drawn with its front the other way round, as a list's is: such a draw is two runs, one for the instances that mirror and one for those that don't, unless it's inside `Draw.Cull(Cull.None)`. A mesh's vertices and indices can be a kernel's too: `Draw.Mesh` and `Draw.Instanced` take a `GPUList` of the vertex struct where the vertices go, and a `GPUList` or a `List` where the indices go, in 2D and 3D, and so does a target's `Mesh`. Each vertex is read on the GPU by its index, zeros past the list's count, and indices on the GPU draw as many triangles as that list's count has there, with nothing read back. ```csharp struct Dot { float2 position; Color color; } local singleton Sparks { GPUList corners; } [Group(64)] compute Spark(Sparks sparks, Burst burst) // Burst: a local singleton of the game's { float2 at = burst.center + float2(float(this.index % 16), float(this.index / 16)) * burst.spacing; int first = this.index * 4; sparks.corners[first] = Dot { position = at + float2(-1, -1), color = burst.color }; sparks.corners[first + 1] = Dot { position = at + float2(1, -1), color = burst.color }; sparks.corners[first + 2] = Dot { position = at + float2(1, 1), color = burst.color }; sparks.corners[first + 3] = Dot { position = at + float2(-1, 1), color = burst.color }; } view DrawSparks(Sparks sparks, Burst burst) { sparks.corners.SetCount(burst.count * 4); GPU.Run(Spark, burst.count); Draw.Mesh(sparks.corners, burst.quads); // burst.quads: a List of 0, 1, 2, 0, 2, 3, 4, 5, 6, ... } ``` A mesh whose indices are a GPU list's has its vertices in one too: they're picked on the GPU. Levels of detail (`lod:`) are made of the CPU's vertices, so they're not for a mesh of a GPU list's. Instances of such a mesh from a `List` are frustum culled by the bounds [`Draw.Bounds`](#doc-game--draw-settings) gives, a box around every vertex the kernel can make: the CPU has none of its own for them, and without them, every instance is drawn. ### Reading images A kernel reads the images a frag reads, through the same fields: a `Texture`, a `DepthTexture`, a `Cubemap`, a `TextureArray` and a `DepthTextureArray`, a `Texture3D`, and the typed `[Raw(T)]` ones. A kernel has no neighbouring pixels to tell how small an image is drawn, so its `Sample` reads the image's own pixels; `SampleLevel` reads the level the kernel picks: ```csharp local singleton Glow { RenderTarget scene; Texture image; // scene.color GPUList average; // What the whole frame comes to } [Group(1)] compute Average(Glow glow) { glow.average[0] = glow.image.SampleLevel(float2(0.5), 10, Filter.Trilinear); // The frame's smallest image } ``` - **The smaller images are made of what was last drawn into the image,** before the run, as they are for a draw that reads them: a target's colors, a multisampled target's too, an array's layers and a cube's faces. A target drawn into again after the run, or written by a kernel, has them made again for the next read. - **The `SampleLevel` decides,** as in a frag: one that names no filter reads between levels, whatever filter the `Texture` carries (a target's color carries `Filter.Bilinear`), typed reads too; one that names `Filter.Point` or `Filter.Bilinear`, and one at a level written `0`, read the image's own pixels. - **What it isn't given reads as in a frag:** a depth the far limit (and `Compare` gives 1), a cube black, an array and a texture white, and a typed image zeros. So does an image that was disposed, an image a target hasn't got, and the colors of an image of depth alone. A `TextureArray` or a target made with `Format.Depth` and read as colors is an error where the compiler can see it: read its depth through a `DepthTextureArray` or `DepthTexture` field instead. ### Writing images A kernel writes a render target's image or a [`Texture3D`](#doc-game--meshes-and-textures--volumes) by cell: ```csharp local singleton Fog { Texture3D density; } [Group(4, 4, 4)] compute FillFog(Fog fog) { float height = float(this.at.y) / float(this.count.y); fog.density[this.at] = Color(height, 0, 0, 1); } view UpdateFog(mut Fog fog) { if (fog.density.contentRevision == 0) fog.density = Texture3D(int3(32), Format.Rgba16f); GPU.Run(FillFog, fog.density.size); } ``` For a target, write `target.color[at]` or `target.colors[i][at]` with an `int2` place, or put that image in a `Texture` field. No `mut` is needed to write through either handle. An out-of-range store does nothing; tidec checks the coordinates. A Color is written as it is, with its alpha: Tide handles premultiplication internally, as it does for a frag. A kernel that writes an image cannot sample or load that same image. Write into a second image, then alternate them between runs. Rgba8, Rgba16f, R32f, Rgba32f and R32i are writable. R8, Rg8, R16f and Rg16f are not portable storage formats; use R32f for a scalar written by a kernel. Tidec must know the destination's format from its constructor assignments; it diagnoses unknown or ambiguous formats and formats that core WebGPU cannot store into. A kernel writes at most four images; split larger work into separate runs. Written targets use a single sample: make the destination without MSAA, then draw its result into a multisampled target. ### Order in a frame A frame's GPU work happens as if in the order it was recorded: a draw after a run sees what it wrote, and one before it doesn't, as do runs after runs, and `Set`, `Clear` and `SetCount` among them. A run that no draw before it depends on is done before them, so it costs the draws around it nothing: write runs where they read best. ### Where kernels run Kernels run everywhere Tide draws: Vulkan (desktop and Android), WebGPU, and Unity's compute-capable graphics APIs. Compute is guaranteed, so a game never needs a path without it. [`tide shaders`](#doc-game--shaders--looking-at-what-s-generated) prints each kernel's WGSL. ## Looking at what's generated `tide shaders` prints each shader Tide writes for the game, as WGSL (which Vulkan's SPIR-V and Unity's HLSL are translated from): one for each combination of vertex struct, instance data, vert and frag a mesh draw uses, and each kernel's WGSL. [Shipping builds](#doc-tools--cli--run-and-build) shorten identifiers derived from your function, type, field, parameter and local names. Shader entry points and renderer bindings retain their names; expressions and layouts are unchanged. The private `game.names` build map records the shortened identifiers by stage. With a custom compiler pipeline, `tidec --shaders --strip-names` shows the shortened form; `--spirv` and `--hlsl` also accept `--strip-names`. ## Choosing a mip level `source.SampleLevel(uv, level)` reads a level you choose, including from a vert, kernel or GPU helper. Level 0 is the original image, level 1 halves its dimensions, and 1.5 blends levels 1 and 2. Levels clamp to the available images. A SampleLevel that names no filter reads between levels (`Filter.Trilinear`), on a color texture, a cube, an array and a number image alike; naming `Filter.Point` or `Filter.Bilinear` reads the original image. A level written as `0` (or less) reads the original image blended, as `Filter.Bilinear` does, which is what reading between levels gives there: so `frame.SampleLevel(uv, 0)` of a target drawn every frame costs no chain of smaller images, where a level the game works out as it runs has the chain made after each frame's drawing. A cubemap takes a direction: `sky.SampleLevel(direction, roughness * 5)` for a blurred reflection. An array takes its layer first: `images.SampleLevel(uv, layer, 2)`. Texture3D has no mipmaps; use its Sample method. Number images in R8, Rg8, R16f, Rg16f and Rgba16f take SampleLevel and SampleGrad as colors do; R32f, Rgba32f and R32i have no mipmaps, and read with `Sample(uv)` (an R32f or Rgba32f one blended with `Filter.Bilinear`, or with `SampleLevel(uv, 0)`). Drawing into a selected mip level is not available. ## Writing a pixel's depth In a frag, `this.WriteDepth(value);` replaces depth with a forward value from 0 near to 1 far. It can write back a DepthTexture.Sample result. Values clamp; NaN becomes zero. A path with no write retains triangle depth; the last write wins. Helpers return a value for the frag to write. Equal and Only use that value, so a prepass and its lit pass should compute the same depth. These draws skip automatic geometry-bound culling, and depth tests may run after the frag. Explicit Bounds also leave occlusion testing disabled for a depth-writing frag. ## Depth bias `Draw.DepthBias(-8, -1) { Draw.Mesh(vertices, indices, transform); }` pulls a coplanar 3D draw nearer. `Draw.SetDepthBias(8, 1);` pushes subsequent 3D draws away; `Draw.SetDepthBias();` clears it. Targets have both forms and keep their own setting. Blocks restore what they found; 2D draws are unaffected. The constant counts GPU precision steps (truncated to a whole number), and slope scales pixel-depth slope. A floating depth image's step follows its depth precision, rather than a fixed fraction of the range. Constants outside ±65536, slopes outside ±16 and nonfinite values become zero. Start with small factors. A biased draw is never [occlusion tested](#doc-game--3d--occlusion-culling): it's drawn whole. How the factors count is provisional. --- Source: https://tide-engine.dev/game/audio.md Import WAV, Ogg Vorbis, MP3 and FLAC audio in Tide, control spatial sound and buses, and create audio filters while keeping sound local to each machine. # Audio Sound is presentation, like drawing: it's this machine's, and nothing of it is in the match. A view says what should be sounding as it says what should be drawn, and a local handler plays a sound when the match sends an event. Nothing in the simulation hears any of it, so a match is the same on a machine with its speakers off. **Info** What's here: clips as assets (WAV, Ogg Vorbis, MP3 and FLAC), `Audio.Play`, `Sound` fields and the listener, buses, `audio` declarations that filter and make sound, the device on every platform, and the microphone. See the [spec](https://tide-engine.dev/spec.md#audio) for the whole design and what's still open. ## Clips A sound is a file the game is built with, declared as an [asset](#doc-game--assets): ```csharp asset Clip shot = "sfx/shot.wav"; asset Clip music = "music/theme.ogg"; asset List hits = "sfx/hit_*.wav"; asset Map voices = "voice/*.ogg"; ``` A `Clip` accepts these source formats, with one or two channels and their source sample rate preserved: | Source | Supported variants | Packed representation | | --- | --- | --- | | WAV | Little-endian RIFF/WAVE, integer PCM 8/16/24/32-bit or IEEE float 32/64-bit | Original WAV | | Ogg Vorbis | Vorbis I, mono/stereo | Original compressed Ogg Vorbis | | MP3 | MPEG Layer III, CBR or VBR | Float32 PCM WAV, converted at build time | | FLAC | Native FLAC, mono/stereo, with a declared STREAMINFO sample count | Float32 PCM WAV, converted at build time | The build identifies the file from its contents and reports unsupported formats, codecs, channels and damaged data at the asset's path. Ogg is a container: an `.ogg` holding Opus is not Vorbis. AIFF, AAC/M4A, Opus, ADPCM WAV and surround audio aren't imported yet; export PCM WAV, FLAC or Ogg Vorbis instead. MP3 and FLAC conversion adds no decoder to the game, but PCM takes more pack space and memory than compressed audio. Use Ogg Vorbis for long music or ambience that should stay compressed. MP3/FLAC imports are bounded to 128 MiB of source data, 256 MiB of decoded samples and 30 minutes of audio. As the game loads its pack, clips are prepared on the pool's threads: WAV and converted MP3/FLAC are fully decoded, as is Vorbis up to ten seconds long. A longer Vorbis clip is kept compressed and decoded as it plays, a block at a time on the audio thread. Playing, looping and pitch use the same API for every imported source format. Runtime playback uses Tide's WAV and Vorbis decoders; MP3/FLAC decoders are build tools only. A `Clip` is a value: keep it in a local field, pass it to a function, pick one from the glob's list or map. It names the declaration's file, so under `tide run` a saved file plays through every copy the game kept. The match can't use one: a `Clip` is this machine's, as a `Texture` is. ## Playing a sound `Audio.Play` starts a clip once, from its start. The mixer owns it from then on: nothing comes back, and nothing stops it but its end. ```csharp local event(Hit hit) HitSound(Body body) { Audio.Play(shot, body.position); } view Steps(Walker walker, mut Feet feet) { if (walker.stepped != feet.lastStep) { feet.lastStep = walker.stepped; Audio.Play(hits[feet.lastStep % hits.count], walker.position, 0.6); } } ``` - `Audio.Play(clip[, volume[, pitch]])` plays it plain stereo, from nowhere in particular. `volume` 1 is the clip as it is; `pitch` 1 is its own speed, 2 an octave up. - `Audio.Play(clip, position[, volume[, pitch]])` places it in the world, as a `float2` or a `float3`: it's heard from the side it's on against the listener, and quieter with its distance. Until a view sets a listener, the listener is at the origin, facing +z, with +x at its right, and a sound is at its volume within 1 unit and silent past 50. Who can play: views, local handlers and the functions they call. A system or an event handler of the match can't (the match runs the same on every machine), nor the input's `Sample`, a task, a method or code the GPU runs. A function that plays is local code's to call, as one that reads `Frame.dt` is. **A local handler is the right place for a one-shot**: it hears the match's event once, even when a correction makes a client run the tick again, so the sound plays once too. A sound the client only guessed at plays as soon as it's guessed; `local event(verified Hit hit)` waits until the server confirmed it. ## Sounds that go on A one-shot can't be changed once it started. A sound a game keeps track of, to change its pitch, its volume or where it is as it plays, is a `Sound` in a local field: ```csharp component Engine { float throttle; local Sound hum; // The match's entity, with a sound of this machine's } view Engines(Body body, mut Engine engine) { engine.hum.clip = engineLoop; engine.hum.spatial = true; engine.hum.position = body.position; engine.hum.loop = true; engine.hum.pitch = 0.8 + engine.throttle * 0.6; engine.hum.playing = true; } ``` A `Sound` has `clip`, `position` and `spatial` (placed in the world, or plain stereo), `volume` and `pitch` (1 each unless set), `loop` and `playing`. The frame reads every `Sound` in local state once the views ran, and names each that's `playing` to the mixer: the mixer keeps a voice for it from frame to frame, by the field it's in and the entity it's on, and moves the voice to whatever the fields say. A sound stops when `playing` goes false, or when its field goes (a destroyed entity's, say): the mixer fades the voice out over a few milliseconds. Stop it in one frame and start it in a later frame to play the clip over; assigning another clip starts it over too. Setting `playing` false and true within one view leaves it playing, because the mixer receives the final value. A looping sound goes on; one that doesn't loop plays to its end and stays silent until it's started over. Changes to the volume and the pan ramp over a few milliseconds, so a value written every frame doesn't click. A `Sound` lives in local singletons, local components, a match component's `local` fields and structs inside those. The match can't hold one, nor can a list. ### The listener Spatial sounds are heard from the listener, which a view sets each frame it wants it elsewhere than the origin: ```csharp view Ears(Camera camera) { Audio.SetListener(camera.position, camera.rotation); Audio.SetFalloff(2, 60); } ``` `Audio.SetListener(position, rotation)` says where it is and which way it faces (its right is +x turned by `rotation`); `Audio.SetListener(center)` with a `float2` is the 2D form, facing +z. `Audio.SetFalloff(near, far)` says how a sound's volume falls with its distance: at its volume within `near`, silent past `far`, and as `near / distance` between, scaled to reach 0 at `far`. Like a draw setting, each holds from where it's set to the end of the frame, and every frame starts from the defaults: the origin, facing +z, and 1 and 50. ## Buses Sounds go through buses, which a game declares as an enum marked `[Bus]`, its first member the master every bus goes through: ```csharp [Bus] enum Bus { Master, Music, Sfx, } view Levels(Settings settings, mut Music music) { music.track.bus = Bus.Music; Audio.SetVolume(Bus.Music, settings.music); Audio.SetVolume(Bus.Sfx, settings.effects); } ``` A `Sound`'s `bus` is one of them (the master unless set). `Audio.SetVolume(bus, volume)` sets a bus's volume for the current frame; every frame starts with every bus at 1, so apply saved volume settings each frame. A game has 16 buses at most. Without a `[Bus]` enum, bus numbers from 0 to 15 are available and 0 is the master. ## Effects An `audio` declaration is code the audio thread runs once a block of 256 stereo frames, on a sound's samples before they're mixed, or on a bus's mix. It's what Unity's `OnAudioFilterRead` lets a game do, and a synth too: ```csharp struct Knobs { float cutoff; } struct LowpassState { float left; float right; } audio Lowpass(mut Samples samples, mut LowpassState state, Knobs knobs) { for (var i = 0; i < samples.values.count; i += 2) { state.left += (samples.values[i] - state.left) * knobs.cutoff; state.right += (samples.values[i + 1] - state.right) * knobs.cutoff; samples.values[i] = state.left; samples.values[i + 1] = state.right; } } view Engines(mut Engine engine, Throttle throttle) { engine.hum.effect = Lowpass(Knobs { cutoff = 0.2 + throttle.amount * 0.5 }); } ``` - **The block** is its first parameter, `mut Samples samples`: `samples.values` is 512 floats, interleaved left then right, 256 frames at 48 kHz, and `samples.values.count` says so. Write what should play into it. - **Its state** is a `mut` struct of plain fields, one at most, the voice's own, zeros when the effect starts and kept from block to block. Nothing else reads it. - **Its knobs** are a read-only struct of plain fields, one at most: a copy of what the frame last gave, `Lowpass(Knobs { ... })`. The value that call makes is an `Effect`, which a `Sound`'s `effect` takes, and a bus through `Audio.SetEffect(Bus.Master, Compress(knobs))`. An `audio` declaration with no knobs is `Square()`. - **A source** is an effect on a `Sound` with no clip: its block starts as silence, and what it leaves is what plays. That's a synth. - **It runs between nothing**: no world, no frame, no files, no C, no text, lists, maps, sets or grids, and no sounds or drawing of its own, itself or through the functions it calls. `Math` is all there, and ordinary functions of plain values are fine. The compiler says what's not. - **It rolls**, for noise: `samples.values[i] = Random.NextFloat(-1, 1);`. Each voice has a [sequence of its own](#doc-language--math--where-rolls-work), which goes on from block to block. An effect's state starts over when a `Sound` is given another effect. Changing the knobs each frame is the way to move a filter: the state carries on. Keep a filter's left and right history separate, as above: consecutive array elements are different channels, not consecutive moments in one channel. ### Making a sound A source uses the same declaration shape as a filter. Keep its phase in the state, advance it once per stereo frame, and write both channels. The frequency is a knob: changing it keeps the phase, while stopping the `Sound` and starting it again resets the state. Click or tap **Play sound** below, then change the frequency or volume. It starts silent and uses a quiet volume. The graph previews ten milliseconds of the generated wave; the view calculates it separately, because audio state belongs to the audio thread. On the web, the button press also lets the browser start audio. **A small synthesizer** ([Run example](https://tide-engine.dev/examples/audio/?stats)) ```tide settings { title = "A small synthesizer"; } local scene Main { } struct Oscillator { float phase; } struct Note { float hertz; } // A source has no clip. Fill each stereo frame with the same sine wave. audio Sine(mut Samples samples, mut Oscillator oscillator, Note note) { for (var i = 0; i < samples.values.count; i += 2) { var value = Math.Sin(oscillator.phase); samples.values[i] = value; samples.values[i + 1] = value; oscillator.phase += note.hertz * (2 * Math.PI / 48000); if (oscillator.phase >= 2 * Math.PI) oscillator.phase -= 2 * Math.PI; } } local singleton Synth { Sound tone; float hertz = 220; float volume = 0.08; } view Instrument(mut Synth synth) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); GUI.SetTheme(GUITheme { radius = 6 }); GUILayout.Area(Rect(16, 16, Screen.width - 32, 170)) { GUILayout.Label($"Sine wave: {int(synth.hertz)} Hz"); GUILayout.Slider("Frequency", synth.hertz, 110, 880); GUILayout.Slider("Volume", synth.volume, 0, 0.15); if (GUILayout.Button(synth.tone.playing ? "Stop sound" : "Play sound")) synth.tone.playing = !synth.tone.playing; } // New knobs keep the oscillator's phase; stopping starts it over. synth.tone.effect = Sine(Note { hertz = synth.hertz }); synth.tone.volume = synth.volume; var width = Screen.width - 40; var center = Screen.height * 0.7; var amplitude = synth.volume / 0.15 * 48; var color = synth.tone.playing ? Color(0.98, 0.75, 0.14) : Color(0.64, 0.64, 0.68); Draw.Line(float2(20, center), float2(20 + width, center), Color(0.24, 0.25, 0.27)); for (var i = 0; i < 160; i++) { var a = i / 160.0; var b = (i + 1) / 160.0; // A preview of ten milliseconds, calculated without reading audio state. Draw.Line(float2(20 + width * a, center - Math.Sin(a * 0.01 * synth.hertz * 2 * Math.PI) * amplitude), float2(20 + width * b, center - Math.Sin(b * 0.01 * synth.hertz * 2 * Math.PI) * amplitude), 2, color); } Draw.Text("Waveform preview: 10 ms", float2(Screen.width * 0.5, center + 64), 13, Color(0.64, 0.64, 0.68), Anchor.MiddleCenter); } ``` ### Echoes and reverbs An echo or a reverb remembers what played a while ago, in a delay line: an array of samples. An ordinary array holds at most 4,096 elements, about 43 ms of stereo at 48 kHz, so in an `audio` declaration's state it can be far longer, as long as the state has bytes: ```csharp struct Tail { int at; float[96000] line; // A second of stereo } struct Delay { int frames; float wet; } audio Echo(mut Samples samples, mut Tail tail, Delay delay) { var frames = Math.Clamp(delay.frames, 1, 48000); for (var i = 0; i < samples.values.count; i += 2) { var from = (tail.at + 48000 - frames) % 48000; var left = samples.values[i]; var right = samples.values[i + 1]; samples.values[i] += tail.line[2 * from] * delay.wet; samples.values[i + 1] += tail.line[2 * from + 1] * delay.wet; tail.line[2 * tail.at] = left; tail.line[2 * tail.at + 1] = right; tail.at = (tail.at + 1) % 48000; } } view Caves(mut Cave cave) { cave.drip.effect = Echo(Delay { frames = 14400, wet = 0.4 }); } ``` This example clamps the delay to one through 48,000 stereo frames, up to one second. It reads the delayed samples before replacing them, so a full second's delay works when the read and write positions coincide. The mixer makes that memory for a sound while it plays through the effect, so only the sounds that echo pay for it, 384 KB each here. When the sound stops, its line goes with it, and the next time it plays the line starts from silence. A bus's is the same: `Audio.SetEffect(Bus.Music, Echo(delay))`, said each frame, keeps one line for everything on the bus, which is how a reverb is usually used. A struct with such an array is never copied, as a copy would be hundreds of kilobytes on the audio thread. It's only ever an `audio` declaration's state, and code reads and writes it where it is: - An element at a time, `tail.line[i]`, with `tail.line.count` for how many there are. A `foreach` goes through a copy of its array, so a long one is gone through by index. - Passed on to a function as a `mut` parameter: `void Push(mut Tail tail, float sample)`. - No local holds one (`var copy = tail;`), no function takes one by value or returns one, and it has no methods. The compiler says which of these a line is. ### How big A state struct is 1,048,576 bytes at the most, a megabyte: 2.7 seconds of stereo. A knobs struct is 256, which is what an `Effect` carries. A `float` or an `int` is 4 bytes, a `long` 8, a `bool` or a `byte` 1, and an array as many as its elements. A struct that's bigger is a compile error at the parameter: ``` error: an audio declaration's state is 1048576 bytes at the most, and 'Tail' is 1048580 ``` Make the struct smaller: a shorter array, or fewer fields. Code that rolls keeps what it rolls with after its state, so its state is 8 bytes less at the most. ## Hearing a run with no window A [run with no window](#doc-tools--cli--without-a-window) mixes what the game plays, a 60th of a second a frame, and writes it out: ``` tide run --frames 300 --capture-audio run.wav --stats ``` `--capture-audio` writes the whole run as a WAV of 16-bit stereo at 48 kHz, and a script's `capture-audio hit.wav` line writes what played since the last such line. The mixer is the engine's own arithmetic, so a run plays the same bytes on every machine. ## The device A game with a window plays through the system's default output: WASAPI on Windows, CoreAudio on macOS, ALSA on Linux (loaded at run time, so games link nothing), AAudio on Android, and the browser's audio on the web. Whatever rate and channels the device has, the mixer's stereo at 48 kHz is resampled and mapped to it. A machine with no device, or none the game can open, says so once on stderr and plays nothing; nothing else differs. A game in Unity (see [the command line](#doc-tools--cli--unity)) plays through Unity's audio instead, an AudioSource Unity's mixer and volume apply to, and hears Unity's microphone; in a WebGL player it plays through the page as any web game does. In a browser, sound starts after the player's first press or key. A web game's sound runs about 90 ms behind what the frame played, as the page's audio runs on a thread the game's code can't, and the game feeds it ahead. Tide continues a hidden tab's match with worker timers while the browser lets the page run (see [web builds](#doc-tools--cli)). A suspended or closed page cannot keep simulating or playing sound; background execution is not guaranteed on phones. ## The microphone `Clip.Microphone` is the capture device as a clip. A `Sound` that plays it is what the microphone hears, mono, which its `effect` can filter (a voice changer) and its bus plays or mutes: `volume` 0 to only process what's heard. A one-shot of it plays nothing: the microphone goes through a `Sound`, which says when it stops. ```csharp local singleton Voice { Sound ear; } view Listen(Devices devices, mut Voice voice) { voice.ear.clip = Clip.Microphone; voice.ear.effect = Robot(); if (devices.keyboard.v.down) voice.ear.playing = !voice.ear.playing; } ``` The device is open while a frame names such a `Sound` playing, and closed when none does. Phones and browsers ask the player the first time: until they allow it, and in a browser until they've touched the page, the sound is silence. A device that couldn't be opened is tried again every second; after declining a browser request, stop and start the `Sound` to ask again. An Android app only asks if the game says `Clip.Microphone` somewhere (its manifest then has `RECORD_AUDIO`); a macOS app needs a bundle that says why it listens (`NSMicrophoneUsageDescription`), which `tide build` doesn't make yet. Pitch doesn't apply to the microphone: it plays at the device's own pace, a few blocks behind it. A run with no window has no device: `--microphone voice.wav` plays a file into it instead, looped, so a test hears what a player would say (see [the command line](#doc-tools--cli)). Microphone playback alone sends nothing over the network. The optional [Voice package](#doc-packages--voice) adds Opus voice chat through sessions, outside match state. --- Source: https://tide-engine.dev/game/local-state.md Keep Tide menus, settings, particles and connection status in local state, separate from the deterministic match and its rollback. # Local state The **match** is what every machine simulates the same way. **Local state** belongs to one machine, and lives outside the match: menus, settings, connection status, animation timers, particles. It's never sent, rolled back or checked against other machines. `local` in front of a singleton, scene or event declaration makes it local. Components define a value shape used in either world: ```csharp local singleton Settings { float volume = 1; bool showFps; } component Spark { float2 position; float age; } ``` `local singleton`, `local scene` and `local event` belong to this machine. A component's placement and access choose its world: `Spawn(Spark)` creates a match entity; `local Spawn(Spark)` creates a local entity. Both use the same `Spark` definition. Structs and ordinary functions also work with values from either side. A local singleton exists once per machine, for the whole program. Local entities hold components in local storage. ## Views change local state Views run every frame, in a match or not. They read the match, and read and write local state: `mut` local parameters, and `Spawn`, `Add`, `Remove` and `Destroy` of local entities. ```csharp // Reads the match and leaves a trail of local sparks behind every ball. view Trail(Body body, with Ball) { local Spawn(Spark { position = body.position }); } view DrawSparks(mut local Spark spark) { Draw.Circle(spark.position, 0.1, Color.yellow); spark.age += Frame.dt; if (spark.age >= 0.5) this.Destroy(); } ``` The example below has no match at all: its `Main` is a local scene. Moving the pointer spawns local entities, and a view moves, fades and destroys them, by `Frame.dt`. **Local entities, and no match** ([Run example](https://tide-engine.dev/examples/local-state/?stats)) ```tide settings { title = "Local state"; } local scene Main { } // No match at all: everything here is this machine's own component Spark { float2 position; float2 velocity; float age; } local singleton Trail { Random random; // This machine's own numbers, for effects float2 last; float life = 0.9; int sparks; } // Views change local state: this one spawns local entities. view Emit(Devices devices, mut Trail trail) { Draw.Clear(Color(0.086, 0.086, 0.094)); Draw.SetScreen(); var at = Screen.Flip(devices.pointer.position); if (Math.Distance(at, trail.last) > 6) { var push = (at - trail.last) * 2 + trail.random.NextFloat2Direction() * 40; local Spawn(Spark { position = at, velocity = push }); trail.last = at; } trail.sparks = 0; } // Once for each local entity, every frame: `this` is a LocalEntity. view Sparks(mut local Spark spark, mut Trail trail) { var dt = Math.Min(Frame.dt, 0.05); // A frame's length, never a tick's spark.age += dt; if (spark.age >= trail.life) { this.Destroy(); return; } spark.velocity.y += 260 * dt; spark.position += spark.velocity * dt; var left = 1 - spark.age / trail.life; Draw.Circle(spark.position, 2 + 6 * left, Color(1, 0.55 + 0.4 * left, 0.25, left)); trail.sparks += 1; } view Hud(mut Trail trail) { Draw.Text($"{trail.sparks} local entities", float2(16, 14), 18, Color.white); Draw.Text("Move the pointer, or drag a finger", float2(16, 40), 13, Color(0.64, 0.64, 0.68)); GUI.SetTheme(GUITheme { radius = 6 }); GUI.Slider(Rect(16, Screen.height - 48, Screen.width - 32, 32), "Life", trail.life, 0.2, 2); } ``` `LocalEntity` is an entity of the local world: local `Spawn` returns one, and in a view of local components, `this` is one. Local code can hold and read an `Entity` of the match, like the unit a player selected, but never change it. Local structural changes and local events apply at the end of the frame, as the match's do at the end of the tick. A view only runs when everything it reads exists, so a view of the match's components or singletons doesn't run outside a match. A view runs for the entities of one world: its components are all local, or all the match's. ## Time Local state has no ticks: views run once a frame, at the display's rate. `Frame.dt` is the seconds since the previous frame started, so what a machine animates for itself takes the same time on every display. The sparks above last half a second whether that's 30 frames or 72. ```csharp struct Puff { float2 position; float2 velocity; float age; } local singleton Smoke { List puffs; } view Drift(mut Smoke smoke) { var dt = Math.Min(Frame.dt, 0.05); // A stall isn't a leap mut var i = 0; while (i < smoke.puffs.count) { mut var puff = smoke.puffs[i]; puff.age += dt; if (puff.age >= 1.5) { smoke.puffs.RemoveAt(i); continue; } puff.velocity = puff.velocity * Math.Max(0, 1 - 2 * dt); // Drag puff.position += puff.velocity * dt; smoke.puffs[i] = puff; Draw.Circle(puff.position, 0.2 + puff.age * 0.3, Color(1, 1, 1, 0.4 * (1 - puff.age / 1.5))); i++; } } ``` - **All local code reads it**: views, local handlers, local tasks, and the functions they call. A task that waits a frame at a time moves on by it, as a view does: ```csharp local singleton Banner { float shown; // 0 to 1 } async void Reveal(mut Banner banner) { while (banner.shown < 1) { banner.shown = Math.Min(1, banner.shown + Frame.dt * 3); await Wait.Frames(1); } } ``` - **The match can't.** A frame's length is another on every machine, so a system or a match handler that reads it is an error, which says to take `Time time` and read `time.dt`, a tick's length. A function that reads it is local code, and the match can't call it. - **It needs no match.** It's there in a local scene and while connecting, and it's 0 only before the first frame, in a handler that runs as the program starts. - **It's the frame's real length**, never negative, and long after a stall, so clamp it where that would show. There's no clock of seconds beside it, no `Frame.time`: a float of seconds gets coarser the longer a program runs, so add `Frame.dt` up into a field of your own and wrap it where it repeats (see [A frame's length](#doc-game--views--a-frame-s-length)). The match's seconds are `time.t`. ## Local fields Configured [frags and verts](#doc-game--shaders--configured-shaders), and `Func` values with owned captures, can be kept in local state too. An attached field can use the frag's name as its type, such as `local ShapeLook fragment;`. These values remain outside match snapshots, networking and deterministic hashes. Some of what a machine keeps is about the match's own entities: a mesh baked for each, an animation timer, a smoothed position, a C library's handle. It isn't part of the match, since the simulation never reads it, and every machine can work it out for itself. `local` before a field of a match component or singleton makes that field this machine's: Fixed arrays work here too: `local float3[4] pieces;` keeps four positions in the entity's local storage, with the usual array defaults and checked indexing. ```csharp component Box { float3 pos = float3(0, 0, 5); local List verts; local List faces; } view DrawBox(mut Box box) { if (box.verts.count == 0) Bake(box); Draw.Mesh(box.verts, box.faces, float4x4.Translate(box.pos)); } void Bake(mut Box box) { box.verts = [Vertex3 { position = float3(0, 0, 0) }, Vertex3 { position = float3(0, 1, 0) }, Vertex3 { position = float3(1, 1, 0) }]; box.faces = [0, 1, 2]; } ``` A local field lives outside the match. It's never sent, hashed, snapshotted or rolled back, and the match is exactly what it would be without it: the same world, the same hash, the same download for a player who joins. A mesh of a hundred thousand corners costs a joining player nothing; their machine bakes its own. - **Every entity with the component has them**, on every machine, however that machine learned of the entity: it ran the spawn, joined later, took over as host, or hot reloaded. Nothing attaches or removes them. Each starts at its default, and takes memory only once a view writes it, a local task that uses them runs for the entity, or a view that can start such a task runs for it (it makes them the entity's own first, so the view and the task share them). - **Views read and write them through their parameter.** `Box box` reads them, and `mut Box box` writes them, and only them: the match's fields stay a blended copy the view can't change. A function that takes the component gets them with it, like `Bake` above, and then only views, local handlers and functions like it can call it. - **A local handler of one of the match's events writes them too**, through `mut`, for the entity the event was sent to: a hit's handler sets the flash the entity's view then fades (see [Events](#doc-game--events--local-handlers)). - **A local handler of `Shown` sets them up.** A machine hears `Shown` when an entity and the components a handler needs become available, including entities already present when it joins. Use `local event(Shown) Dress(mut Box box)` to initialize what this machine keeps for a `Box`. `Spawned` describes a genuine spawn; `Hidden` describes losing availability, and `Forgotten` releases local resources when their fields go (see [The engine's events](#doc-game--events--the-engine-s-events)). - **Availability can return after a correction or rebuild.** `Shown` prepares the final presented state, so its initialization should safely reuse or replace resources already stored in local fields. Intermediate add/remove changes between frames do not repeatedly initialize and release them. - **A local task reads and writes them too**, through its component or singleton, which it gets again with them each time it goes on: a mesh a [local worker](#doc-game--tasks--local-workers) made goes straight into the entity's local fields. The task ends when the entity goes from this machine (see [Tasks: local fields](#doc-game--tasks--local-fields)). - **The match can't see them.** Reading or writing one in a system, a match handler or a match task is an error, and so is naming one in a `Spawn` or a component value. A component's value is the match's part: a copy, `var b = box;`, has no local fields. - **They go with the entity**, once it's in neither the world views draw nor the last one the server confirmed. So a destroy this machine predicted wrong, which the server undoes, takes nothing with it, and a spawn it predicted that never happened leaves nothing behind. Losing the component loses them, and a match that's over takes them all. Singletons have them too, like a texture painted from the match's state: ```csharp singleton Arena { float size = 8; local Grid2 floor = Grid2(64, 64); local bool painted; } ``` A local field holds what a local component's field can: text, lists, maps, sets, grids and a `LocalEntity` among them. `local` on a field of a struct, the input, an event, or a declaration that's local already is an error that says why. ### After a rollback A client predicts, and the server can turn out to have had a tick otherwise. This machine spawned a rocket, and in the server's order the entity with that handle is another player's bullet: one handle, two entities. Local fields don't pass from one to the other. Each entity remembers what it was spawned as, the tick and the values it was spawned with, and local fields are kept for the entity they were written for: - A replay that spawns **the same** under the handle (the server had the tick as this machine predicted it) is the same entity, and its local fields stay. - A replay that spawns **something else** there is another entity. What was kept for the first goes, with [`Forgotten`](#doc-game--local-state--letting-go) where a handler asked for it, and the new one starts from the defaults: a view that bakes a mesh bakes it again, once. A spawn that comes out with other values, like a position a wrong guess had moved, counts as something else. **Info** What an entity was spawned as is this machine's own knowledge, from the spawns it ran: it's never sent, and costs the match nothing. Entities that came with the world from the server, to a player who joins, are known by their handles alone. ### Letting go When local fields hold something to let go of, like a C library's handle, a local handler of `Forgotten` hears that they're going, with the fields still there: ```csharp component Model { int kind; local int handle; } local event(Forgotten) FreeModel(Model model) { ReleaseModel(model.handle); } ``` It takes the one component or singleton whose local fields are going, and local singletons. The entity is gone from the match by then, so only its local fields are there to read: what the handler needs of the match goes in a local field while the entity is there. It runs for the entities something was written for, and a singleton's runs once, as the match goes. ## The compiler keeps them apart No mistake here can reach a running game, because the compiler enforces the boundary: - **Match code** (systems, match event handlers, match scenes) can't read or write anything local, a component's [local fields](#doc-game--local-state--local-fields) included, and can't read this machine's `Devices`: it takes a `Devices` parameter, the owner's, which the input sends. - **Local code** (views, local event handlers, local scenes) can read the match, but never change it directly: `mut` on one of the match's components or singletons only writes its local fields. It can send [commands](#doc-game--commands) for a match handler to check and act on; it cannot spawn match entities or send match events. Views read the match as it's drawn, or as the server [confirmed](#doc-game--views-and-the-match--confirmed-state) it, and a local handler [hears its events](#doc-game--events--local-handlers). - The input's `Sample` reads this machine's devices and local singletons, and writes only the input. Input and commands carry local actions into the match. Starting, joining and leaving a match are session calls, which never touch a running match (see [Matches](#doc-multiplayer--matches)). The errors say where to go instead: ```csharp // Error: match code can't read local state. system Count(local Spark spark) { } ``` ## Quitting `Application.Quit()` ends the program after this frame, as closing its window does: this machine leaves its match first (with [host migration](#doc-multiplayer--matches--host-migration), the others carry a match it ran on), and the program's exit code is 0. It's local code's, like `Session`'s calls: a view, a local handler or a function they call, never match code, as quitting is this machine's alone. ```csharp view Menu() { GUILayout.Area(Anchor.MiddleCenter) { if (GUILayout.Button("Quit")) Application.Quit(); } } ``` - **On desktop and Android**, the window closes and the program ends. A run with no window (`--frames`, `--script`) ends at that frame as at its script's `quit`, its `--capture` taking that frame. - **On the web**, a page can't close itself: the game stops running and the page hears it end (`Tide.onExit(0)`), its last frame still showing. What the page shows then is the page's. - **Inside another program** (Unity, `tide/embed.h`), that program decides: Unity's `TideRunner` ends play mode in the editor and quits a player, unless a `QuitAsked` handler takes it. - **A dedicated server** runs no local code, so nothing there quits this way. ## Local scenes and events A local `Main` starts the program outside any match, usually in a menu: ```csharp local scene Main { } ``` Move between local scenes with `Scene.Switch(Lobby)`, and unload the menu as a match starts: it stays gone until this machine is offline again (see [Switching scenes](#doc-game--scenes--switching-scenes)). `local event` declares an event of this machine's own, which local code sends and handles. A local handler is `local` before a handler, `local event(...)`, and what it takes depends on what it hears: - **Local events**, and `Spawned` and `Destroyed` of local entities: local state only. - **The match's events**, to show what happened: what it reads of the match, as the event left it, and local state. Through `mut` it writes the [local fields](#doc-game--local-state--local-fields) of the entity the event was sent to. See [Events](#doc-game--events--local-handlers). - **[`Forgotten`](#doc-game--local-state--letting-go)**: the component or singleton whose local fields are going, and local singletons. ### A frame, in order 1. The local handlers of the match's events run, for each tick this machine simulated since the last frame, and for the entities of a world that arrived since. 2. The local fields of entities that are gone go, with [`Forgotten`](#doc-game--local-state--letting-go) first where a handler asked for it. 3. The views run. 4. What handlers and views spawned, changed and sent locally is handled. So a view draws what a handler left in the same frame. What a handler wrote into the local fields of an entity that's gone by then goes in that frame too, before the views. --- Source: https://tide-engine.dev/game/files.md Read and write local files in Tide, use persistent save and temporary cache paths, and fetch URL bytes from views, handlers or tasks. # Files and directories `File` and `Directory` read and change this machine's files, and `Web.Fetch` gets a URL's bytes. Use them from views, local handlers and local tasks, or functions those call. They cannot run in the match, in input sampling, on the GPU or inside a parallel loop. A service or file's contents reach the match through [input](#doc-game--input) or a [command](#doc-game--commands). ## Where to save `Application.persistentDataPath` is the game's save directory. Its contents survive normal restarts and application updates. `Application.temporaryCachePath` is for disposable files; code must tolerate their disappearance. Both are read-only runtime properties. The engine keeps two files of its own in the temporary cache folder. `pipelines.vulkan` holds the GPU programs it compiled with Vulkan, so the game's next run starts drawing sooner. `pipelines.keys` says how each of the game's shaders was drawn (into which kind of target, blended how), so the next run compiles them as it starts, rather than in the frame that first draws one; a shader whose code changed keeps its name, so it's compiled as it starts too. On a desktop with an NVIDIA GPU, the `driver` folder beside them is the driver's own cache of what it compiled for the game, which it would otherwise keep with every other program's; past 256 MB it starts over. It isn't used where `__GL_SHADER_DISK_CACHE_PATH` or `__GL_SHADER_DISK_CACHE=0` is set. They're there whether or not the game uses files: `pipelines.vulkan` for a game that draws with Vulkan, `pipelines.keys` for any that draws on a desktop or a phone; a page keeps neither. Deleting them is harmless: the next run compiles its shaders as it draws them, and writes them again. Save locations use the game's stable `appId` setting, independently of its window title: ```csharp settings { appId = "com.studio.game"; } void WriteSave(string contents) fails IOError { var path = Path.Combine(Application.persistentDataPath, "save.txt"); try File.WriteAllText(path, contents); } ``` Without an explicit `appId`, the standard host derives one from the game's folder or target name. Set one before shipping: changing it changes which save directory the game uses. Relative paths resolve under the persistent data directory on every platform. Explicit absolute paths are usable on native platforms subject to the OS's permissions. On the web, files stay inside this game's persistent and temporary virtual roots. For native desktop tests, [`--data-dir `](#doc-tools--cli--without-a-window) selects a separate persistent directory. Scripted runs otherwise use the normal saves. The override changes relative paths and `Application.persistentDataPath`; explicit absolute paths still reach the files they name. ## Saving the match Match code can't touch files: they're this machine's, and the match is the same on every machine. What a match needs kept, it asks the machine that runs it to keep, with `Storage`: ```csharp // As a chunk nobody is near goes Storage.Save($"chunks/{chunk.at.x}_{chunk.at.z}", chunk.blocks.ToBytes()); // As someone next comes near: the answer is an event, a tick later Storage.Load($"chunks/{at.x}_{at.z}", chunk); event(Loaded loaded) Fill(mut Chunk chunk) { if (loaded.found) chunk.blocks = Grid3.FromBytes(loaded.bytes) ?? Grid3(16, 16, 16); } ``` A grid's `ToBytes()` and its type's `FromBytes(bytes)` turn it into a `List` and back, its size and its cells, a chunk of air as nothing and a chunk of one block as a few bytes (see [Grids as bytes](#doc-language--grids--grids-as-bytes)). For values of other kinds, a game writes its own bytes, or [JSON](#doc-language--json). `Storage.Save(key, bytes)` keeps a `List` under a key, replacing what was there. `Storage.Load(key)` asks for it back: the answer is a `Loaded` event in a later tick, with the `key`, the `bytes`, whether it was `found`, and whether reading it `failed` (something is kept there that couldn't be read, which a game shouldn't make afresh and save over), sent to the entity the load names (`Storage.Load(key, entity)`) or to the world. `Storage.Delete(key)` forgets it. `Storage.List(prefix)` asks for the keys that start with a prefix: the answer is a `Listed` event in a later tick, with the `keys` sorted by their bytes, 1,024 at the most, whether there are `more` past the last, and whether listing them `failed`. To go on, list again after the last key, `Storage.List(prefix, after)`. Like a load, a listing goes to the entity it names, `Storage.List(prefix, entity)` or `Storage.List(prefix, after, entity)`, or to the world: ```csharp // Every chunk dimension 0 has saved, a page at a time Storage.List("chunks/0/", this); event(Listed listed) Count(mut Atlas atlas) { if (listed.failed) return; atlas.saved += listed.keys.count; if (listed.more) Storage.List(listed.prefix, listed.keys[listed.keys.count - 1], this); } ``` A listing has only keys a save made: other files in the folder (a half-written save the server stopped in, a file someone put there) are left out. ### Waiting for the answer in a task A match [task](#doc-game--tasks) can wait for a load or a listing instead, and have the answer as a value: `await Storage.Load(key)` gives the `List` kept under the key, and `await Storage.List(prefix)` or `await Storage.List(prefix, after)` a `StorageKeys`, its `keys` and whether there are `more`. Each fails with an `IOError`: `NotFound` where nothing is kept under the key, `Failed` where something is kept that couldn't be read, or the keys couldn't be listed, and `InvalidPath` at once, in the tick it's awaited, for a key the store can't keep: an empty one, or one longer than 256 bytes (a listing's prefix or `after` longer than that too). ```csharp // A chunk's blocks, once the store has answered async void Fill(mut Chunk chunk, string key) { var saved = await Storage.Load(key); if (saved is List bytes && Grid3.FromBytes(bytes) is Grid3 blocks) chunk.blocks = blocks.Copy(); else if (saved is IOError.NotFound) chunk.stage = Stage.Missing; // Never saved: made from the seed // Anything else was kept but couldn't be read: not made afresh over it } // Every key under a prefix, a page at a time async void Survey(mut Atlas atlas, string prefix) { mut var after = ""; mut var going = true; while (going) { var page = await Storage.List(prefix, after); if (page is StorageKeys keys) { atlas.saved += keys.keys.count; going = keys.more; if (going) after = keys.keys[keys.keys.count - 1]; } else going = false; } } ``` The answer is the same as a `Loaded`'s or a `Listed`'s, and comes the same way: in a later tick, the same one on every machine, which the task goes on at the end of with the other tasks whose time has come. An awaited load names no entity, as its answer is the task's; without `await`, `Storage.Load(key)` is answered by a `Loaded` event, in a task too. Two tasks that await one key are answered apart. What a task waits for is kept in it, so a snapshot, a joining player and a rewind keep it too. A task that ends before its answer comes (its entity was destroyed, or it was cancelled) is gone, and its answer changes nothing. Rewinding the match drops the answers on their way, and the tasks the rewound match has waiting ask again. Only match tasks wait for the store: local code keeps this machine's files with `File`. The answer comes once the files have been read, usually the next tick or the one after, and its handlers run after that tick's systems. In a match that doesn't hide state, an answer of more than about 1 KiB goes to every player first, as a big command does, so it can take longer, and the answers after it wait for it. The answers come in the order they were asked, and what a tick asks is carried out after what the ticks before it asked: a load after a save of its key, in the same tick or a later one, finds what was saved. The standard hosts read and write the files on a thread of their own, so a tick never waits for the disk; a page keeps them on its own thread, between ticks. A [run with no window](#doc-tools--cli--without-a-window) (`--frames`, `--capture`, `--script`) reads and writes them as each tick ends instead, so every answer comes the tick after it was asked and the run goes the same every time. A server that stops cleanly writes what it was asked to save first. A load of a key nothing was saved under costs no read: the server lists `saved/` once, at its first load, and from then on knows which keys have a file (those listed, and those it saved since). So a world that asks for every chunk a player comes near, most of them never changed, asks the disk only for the ones that were. While the server runs, `saved/` is its own: a file put there by anything else (a backup copied in, the game's own file calls) may not be found until the server starts again. Only the server asks: a player's machine that runs the same tick saves and loads nothing. With the standard hosts, each key is a file in `saved/` in the game's persistent data folder, on the machine that runs the match: the hosting player's, or a dedicated server's (the same folder, named for the game's `appId` or, without one, for the game). A key is any text up to 256 bytes, with `/` for folders, and a value up to 32 MiB. Any key is a file of its own on every system: in its file's name, everything but small letters, digits, `-`, `_` and the dots of its last part is written out as `%XX`, and so is the first letter of a Windows device's name (`con`, `nul`). A save is written whole beside the old file and then moved over it, so a server that stops mid-save keeps one or the other. Every match a server hosts shares the folder, so a game with several worlds puts the world's name in its keys. A match that uses the store can't change hands (`hostMigration`): what it keeps is on the hosting machine. A match the [hosting service](#doc-multiplayer--hosting--the-match-s-store) runs keeps its store there, with the same keys, values and answers: the service reads and writes it while the match goes on, and the answers come in the order they were asked, as from files. Each world keeps its own (a long-lived match's, which it finds again when it's resumed or recovered, or a sharded world's, which all its shards share), within the service's limits on a value, on what one world and one account keep and on how fast a world reads and writes; a save past them isn't kept, and the match's log says why. Every load is answered, as `failed` where the service couldn't read it. `Storage.Flush` is local code's, and about this machine's own files. ## Logs and crashes A game run with a window keeps its log and its crashes in its persistent data directory (`Application.persistentDataPath`), beside its saves, so a player's problem can be looked into once they send them: | System | Log | Crashes | |---|---|---| | Windows | `%USERPROFILE%\AppData\LocalLow\\Player.log` | `%USERPROFILE%\AppData\LocalLow\\Crashes\` | | macOS | `~/Library/Application Support//Player.log` | `~/Library/Application Support//Crashes/` | | Linux | `~/.local/share//Player.log` (under `$XDG_DATA_HOME` when it's set) | `~/.local/share//Crashes/` | | Android | `Player.log` in the app's internal storage; the system log (`adb logcat`) has it too | The system's own crash reports | | Web | The browser's console | The browser's console | With [`--data-dir `](#doc-tools--cli--without-a-window) they go in that folder instead. `Player.log` has everything the game wrote to stderr, after a line naming the Tide version, the game's `appId`, the system and the time it started: `Debug.Log` and `Debug.Assert`, the engine's messages and what your C prints there. The output still reaches the terminal or console too. The run before is kept as `Player-prev.log` beside it, and a log stops growing at 100 MB. A crash on Windows, macOS or Linux leaves a folder of its own in `Crashes`, named `Crash__