Skip to main content
Version: Next (dev)

Data store and saving

Authored tables are read-only. Rows that change while the game runs, such as the inventory, a quest log, unlocked levels or run statistics, go in the data store: a set of writable tables with the same row model, declared per project and saved through the save game system.

The usual shape is a store row keyed by a static row's key. The store table Inventory has a row rifle_mk2 holding the count and durability, and the static Weapons table's rifle_mk2 row holds everything that does not change.

Scopes​

ScopeLives inUse for
SlotA save game. Restored when that save is loaded.Inventory, quest state, currency.
ProfileThe player profile. Survives across save slots.Unlocks, bestiary entries, lifetime statistics.
SessionMemory only. Never written.Statistics for the current run, caches.

Declaring store tables​

  1. Open Project > Data Tables… and switch to the Data Store page.
  2. Press Add table and fill in its fields (below).
  3. Save. The dialog writes RuntimeConfigs/DataStore.ddl. The game reads it at start-up and creates the tables.
FieldDefaultDescription
NamenoneThe name code and scripts use, e.g. Inventory. Unique within the project.
SchemanoneThe Data Schema asset that defines the columns.
ScopeSlotProfile, Slot or Session.
Seed tablenoneOptional. A static table whose rows are copied in when the store is created and whenever the scope is reset: such as the starting inventory or the default unlocks. Columns are matched by name, and the seed table may use a different schema.
Max rows0The most rows the table may hold. 0 means no limit. Adding a row past the limit fails with a warning.
BackendMemoryWhere the rows are kept. See Backends.
Table
{
string %Name { "Inventory" }
string %Schema { "{ 7d1c0a4e-... }" }
string %Scope { "Slot" }
string %Seed { "{ 9e2b41f0-... }" }
uint32 %MaxRows { 0 }
string %Backend { "Memory" }
}

Store tables can also be created from code, for example by a package, with plDataStore::CreateTable(desc, schema). Take the schema from a loaded plDataSchemaResource.

Reading and writing​

#include <GameEngine/DataTables/DataTables.h>

plDataStore& store = plGameApplication::GetGameApplicationInstance()->GetDataTables().GetStore();
plDataStoreTable* pInventory = store.GetTable("Inventory");

pInventory->Set(plMakeHashedString("rifle_mk2"), "Count", 1); // adds the row if it does not exist
pInventory->Increment(plMakeHashedString("potion_small"), "Count", -1);
const plInt32 iPotions = pInventory->Get("potion_small", "Count").ConvertTo<plInt32>();

for (plUInt32 i = 0; i < pInventory->GetRowCount(); ++i)
{
const plHashedString sItem = pInventory->GetRowKey(i);
plDataRowView staticItem = pItems->GetRow(sItem); // the authored row with the same key
}
MemberDescription
Add(key)Adds a row with every cell at its column default. Does nothing if the row exists.
Set(key, column, value)Writes one cell, adding the row when needed. The value is converted to the column's type.
Increment(key, column, delta)Adds a number to a numeric cell, adding the row when needed.
Remove(key)Removes a row. Fails if the key is unknown.
Get(key, column), GetByIndex(row, column)Reads a cell as a variant. Invalid for an unknown row or column.
HasRow, FindRow, GetRowCount, GetRowKeyRow lookup and iteration. Row order is not stable across removals, so iterate by index and look up by key.
Clear()Removes every row.
GetGeneration()A counter that changes on every write. UI can compare it instead of polling values.
GetSnapshot()An immutable copy of the table for queries and worker threads. See Snapshots.
warning

Important

Write to the store from the main thread only. Readers on other threads use a snapshot.

In Development builds the cvar DataStore.ValidateWrites checks every write against the column's range and logs a warning when a value is outside it. The value is still written.

Transactions​

A purchase touches the wallet and the inventory. Group such writes so they apply together or not at all:

store.BeginTransaction();

store.GetTable("Wallet")->Increment(plMakeHashedString("gold"), "Amount", -iPrice);
store.GetTable("Inventory")->Increment(plMakeHashedString("rifle_mk2"), "Count", 1);

if (bPurchaseConfirmed)
store.Commit(); // events for these writes are delivered on the next frame
else
store.Rollback(); // every write since BeginTransaction is undone, and no events are sent

Transactions nest: only the outermost Commit or Rollback takes effect.

Reacting to changes​

Every write queues a plDataStoreEvent. The events of a frame are broadcast once, at the end of the frame, on plDataStore::m_Events. Events of an open transaction wait for its commit.

Event typeSent when
RowAdded / RowRemovedA row was added or removed.
CellChangedA cell changed. The event carries the column, the old value and the new value.
TableClearedClear() was called outside a transaction.
TableLoadedThe table was read from a save game or a profile.

Without code, add a Data Table Events component (category Gameplay / Data Tables) to an object. It turns store events into plMsgDataStoreChanged messages for scripts and components on that object.

PropertyDefaultDescription
TableFilteremptyOnly events of this store table. Empty means every table.
RowFilteremptyOnly events of this row key. Empty means every row.
ForwardToScriptsonOn: the message goes to the nearest event handler up the hierarchy, where scripts receive it. Off: it goes to the owner object's components only.

The message members are Type (the event type as text), Table, Row, Column, OldValue and NewValue.

Saving​

Slot tables: part of the save game​

  1. Register the store with the game state's save game service once, before the first save, for example when the game state activates:

    GetDataTables().RegisterWith(GetSaveGame()); // inside your plGameState

    This hands the save service an adapter under the schema name DataStore.

  2. In the scene, pick one object that always exists, typically the one with the game state logic. Add a Persistence component to it (or use its existing one) and add DataStore to its Schemas list. Only one object should carry it.

  3. Save and load as usual. Every Slot table is written into the save game with that object, and restored when the save is loaded, before the loaded world becomes active. A save that cannot be read fails the load's validation, so the current game is not touched.

When the player starts a new game, call store.ResetScope(plDataStoreScope::Slot). It empties the Slot tables and fills seeded tables from their seed again.

Profile tables: part of the player profile​

// Save: put the store's Profile tables into the profile graph, next to your own profile data.
plAbstractObjectGraph profile;
GetDataTables().WriteProfileGraph(profile);
GetSaveGame().SaveProfile(profileId, "Player 1", profile, expectedRevision);

// Load: loading with an empty slot id reads the profile graph.
GetSaveGame().Load(profileId, plUuid(), [this](const plSaveGameOperation& op)
{
if (op.GetResult() == plSaveGameError::Success)
GetDataTables().ReadProfileGraph(op.GetDocument().m_State);
});

For a new profile, call store.ResetScope(plDataStoreScope::Profile).

Changing the schema between builds​

Saved rows carry their column names. When an older save is loaded into a build whose schema changed, columns are matched by name:

ChangeResult on load
Column addedOld rows get the column's default.
Column removedThe saved values are dropped, with a line in the log.
Column renamed in the Schema tabMatched through the column's Previous names, and the values are kept.
Column type changedEach value is converted to the new type when a conversion exists, otherwise it is left unset.
Store table no longer declaredSkipped, with a line in the log. The rest of the save loads.
warning

Important

Rename columns in the Schema tab rather than deleting and re-adding them, or shipped saves lose the values.

Snapshots​

GetSnapshot() returns an immutable copy of a store table as an ordinary table payload. Everything in C++ runtime works on it: row views, column handles and queries. Take it on the main thread and hand it to a worker. It stays valid for as long as you hold the pointer, and it is cached until the next write.

plSharedPtr<plDataTableData> pRuns = store.GetTable("RunHistory")->GetSnapshot();

// on a worker thread:
plDataRowView best = plDataQuery(pRuns.Borrow()).OrderBy("Score", plDataOrder::Descending).First();

Backends​

The built-in Memory backend keeps a table's rows in memory, sized for thousands of rows. A package can provide another backend by reflecting a plDataStoreBackend subclass, and a store table selects it by entering that type's name in its Backend field. When the named backend is not available, the table falls back to memory and a warning is logged.

note

Note

The Backend drop-down also offers SQLite, for a planned plasma.sqlite package that does not exist yet. A table set to SQLite currently runs on the memory backend.