# C# SDK

`Yumina.Games` is one .NET Standard 2.0 DLL with no third-party dependencies, so it loads next to whatever your game or other mods ship (it carries its own small JSON instead of Newtonsoft.Json). On .NET Framework and Unity Mono, also reference the framework's own `System.Net.Http` (`<Reference Include="System.Net.Http" />`), or the build fails with CS0012.

It runs in Unity (Mono and IL2CPP), Godot 4 .NET, MonoGame / FNA, .NET 6+ and .NET Framework 4.6.2+, and in mod loaders: BepInEx, MelonLoader, SMAPI.

## Set up

```csharp
using Yumina.Games;

var yumina = new YuminaClient(new YuminaOptions
{
    ClientId = "ym_…",                                   // yumina.io → Developer → your game
    TokenStore = FileTokenStore.ForApp("MyGame"),         // DPAPI-encrypted on Windows
    Language = "en",                                      // reply language, optional: "en", "zh-Hans", "ja", or a name
    UserAgent = "MyGame/1.0",
});
```

`BaseUrl` defaults to `https://yumina.io`; change it only if Yumina gives you a test server.

Every method is async and thread-safe. Callbacks (`onText`, events) arrive on a background thread: hand them to your main thread before touching UI or game state. `MainThreadQueue` does it:

```csharp
readonly MainThreadQueue main = new MainThreadQueue();
void Update() => main.Drain();                                        // Unity, MonoGame; Godot: _Process, or CallDeferred

var turn = await npc.SayAsync(text, onText: line => main.Post(() => bubble.Text = line));
main.Post(() => Apply(turn));
```

A game that shows the whole line at once (a dialogue box, not a growing bubble) can pass `onLine` instead: it gets the final line a couple of seconds before the turn returns, while Yumina still checks what the line promised. Show the line then; apply the action only from the returned turn.

## Sign in

```csharp
if (!yumina.IsSignedIn)
{
    // PC: opens the browser; the code comes back to 127.0.0.1.
    await yumina.SignInWithBrowserAsync();

    // Or anywhere: a QR code the player scans with their phone.
    var link = await yumina.StartQrSignInAsync();
    for (int r = 0; r < link.Qr.Size; r++)
        for (int c = 0; c < link.Qr.Size; c++)
            if (link.Qr.IsDark(r, c)) DrawSquare(r, c);        // plus a light border of 4 squares
    ShowText($"{link.VerificationUri}  {link.UserCode}");
    await link.WaitAsync();
}
```

`link.Qr.ToRgba(pixelsPerModule)` gives pixels for a texture if you'd rather not draw squares. In Unity, set `OpenBrowser = Application.OpenURL` in the options.

## Talk

```csharp
var abigail = yumina.Character("abigail", CardRef.Hub(cardId));       // or CardRef.Inline(json)

Turn turn = await abigail.SayAsync(
    "Do you like amethysts?",
    inputs: new { hearts = 6, season = "summer", holding = "an amethyst" },
    allow: hearts >= 2 ? new[] { "give_item" } : new string[0],
    period: $"y{year}-{season}-{day}",
    onText: line => Post(() => bubble.Text = line),
    blocked: hearts < 2 ? new Dictionary<string, string> { ["give_item"] = "you barely know the player" } : null);

turn.Text;                                   // the clean line
turn.Choices;                                // three replies in the player's voice
turn.Outputs["friendship_delta"].AsNumber();
turn.Action;                                 // null, or Id / Params / Accepted / Code / Reason
turn.Raw;                                    // the turn as the server sent it, for your logs
```

`SayAsync` keeps the conversation going; call `EndConversation()` when the player walks away. Send a `[stage direction]` as the text when the game, not the player, speaks: `"[The player hands you a parsnip.]"`.

## Narrow an action for this turn

When what a character can give depends on the moment (what this NPC carries, how much gold is in their purse), pass `Allow` instead of a plain id. The character is shown only these values, and Yumina refuses any other:

```csharp
var carried = npc.Inventory.Select(i => i.Name);                     // e.g. "Bandage", "Rice wine"
var turn = await npc.SayAsync(text, inputs: facts, allow: new object[]
{
    Allow.Action("give_item").Only("item", carried),
    Allow.Action("give_gold").Range("amount", 0, npc.Gold),
    "teach",                                                         // a plain id: as the manifest says
});
```

The manifest still sets the outer bounds: `Only` keeps values inside the manifest's own `enum` (when it has one), `Range` inside its `min`/`max`. If nothing is left (the NPC carries nothing), the action is not offered and the character is told so.

## Apply actions

```csharp
if (turn.Action is { Accepted: true } a)
{
    switch (a.Id)
    {
        case "give_item":
            bool ok = inventory.TryAdd(a.Text("item"));
            abigail.Report(turn, ok, ok ? "the player got it" : "backpack full");
            break;
        case "give_gold":
            player.Gold += (int)a.Number("amount");
            abigail.Report(turn, true);
            break;
    }
}
```

Report every accepted action, applied or not. The character hears it on its next line, and an action that didn't happen doesn't count toward its limits. Reports wait in the `Character` object and go out with the next line; an accepted action that was never reported (the player quit first) counts as done.

A refused action (`Accepted == false`) has a `Code`: `limit`, `not_allowed`, `invalid_params`, `unknown_action`, or `said_not_done` (the line handed something over without asking your game; `Said` holds what). Never apply it, and always handle it: the character's line already promised something, so add a word of narration ("He pats his empty sleeve."). On its next line the character is told it did not happen. `Params` holds what the character asked for.

## Save and load

```csharp
yumina.Memory.Changed += head => currentSave.YuminaMemory = head;   // or read yumina.Memory.Head when saving
yumina.Memory.Load(loadedSave.YuminaMemory);                         // null for a new game
```

Call `Memory.Load` every time a save is loaded (or a new game starts), before the next line. Until then the client still holds the head of whatever was played last, and the characters would remember the wrong timeline.

## Errors

Everything throws `YuminaException` with `Status` and `Code`, plus two helpers: `NeedsSignIn` (show sign-in again) and `NeedsMushies` (open `GetAccountAsync().PlansUrl`).

## Engines and mod loaders

| Where | Notes |
| --- | --- |
| Unity | Drop `Yumina.Games.dll` into `Assets/Plugins`. WebGL builds can't use `HttpClient`: use the JavaScript SDK there. For a mod with no UI of its own yet, start from the ready talk window in the SDK's `examples/unity-imgui` (sign-in, streaming, suggested replies, refusals; you write one adapter class). |
| Godot 4 (.NET) | Reference the DLL from your `.csproj`. Marshal callbacks with `CallDeferred`. |
| BepInEx / MelonLoader | Ship the DLL next to your plugin. Tested in a Unity 2022.3 Mono game. |
| SMAPI (Stardew Valley) | `ProjectReference` or ship the DLL in your mod folder; see the [Stardew example](./example-stardew). |
