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 or a command.

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:

tide
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.

The engine's folder

The Tide folder in Application.persistentDataPath is the engine's: the match's store keeps its files in Tide/store/. File and Directory calls can't use it, so a game's files can never be mistaken for the store's or overwrite them. Every call on a path in it, the folder itself too, fails with IOError.AccessDenied, as does moving or deleting a folder it's in (the persistent data directory itself, say); File.Exists and Directory.Exists are false there. Listing a folder it's in names the Tide folder, but nothing inside it. Keep the game's own files anywhere else in the directory, and what the match needs kept in Storage. The first refused call of a run prints that to the log.

A path is refused however it's written: relative or absolute, with / or \, through . or .. (saves/../Tide/x), and in any case (TIDE/store), on every platform alike, so a game that works on one works on all. Names that only look like it are the game's: Tide2/, tide-notes.txt and saves/Tide/ are fine.

For native desktop tests, --data-dir <folder> 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:

tide
// 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<Block>.FromBytes(loaded.bytes) ?? Grid3(16, 16, 16);
}

A grid's ToBytes() and its type's FromBytes(bytes) turn it into a List<byte> 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). For values of other kinds, a game writes its own bytes, or JSON.

Storage.Save(key, bytes) keeps a List<byte> 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:

tide
// 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 can wait for a load or a listing instead, and have the answer as a value: await Storage.Load(key) gives the List<byte> 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).

tide
// 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<byte> bytes && Grid3<Block>.FromBytes(bytes) is Grid3<Block> 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 (--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 Tide/store/ 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. The game's own file calls can't touch the folder (see The engine's folder); a file put there by anything else while the server runs (a backup copied in by hand) 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 Tide/store/ 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 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\<appId>\Player.log %USERPROFILE%\AppData\LocalLow\<appId>\Crashes\
macOS ~/Library/Application Support/<appId>/Player.log ~/Library/Application Support/<appId>/Crashes/
Linux ~/.local/share/<appId>/Player.log (under $XDG_DATA_HOME when it's set) ~/.local/share/<appId>/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 <folder> 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_<UTC date>_<time>, with:

  • crash.txt: what the crash was (an access violation, a signal, an abort, as a failed Debug.Assert ends) and the stack, as module and offset
  • Player.log: a copy of the log up to the crash
  • crash.dmp on Windows: a minidump, which Visual Studio, WinDbg or CLion open with the build's PDB

The log also notes the GPU the game draws with and its driver, which isn't printed to the terminal.

A game built with tide build has tide-crash beside it, which a crash opens. It's a small window of its own, so it opens at once however big the game is. It names the game by its title and shows what the report says: the crash and its stack, then the last lines of the log, which may help a player see what led to it. Its Show report button opens the file manager at the crash's zip, Crash_<UTC date>_<time>.zip beside its folder. The zip holds crash.txt, system.txt (the system's version, processor and memory), the end of Player.log (at most its last 4 MB) and the minidump. On Linux it needs an X display, which Wayland desktops provide too; without one it opens nothing, and the zip is still there. tide run doesn't put it beside the game, so a crash while you work goes to the terminal.

What a report leaves out

Before the zip is made, tide-crash masks what would say who the player is, with * in place of each character, so a report can go to you as it is:

  • the folder after Users or home in every path, which is usually the player's name (C:\Users\*****\AppData\...); Public and Default stay
  • the player's user name and the computer's name, wherever they're a whole word
  • IP addresses, except the machine's own (127.0.0.1, ::1), and email addresses

It masks them in the log, in crash.txt and system.txt, and in the minidump: the paths of its modules and the memory it holds. Only the zip is masked; the crash's folder keeps the files as they were. The masking can't know everything your game writes, so don't Debug.Log a player's account details, chat or other personal data.

Receiving reports

A game linked to a hosting project with crash reports on sends each report there by itself, without asking the player. Its window then says the report was sent, and still shows what it says. Turn reports on in the project's Settings tab in the hosting console, which shows the project's report key. tide deploy writes the key into the game's tide.deploy.json as "reports", or you can add it there yourself:

json
{
  "origin": "https://console.tide-engine.dev",
  "project": "<project id>",
  "reports": "<report key>"
}

tide build then puts crash.json beside the game, with the key, the service's address and the build's ID (the SHA-256 of the game's program), and tide-crash sends there. Ship crash.json with the game. The console groups reports by what crashed and where, with how often and on which builds, systems and GPUs, and keeps each report's files. The hosting plan includes a monthly number of reports; past it, reports are dropped unless extra usage is on.

The key ships inside the game, so all it can do is add reports to its project. Replacing it in the console stops the old one, and the next build carries the new one. Turning reports off and building again removes crash.json. A run with TIDE_HIDDEN set never sends.

The ten newest crash folders and their zips are kept. Under a debugger the debugger has the crash instead. A run with no window (--frames, --capture, --script) writes no log, as its output is the test's.

Whole-file operations

Call Behavior
File.Exists(path) Whether a file exists; false if the path is inaccessible or invalid.
File.Create(path) Create an empty file, replacing its contents if it exists.
File.ReadAllText(path) Read UTF-8 text; invalid UTF-8 fails with IOError.InvalidData.
File.WriteAllText(path, text) Create or replace a UTF-8 file.
File.AppendAllText(path, text) Append UTF-8 text, creating the file if necessary.
File.ReadAllBytes(path) Read the exact contents as a List<byte>.
File.WriteAllBytes(path, bytes) Create or replace a file with a List<byte>.
File.Copy(source, destination[, overwrite]) Copy a file; overwriting is off by default.
File.Move(source, destination[, overwrite]) Move or rename a file; overwriting is off by default.
File.Delete(path) Delete a file; an absent file succeeds.

Writing a file does not create its parent directories. Use Directory.CreateDirectory first. byte is an unsigned integer from 0 to 255, so binary files can contain every byte, including zero, without text encoding.

tide
void WriteBinary() fails IOError
{
    var folder = Path.Combine(Application.persistentDataPath, "saves");
    try Directory.CreateDirectory(folder);
    try File.WriteAllBytes(Path.Combine(folder, "data.bin"), [0, 128, 255]);
}

Directories and paths

Call Behavior
Directory.Exists(path) Whether a directory exists.
Directory.CreateDirectory(path) Create missing parents; an existing directory succeeds.
Directory.GetFiles(path[, recursive]) A List<string> of file paths.
Directory.GetDirectories(path[, recursive]) A List<string> of directory paths.
Directory.Move(source, destination) Move or rename a directory; the destination must be absent.
Directory.Delete(path[, recursive]) Delete a directory. Nonempty directories require recursive = true.

Enumeration returns complete paths, sorted by their UTF-8 bytes. Recursion is off by default; native recursive traversal does not follow directory links. A missing directory is an error.

Path.Combine(a, b) joins paths with a separator, using the second path by itself if it is absolute. Path.GetFileName(path), Path.GetDirectoryName(path) and Path.GetExtension(path) work on the path's text without accessing the filesystem. Both / and \ are recognized as separators. These pure operations can also run in match code.

Errors and persistence

File and Directory operations other than Exists use errors as values: fails IOError. A missing file gives IOError.NotFound; reading an empty file succeeds with empty text or an empty list. Other error members are AlreadyExists, AccessDenied, InvalidPath, NotDirectory, DirectoryNotEmpty, OutOfSpace, StorageUnavailable, InvalidData, Failed, and TimedOut, which only a request with a time limit gives.

On the web, a virtual filesystem is loaded from IndexedDB before the game starts. Reads and mutations then operate immediately in memory. Persistent changes are committed automatically in the background, and hot reload retains the files and pending commits. Temporary files are held only by the page.

await Storage.Flush() confirms that save changes made before the call have committed. It is a local asynchronous operation that can fail with IOError; it does not freeze the frame loop. On native platforms it flushes the affected files and directory changes through the operating system.

tide
local singleton SaveStatus { bool saved; string message; }

async void Save(string contents, mut SaveStatus status)
{
    status.saved = false;
    if (WriteSave(contents) is IOError error)
    {
        status.message = "Write failed: " + error;
        return;
    }
    if (await Storage.Flush() is IOError error)
    {
        status.message = "Save failed: " + error;
        return;
    }
    status.saved = true;
    status.message = "Saved";
}

Wait for a flush before showing that a save is finished. Do this during play: closing a browser page cannot reliably finish pending work. A failed commit retains its in-memory changes, so another flush can retry them. Browser storage belongs to the site's origin and browser profile, and may be cleared by the user or evicted by the browser. Unavailable persistent storage is reported as an error; the temporary directory remains usable.

Fetching a URL

await Web.Fetch(url) gets what's at an http:// or https:// URL, as a List<byte>. It's local and asynchronous, like Storage.Flush: the task waits while this machine fetches, frames go on, and the bytes arrive in a frame to come. It fails with IOError:

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, or more than 5 redirects.

Redirects are followed. On the web it's the page's fetch, so the server's CORS rules apply, and a refusal is Failed. Natively it's an HTTP client of the engine's own over the system's TLS. Nothing times out: a server that never answers is a fetch that never ends, as a browser's is. For a fetch with a time limit, send a request: await Web.Request(url).SetTimeout(10).Send().

Sending a request

Web.Fetch is a GET that wants a page. To talk to a service, build a request and send it: Web.Request(url) gives a WebRequest, each call on it gives the request with one more thing set, and await request.Send() sends it.

tide
async void Report(string url, List<byte> score, mut Board board)
{
    var answer = await Web.Request(url)
        .SetMethod("POST")
        .SetHeader("Content-Type", "application/octet-stream")
        .SetBody(score)
        .Send();
    if (answer is WebResponse response)
    {
        board.accepted = response.status == 200;
        board.reply = response.body;
    }
    else board.accepted = false; // No answer came
}
Call What it sets
Web.Request(url) A request to that URL: a GET, with no headers and no body
SetMethod(method) The method, like "POST", "PUT" or "DELETE", in any case
SetHeader(name, value) One more header
SetBody(bytes) The body, a List<byte>
SetTimeout(seconds) How long its answer may take; 0 or less is no limit, which is what a request starts with
await request.Send() Sends it, and gives a WebResponse: its status and its body

A service that speaks JSON takes and gives structs: SetBody(Json.Write(report).ToBytes()) sends one, and Json.Read<Answer>(response.body) reads the reply as one, or gives nothing when the reply isn't what the game expects (see JSON).

A request is a value, like any struct: a call changes nothing where it's written, it gives a new request. So a request kept in a variable is built on by assigning, request = request.SetHeader("Accept", "text/plain");, and its fields can be set as they are (request.method = "PUT";). Keep one and send it as often as you like.

An answer is an answer, whatever its status. A 404 or a 500 comes back as a WebResponse with that status and the body the server sent, for the game to read. Send fails only when no answer came:

Result When
IOError.InvalidPath The URL doesn't start with http:// or https://.
IOError.InvalidData The request can't be sent as it's written: a method that isn't a word of letters, or is CONNECT, TRACE or TRACK; a header whose name isn't a token or whose value has more than printable ASCII; a body over 64 MiB.
IOError.TimedOut The request has a time limit, and its whole answer didn't come within it.
IOError.Failed Anything else: no connection, a certificate the system doesn't trust, an answer over 64 MiB, more than 5 redirects, or on the web a server whose CORS refuses the page.

A request waits as long as it takes, unless it has a time limit. A server that takes a request and never answers is a Send that never ends, and the task waiting for it waits too. SetTimeout(seconds) gives the request a limit: once that many seconds have passed with no whole answer, from Send to the last byte of the body, the request is stopped and Send fails with IOError.TimedOut. Nothing is tried again; that's the game's to decide.

tide
async void Ask(string url, mut Board board)
{
    var answer = await Web.Request(url).SetTimeout(10).Send();
    if (answer is IOError.TimedOut) board.note = "The server took too long.";
    else if (answer is WebResponse response) board.reply = response.body;
}

The limit is this machine's own time, so it's no rule of the match. There's no way yet to cancel a request from code once it's sent: give one that might hang a limit.

The rest is Web.Fetch's: local and asynchronous, the page's fetch on the web and the engine's own client natively. Redirects are followed as a browser follows them: a 303, and a POST's 301 or 302, become a GET of where they point, and a 307 or 308 is the same request again. Host, Content-Length, Connection and Transfer-Encoding are the sender's own to say, so setting them does nothing, and a browser keeps a few more to itself (User-Agent among them). A line break in a header's name or value becomes a space. On the web, a request with headers of its own or a method beyond GET and POST is one the server has to allow (CORS), as for any page.

What a machine fetches is its own, like a file it reads. A picture every player should see goes into the match through a command, and each machine decodes it there (see Assets):

tide
local singleton Download { bool busy; string message; }

async void Load(string url, mut Download download)
{
    download.busy = true;
    if (await Web.Fetch(url) is IOError error)
    {
        download.message = "Couldn't fetch: " + error;
    }
    else download.message = "Fetched";
    download.busy = false;
}