# csharp

Part of the [scripting reference](index.md), written by the engine so it matches your `frost`. Start with [your first game](../start/first-game.md) if you are new.

Use when writing gameplay in C#, checking Luau API parity or preparing the .NET tools and platform build.

# Writing a game in C#

A game's scripts can be C# as well as Luau: a script whose name ends in `.cs` is compiled
by the .NET SDK on the machine (version 10 or later) and run by the .NET runtime inside
`frost`. It is for `frost` with C#: Coldwave's download whose name ends in `-csharp`, or a
`frost` built with its `dotnet` feature (`cargo build -p frost_cli --features dotnet`). A game
in C# is exported to the desktop with its scripts compiled ahead of time (below); the web
does not run C#.
the engine's `csharp/vigil` example is the arena template, Vigil, written in C#: played on its recording it is the Luau Vigil to the bit at every step, but for what each script keeps. the engine's `csharp/embers` example is Embers, the 3D template, the same way: a mover on Jolt, sensors, chasers, the interface and the engine's `Follow` camera, with no camera code in either language. An angle kept from 0 to 360 is `a - Math.Floor(a / 360) * 360` in C#, Luau's `%`: C#'s `%` keeps the sign of `a`.

## A script

```csharp
using Ven;

[State]                                  // the one struct the script keeps between steps
public struct Game
{
    public int Score;
    public Thing Hero;                   // a thing of the game, or Thing.None
}

public static class Main
{
    public static void OnScene(string scene, ref Game game)
    {
        game.Hero = World.Spawn("Transform", "Sprite", name: "hero");
        World.Set(game.Hero, "Sprite", "image", "art/hero.png");
    }

    public static void Step(float dt, TransformColumns transform, ref Game game)
    {
        int row = transform.Row(game.Hero);
        if (row >= 0) transform.X[row] += Input.Get(0, "move_x") * 90 * dt;
        if (Input.Held(0, "fire")) Sound.Play("sounds/pew.wav", vary: 0.1);
    }
}
```

`Step` takes the components it walks as columns: each is lent the world's own memory for
the length of the step, a span per number or true-or-false field (`transform.X[row]`), with
`Rows`, `Thing(row)` (the thing at a row), `Row(thing)` (a thing's row, -1 for none) and
`Slot`/`Row(slot)` to join two components. That is Luau's `each`, `has`, `get` and `set`
as reads of memory, and the fast path. Everything else is a call: the table below.

Custom `{ f64 = 0.0 }` fields lend `Span<double>` columns; `{ u32 = 0 }` lends
`Span<uint>`. `World.Get` and `World.Set` carry both through a double without rounding.
Snapshots preserve bits; as with f32, equality and checksums canonicalize NaNs while
distinguishing signed zeros.

The struct marked `[State]` is in the world under the script's name, as Luau's `state` is:
in the checksum, in a snapshot, read by `script.state`. It holds `bool`, `int`, `uint`, `float`,
`double` and `Thing` fields. A `static` field is the script's own and is not saved, as a
Luau `local` is not: `frost test --restore` finds one that changes the game.

## Writes are done when the step returns

The columns a step holds are the world's own memory, so nothing changes the world's shape
while it runs. A call reads the world as it is; what a call changes (`Set`, `Spawn`,
`Despawn`, `Send`, `Tween`, `Place`, `Ui.Focus`, `Scene.Load`) is done when the script's
`Step` (or `OnScene`) returns, in the order it was asked, before the next script steps.
The world then goes through the same changes in the same order as the same calls in Luau,
so it reaches the same slots and the same checksum (`tests/csharp_api.rs` plays one game
in both for 240 steps and holds the two worlds equal at every step). What that means:

- A thing `World.Spawn` makes is a thing to come: `Set`, `Despawn`, `Tween` and `Send`
  take it, and the `[State]` struct holds it as the thing it became. Columns do not have
  it until the next step (`Row` gives -1), and `Get` and `Has` refuse it.
- `World.Get` reads the world as the step found it, with what the step's spans wrote; a
  `World.Set` earlier in the step is not seen yet.
- A Luau loop over `each` after a `spawn` finds the new thing; a C# loop over a column
  does not. Make things after walking the ones there are.

`Bone` overrides use ordinary generated columns or `World.Set`. `World.Bone`, `World.Placed`,
`Screen.Project` and `Screen.Ray` include queued writes from this step; other reads retain
their documented column semantics. Spatial reads currently copy the world when writes are pending.

A number written to a whole-number field must be whole; a call that cannot be done throws
`Ven.EngineError` with the engine's sentence, and the step stops with `E0302` on the
script's own line and column (`frost` compiles scripts without the optimiser so that the line
is right).

## The API against Luau's

Every call a Luau script has, and what a C# script calls for it. `tests/csharp_parity.rs`
holds this table to both sides: it fails when Luau gains a call this table lacks, or C#
gains one (a public method of `World`, `Input`, `Events`, `Sound`, `Net`, `Music`, `Scene`,
`Frame`, `Screen`, `Tuning`, `Quat`, `Ui`, `Physics`, `Save` or `Data`) that no row names. A
component's fields are no calls: a field (`Mesh.roughness`, a 3D thing's `Opacity.alpha`) is
read and written by `World.Get` and `World.Set` as Luau's `get` and `set` do, so it needs
no row.

The call numbers keep `World.Emit` at 52; `NetHost`, `NetJoin`, `NetCancel`,
`NetState` and `NetPlayer` are 53, 54, 55, 56 and 57. `Bone`, `ScreenProject` and
`ScreenRay` are 58, 59 and 60. `COUNT` and the Rust `OPS` table's length are 63. `StreamLoaded` and `StreamHold` are 61 and 62.

<!-- parity -->
| Luau | C# |
| --- | --- |
| `step` | `Step(float dt, ...)` |
| `state` | the `[State]` struct |
| `keeps_things` | a `Thing` field of the `[State]` struct: its type says it is a thing |
| `on_scene` | `OnScene(string scene, ref State state)` |
| `on_restore` | `OnRestore()`, called before the next step after the game was put back: empty a static cache there |
| `find` | `World.Find` |
| `get` | `World.Get`, `World.GetBool`, `World.GetText`; a column's span |
| `set` | `World.Set`; a column's span |
| `has` | `World.Has`; a column's `Row(thing) >= 0` |
| `each` | a component's columns: `Rows`, `Thing(row)` |
| `spawn` | `World.Spawn` |
| `despawn` | `World.Despawn` |
| `emit` | `World.Emit` |
| `send` | `World.Send` |
| `events` | `Events.Count`, `Events.At` |
| `tween` | `World.Tween` |
| `place` | `World.Place` |
| `placed` | `World.Placed` |
| `bone` | `World.Bone` |
| `screen.project` | `Screen.Project` |
| `screen.ray` | `Screen.Ray` |
| `print` | `World.Print` |
| `tuning` | `Tuning.Get` |
| `library` | a `.cs` file under the project's `libraries`, compiled into every C# script: its classes are the script's |
| `data` | `Data.Get`, a `Table` |
| `math.random` | `World.Random` |
| `math.roundeven` | C#'s own Math.Round(x, MidpointRounding.ToEven) |
| `bit32.mul` | C#'s own unchecked((int)(a * b)) |
| `input.get` | `Input.Get` |
| `input.held` | `Input.Held` |
| `input.keys` | `Input.Keys` |
| `sound.play` | `Sound.Play` (its `near` and `far` too, by name) |
| `sound.volume` | `Sound.Volume` |
| `sound.effects` | `Sound.Effects` |
| `music.play` | `Music.Play` |
| `music.stop` | `Music.Stop` |
| `music.pause` | `Music.Pause` |
| `music.resume` | `Music.Resume` |
| `music.volume` | `Music.Volume` |
| `net.host` | `Net.Host` |
| `net.join` | `Net.Join` |
| `net.cancel` | `Net.Cancel` |
| `net.state` | `Net.State`, a `NetState` (`Player` -1 while unknown) |
| `net.player` | `Net.Player`, -1 while unknown |
| `stream.loaded` | `Scene.Loaded` |
| `stream.hold` | `Scene.Hold` |
| `scene.load` | `Scene.Load` |
| `scene.name` | `Scene.Name` |
| `frame.size` | `Frame.Size` |
| `ui.focus` | `Ui.Focus` |
| `ui.measure` | `Ui.Measure` |
| `quat.turn` | `Quat.Turn` |
| `quat.look` | `Quat.Look` |
| `quat.mul` | `Quat.Mul` |
| `quat.slerp` | `Quat.Slerp` |
| `quat.rotate` | `Quat.Rotate` |
| `save.get` | `Save.Get`, a `Table` or null |
| `save.set` | `Save.Set` |
| `save.delete` | `Save.Delete` |
| `save.slots` | `Save.Slots` |
| `physics.ray` | `Physics.Ray` |
| `physics.cast` | `Physics.Cast` |
| `physics.overlap` | `Physics.Overlap` |
| `physics.ground` | `Physics.Ground` |
| `physics.mass` | `Physics.Mass` |
| `physics.wheels` | `Physics.Wheels` |
| `ground.at` | `Ground.At` |
| `physics.impulse` | `Physics.Impulse` |
| `physics.force` | `Physics.Force` |
| `physics.pause` | `Physics.Pause` |
| `physics.paused` | `Physics.Paused` |
<!-- /parity -->

A `Table` is a Luau table as C# holds one: flat, each value under its path, the keys on the
way with a `.` between, so `level.waves[1].count` in Luau is
`Data.Get("levels/one.toml").Number("waves.1.count")` in C#, and `Count("waves")` is `#level.waves`.
`new Table().Set("best", 120)` is what `Save.Set` keeps; a table of tables is written the
same way (`Set("best.time", 31.5)`).

What reads the machine's clock or draws chance of its own is refused as the script
compiles (`VEN105`, in `E0309`): `DateTime.Now`, `UtcNow` and `Today` (and
`DateTimeOffset`'s), `Environment.TickCount`, a `Stopwatch`, `new Random()` with no seed,
`Random.Shared` and `Guid.NewGuid()`. A game reads nothing but its inputs, so that a replay,
a rollback and another player's machine play it the same: time is the steps, and the
`dt` each `Step` is given; chance is `World.Random`. A `Random` with a seed is the script's
to use.

Luau's `%` is floored and C#'s is not: `-30 % 360` is 330 in Luau and -30 in C#. An
angle kept from 0 to 360 is `a - Math.Floor(a / 360) * 360` in C# to give Luau's bits.

A model's clip is a field like any: Luau plays one with `set(arm, "Pose", "clip", "lift")`
and asks which plays with `get(arm, "Pose", "clip")`; C# with `World.Set(arm, "Pose",
"clip", "lift")` and `World.GetText(arm, "Pose", "clip")` (or the `Pose` columns' spans).

Luau's `math` (sine and its kin, `pow`, `log`) is `Maths` in C#, the same bits on every
machine; `System.Math.Sin` and its kin are refused (`VEN104`), because they give other
answers on other machines.

## Saving, errors, the debugger

- Saving a `.cs` file under `frost dev` swaps the code and keeps the world and the `[State]`
  struct; code that does not compile is refused (`E0309`, with its line) and the old code
  runs on.
- `frost check` writes a project a C# language server is started on (`game.info`'s
  `csharp.solution`).
- `World.Print` lines carry the file and line of the call, a script's or a library's, as
  Luau's `print` does (`log.since`); an error in a C# library names the library's file and
  line; `game.info`'s `csharp.scripts` says of each script `ahead` or `runtime`.
- `frost dap` debugs a game in C# with the person's own netcoredbg (on the path, or named by
  `FROST_NETCOREDBG`; `frost` installs none): it starts the engine as for Luau, attaches
  netcoredbg to it and hands it the editor's requests. Breakpoints go in the game's own `.cs`
  files (the compiled script's symbols name them), and a stop shows .NET's threads, stack,
  locals and expressions. A game in both Luau and C# is refused. netcoredbg's own command
  line (`--interpreter=cli`) waits for ever on any expression that reads a frame (`print
  dt`, `print v.T`) at such a stop, where `print 1+2` answers: use an editor, or `frost dap`.

## Shipping a game in C#

`frost export desktop GAME.toml --out DIR` compiles a game's C# scripts ahead of time, with
.NET's own Native AOT, into one native library beside the game (`game/csharp/scripts.dylib`),
which the exported player opens: the person who plays the game needs no .NET. The library
holds every script, each compiled as `frost` compiles it (with the project's C# libraries,
statics of its own, and its classes named as it likes), the engine's side of them, and one
runtime under them all; it links only the system's own libraries. Each script in it is
stamped with what it was compiled from (the script, the libraries and the components), and
a player refuses one whose stamp is not its game's: export again after changing a script.
`frost` plays an exported game's library too (`frost run` says so), and compiles a script
again whose stamp is not its own; played on the recording, every C# game of the engine's
fixtures, compiled ahead of time, comes to the very run it comes to compiled by `frost`
(`tests/csharp_aot.rs`).

Every project the export writes is held to .NET's analyzers of what trimming and Native AOT
cannot keep (`IsAotCompatible`, with the trim and AOT analyzers on): what they or the
compiler warn of is said after the library, and the engine's fixtures and its own side
(`Aot.cs`) have no warning. The packages are restored first, from the SDK's own folders
alone, and compiled with `--no-restore`.

Native AOT needs the ILCompiler package for the machine. A .NET SDK that has it beside
itself (Homebrew's does, in its `library-packs` and `packs` folders) is all that is read,
and nothing is fetched. On one that has it not, the export stops (`E0311`), names the
package, and says it is fetched once from nuget.org and kept in frost's cache:
`frost export desktop ... --fetch` allows that. A web export of a game in C# is refused
(`E0482`): no web player runs C#.

## Not yet in C#

- Playing with other machines (`net.*`, `docs/multiplayer.md`): a game in C# is refused
  (`E0543`). Half of what lifts it is done: the clock and unseeded chance are refused as a
  script compiles (`VEN105`). The other half waits: a second kind of CPU playing Vigil in C#
  to the bit (an x86_64 library compiled ahead of time, under Rosetta, which needs one package
  the owner has not yet allowed).

## Fusion on the web

With a `frost` built with `--features dotnet`, `frost export web GAME.toml --out DIR`
accepts C# scripts whose `Step` classes are all marked `[FusionCompile]`. Export runs the
same generator and semantic walk used by desktop C#, then Coldwave's own emitter.
It writes one `game/compiled.wasm` and replaces each exported `.cs` file with its
script description. Source files in your project remain the source of truth.
The SDK is needed on the exporting machine; the browser downloads no .NET runtime.
An unmarked C# Step still refuses web export and names Fusion as the web route.

Both WebGPU and WebGL2 players instantiate that module before starting the game,
sharing the player's memory. The player reserves its first 64 KiB for the module.
Each step lends the world's columns and entity indices directly; boolean columns
use the same byte staging as hosted C#. Kept fields use the same world state as
.NET, so replay and restore include them. The description's schema is checked
before the first call; changed fields require a new export. A checked index or
arithmetic failure stops with the script name and C# line. C# scripts still run
after Luau scripts, in their own project order, on both hosts.

Desktop `frost dev` and headless runs continue executing the marked class under
.NET. Desktop export continues using Native AOT. Web Fusion is an export path;
editing a C# source in an exported page requires exporting and reloading it.
The Fusion module does not call hosted APIs such as `World.Random`, `Input`,
spawning, sound, text or scene changes. Use a Luau companion to prepare columns
for those operations. Heap arrays, `[Engine]` math routines, and `uint` kept
state remain outside this emitter's current game door.

the engine's `csharp/fusion` example is a recorded parity game: every world from step 0 through
60 is held to `checksums.txt`, under .NET and under Node running the exported
door. It includes two scripts, different row orders, entity replacement, input,
booleans, integers and kept `Thing` state. Run:

```sh
nice -n 10 cargo test --offline -j 6 -p frost_remote --features dotnet --lib session::fifth -- --nocapture
```

the engine's `bunnymark-fusion` example carries the original Luau Bunnymark from the unmerged
`demos` branch and a Fusion motion loop. Its companion prepares seeded floor kicks.
Positions, velocities and random state match the original at every recorded step;
whole-world checksums differ because the helper column/component and script names
are also state. See the engine's `RESULTS-fusion.md` example for measurements and their boundaries.
