Skip to content

Persistence

Inventories live in memory and are not persisted by default. To keep them, store them in a database and give them back when the player returns. Depending on the type of server you are building you can do this after the player selected a character in your custom menu or make custom rule depending on what game mode you are running.

There is two APIs that are especially useful for this:

  • Inventory.GetItemData(inventory, item) returns an item as bytes, with everything about it (stats, mods, loot rolls), and Inventory.AddItemData restores it.
  • InventoryChanged carries the same bytes for every stack that changed (Data, at the new Total), so you can keep a database in sync without reading anything back.

These bytes contain a version number and we will try to maintain compatibility with older formats from here on.

Below are two ways to use these APIs. A simple one that saves when a player leaves, and an incremental one that writes every change as it happens.

Deciding how to store the inventory data

A very basic pattern would be to store the inventory data by using the replay UUID to identify unique players. This works well if not in sv_lan true, but be aware that users can join the same server with the same account multiple times. Reject those connections if you don't like that behaviour. This has implications how you store data. It works well if you allow users to join multiple times but you dont allow playing one character at the same time.

This is the very basic "I will only allow one connection per account to my server and I carefully enforce that in events. I know what I'm doing" approach:

static string AccountKey(re.ClientId client)
{
    var uuid = re.cl.IdentityComponent.GetUserUUID(client);
    if (uuid.Length != 0)
    {
        return uuid;
    }

    // If you're in sv_lan true mode, GetUserUUID wont be able to give you a real ID,
    // so you need to handle it in a way that suits you. This will only work
    // if one client connects at most to your dev server
    //
    return "<NotUniqueThisWillGiveYouHeadaches>"
}

Restoring

Restore the player inventory and the stash together when the player's inventory exists (PlayerInventoryCreated), with the game's starter items off:

re.Inventory.SetStarterItems(re.StarterItemsMode.Never);

re.Events.On(
    "PlayerInventoryCreated",
    (re.PlayerInventoryCreated x) =>
    {
        var client = x.Client;
        var inventory = x.Inventory;
        var stash = re.Inventory.GetPlayerStash(client);

        // Into the same ordered queue as the writes (see "Incremental" below)
        //
        Enqueue(() => Restore(client, inventory, stash));
    }
);

static async Task Restore(re.ClientId client, re.InventoryId inventory, re.InventoryId stash)
{
    var key = AccountKey(client);
    foreach (var row in await LoadRows(key))
    {
        var added = re.Inventory.AddItemData(row.Stash ? stash : inventory, row.Data);
        if (added.Status != re.AddItemStatus.Added)
        {
            Console.WriteLine($"Could not restore an item of {key}: {added.Status}");
        }
    }
}

If you also write changes as they happen (below), run the restore through the same queue as those writes. The items the player joins with arrive right after PlayerInventoryCreated as Initial changes. Queued first, the restore reads the stored rows before those changes overwrite them.

The snippets on this page leave out the database calls themselves (LoadRows, SaveRows, Enqueue). Those are plain queries through re.sql or Dapper, as on the Databases page. Design the schema to suite your needs.

Save on leave

Read everything in the ClientDisconnecting handler. The player's inventory and stash are destroyed right after the handlers ran, so copy the data out first, then write it at your own pace:

re.Events.On(
    "ClientDisconnecting",
    (re.ClientDisconnecting x) =>
    {
        var rows = new List<ItemRow>();
        foreach (var (inventory, stash) in new[]
        {
            (re.Inventory.GetPlayerInventory(x.Id), false),
            (re.Inventory.GetPlayerStash(x.Id), true),
        })
        {
            foreach (var entry in re.Inventory.GetItems(inventory))
            {
                rows.Add(new ItemRow(stash, re.Inventory.GetItemData(inventory, entry.ToRef())));
            }
        }

        _ = SaveRows(AccountKey(x.Id), rows); // replace the player's rows with these
    }
);

This is enough for many basic servers, but its not failure resistant. If the server crashes and you have no periodic flushing, all changes since the last save are lost.

Writing incremental changes

To lose nothing, write each change from InventoryChanged. Keep one row per stack, keyed by the owner and the item's identity:

create table if not exists inventory_item (
    owner text not null,     -- e.g. "player:<replay_uuid><character_id>" or "stash:<replay_uuid><character_id>"
    record integer not null,
    seed integer not null,
    counter integer not null,
    quantity integer not null,
    data blob not null,
    primary key (owner, record, seed, counter)
)

Every change tells you the new state of the stack it touched. Write it as:

  • An upsert when Total is above 0
  • A delete when it is 0

A Transfer also touches its source, given by SourceItem, SourceTotal and SourceData:

// Inventory id -> row owner, set in PlayerInventoryCreated:
// owners[x.Inventory.Id] = "player:" + key; owners[stash.Id] = "stash:" + key;
static readonly Dictionary<ulong, string> owners = [];

re.Events.On(
    "InventoryChanged",
    (re.InventoryChanged x) =>
    {
        var writes = new List<Write>();
        foreach (var change in x.Changes)
        {
            if (owners.TryGetValue(change.Inventory.Id, out var owner))
            {
                writes.Add(new Write(owner, change.Item.ToRef(), change.Total, change.Data));
            }

            if (change.Kind == re.InventoryChangeKind.Transfer
                && owners.TryGetValue(change.Source.Id, out var source))
            {
                writes.Add(new Write(source, change.SourceItem, change.SourceTotal, change.SourceData));
            }
        }

        // Applied in order, one event at a time, in a transaction
        //
        Enqueue(writes);
    }
);

Things you need to get right and should test very carefully:

  • Trust Do NOT trust the client. Use approval mode, validate everything a client claims
  • Order Apply the writes in the order the events arrived. Database calls are asynchronous, so queue them and run one batch after the other. The restore goes into the same queue (see Restoring)
  • Owners first PlayerInventoryCreated arrives before the items of a joining player, so map the inventory to its owner there
  • Restore writes back Restored items arrive as changes again, with the identity as the key they overwrite their own rows, so nothing doubles.
  • Leaving keeps the rows InventoryDestroyed for a player's inventory is not a reason to delete anything
  • Destroyed inventories send no Removed When one of your own inventories is destroyed, its items end with InventoryDestroyed alone. Delete its rows there if you no longer need them