Add a Simulation System in C++
Most gameplay belongs in Blueprint: abilities, effects and Sein components cover moving, fighting, building and economy. Write a system in C++ when logic must run on every tick across many entities, such as cooling every overheated unit, and a per-entity ability would be too slow or too awkward.
This guide adds a Heat component and a system that cools it. A designer adds Heat to any unit Blueprint, and the simulation lowers it by 5 per second. Saving, replays, reconnecting and the desync checksum include it with no extra code.
Read Deterministic Simulation first. Everything below follows its rules.
Before you start
Section titled “Before you start”You need a game module in a C++ project that uses the SeinARTS plugin. Your module links against the plugin’s modules and includes their public headers.
1. Add the modules
Section titled “1. Add the modules”In your module’s Build.cs, depend on the math, simulation and game framework modules:
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "GameplayTags", "SeinARTSMath", "SeinARTSSimulation", "SeinARTSGameFramework"});2. Define the component struct
Section titled “2. Define the component struct”A Sein component is a struct. The simulation stores one per entity, saves it and checksums it.
#pragma once
#include "CoreMinimal.h"#include "Components/SeinPayload.h"#include "Types/FixedPoint.h"#include "HeatPayload.generated.h"
USTRUCT(BlueprintType, meta = (DisplayName = "Heat Data", SeinDeterministic))struct MYGAME_API FHeatPayload : public FSeinPayload{ GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Heat") FFixedPoint Heat = FFixedPoint::Zero;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Heat") FFixedPoint MaxHeat = FFixedPoint::FromInt(100);
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Heat") FFixedPoint CoolPerSecond = FFixedPoint::FromInt(5);};Three things make this a simulation struct:
- It derives from
FSeinPayload. - It carries
SeinDeterministic, which lets the editor offer it in pickers and check its fields. - Every number is
FFixedPoint. Afloatordoublemember stops the match from starting. If only visuals read the number, mark the propertymeta = (SeinPresentation)instead.
3. Add an authoring component
Section titled “3. Add an authoring component”Designers add data to an actor with a component. A native one embeds your struct:
#pragma once
#include "CoreMinimal.h"#include "Authoring/SeinActorComponent.h"#include "HeatPayload.h"#include "HeatComponent.generated.h"
UCLASS(NotBlueprintable, ClassGroup = (SeinARTS), meta = (BlueprintSpawnableComponent))class MYGAME_API UHeatComponent : public USeinActorComponent{ GENERATED_BODY()
public: UPROPERTY(EditAnywhere, Category = "SeinARTS", meta = (ShowOnlyInnerProperties)) FHeatPayload Heat;
virtual const UScriptStruct* GetPayloadStruct() const override { return FHeatPayload::StaticStruct(); }
virtual bool WritePayload(FInstancedStruct& Out) const override { Out.InitializeAs<FHeatPayload>(Heat); return true; }};The component shows in the Add menu as Heat, named from the class: the prefix and the word Component are removed. When the actor spawns, the simulation copies the struct into its storage. The component itself does nothing at runtime.
4. Write the system
Section titled “4. Write the system”A system is a class with two functions. One names it and says where it runs. The other runs once per tick.
#pragma once
#include "CoreMinimal.h"#include "Core/SeinTickPhase.h"#include "Math/MathLib.h"#include "Simulation/ComponentStorage.h"#include "Simulation/SeinWorldSubsystem.h"#include "HeatPayload.h"
class FHeatCoolingSystem final : public ISeinSystem{public: virtual FSeinSystemDescriptor DescribeSystem() const override { return FSeinSystemDescriptor::Make( FName(TEXT("mygame.heat_cooling")), ESeinTickPhase::PostTick, 20); }
virtual void Tick(FFixedPoint DeltaTime, USeinWorldSubsystem& World) override { ISeinComponentStorage* Storage = World.GetComponentStorageMutable(FHeatPayload::StaticStruct()); if (!Storage) { return; }
const FSeinEntityPool& Pool = World.GetEntityPool(); Storage->ForEachLiveComponent([&Pool, DeltaTime](FSeinEntityHandle Handle, void* Raw) { if (!Pool.IsValid(Handle)) { return; } FHeatPayload& Component = *static_cast<FHeatPayload*>(Raw); if (Component.Heat > FFixedPoint::Zero) { Component.Heat = SeinMath::Max( FFixedPoint::Zero, Component.Heat - Component.CoolPerSecond * DeltaTime); } }); }};What each part does:
- The name must be unique in the world, ignoring case. A missing or duplicate name stops the match from starting.
- The phase and priority set the order. Phases run in this order each tick: PreTick (effects, cooldowns, match flow), then the AI and the tick’s commands, CommandProcessing, AbilityExecution (abilities, latent actions, production), PostTick (settled state, movement, fog), and FinalObservation, which must not change state. Within a phase, lower priority numbers run first, and ties break by name. Cooling needs no particular slot, so PostTick with priority 20 is fine. The slots the shipped systems use are in
Core/SeinSystemPriority.h. DeltaTimeis one tick as a fixed-point number, from the Simulation Tick Rate. Use it, never the frame time.ForEachLiveComponentvisits entities in ascending slot order, which is the same on every machine. You may change the component you are given. You may not add or remove components of this storage while you walk it.- Check the handle with the pool before you use it.
Destroy an entity from a system with World.Entities().DestroyEntity(Handle). The destroy is deferred, so it is safe in a walk.
5. Host the system
Section titled “5. Host the system”A subsystem owns the system and registers it when the world starts, so you never register by hand:
#pragma once
#include "CoreMinimal.h"#include "Simulation/SeinSystemHostSubsystem.h"#include "HeatCoolingSystem.h"#include "HeatSystemHost.generated.h"
UCLASS()class MYGAME_API UHeatSystemHost : public USeinSystemHostSubsystem{ GENERATED_BODY()
protected: virtual void CreateSystems(USeinWorldSubsystem& Sim, TArray<TUniquePtr<ISeinSystem>>& OutSystems) override { OutSystems.Add(MakeUnique<FHeatCoolingSystem>()); }};Systems must register before the match builds. The subsystem does this when the world initializes. A system registered later invalidates the running match.
If your module can unload while worlds are alive, release the hosted systems first in your module class:
#include "UObject/UObjectIterator.h"
void FMyGameModule::PreUnloadCallback(){ for (TObjectIterator<UHeatSystemHost> It; It; ++It) { if (!It->HasAnyFlags(RF_ClassDefaultObject)) { It->ReleaseHostedSystemsForModuleUnload(); } }}6. Use it
Section titled “6. Use it”- Build the project and open the editor.
- Open a unit Blueprint, choose Add > Heat, and set Heat to
50. - In the unit’s HUD widget, read the value with Get Attribute on the entity view model: Component Type Heat Data, Field Name
Heat. See UI and View Models. - To raise heat, use Apply Field Delta in an ability on the Heat Data field
Heat. Use it, rather than writing the struct, for any field that effects can modify, so the effect’s base value stays consistent.
The determinism rules for system code
Section titled “The determinism rules for system code”| Do | Do not |
|---|---|
FFixedPoint, FFixedVector, FFixedTransform |
float, double, FVector, FMath |
FSeinEntityHandle |
Actor, component or UObject pointers in state |
Walk storage with ForEachLiveComponent |
Iterate a TMap or TSet, or any container whose order is not fixed. Sort keys first if you must |
World.GetSimRandom() |
FMath::Rand, FRandomStream, FGuid::NewGuid |
Tick counts and DeltaTime |
FPlatformTime, FDateTime, GetTimeSeconds |
Read and write inside Tick |
Write from a delegate, a widget or an actor |
| Deferred destroy | Add or remove components of the storage you are walking |
The one-line difference between a working and a desynced cooler:
// Wrong: the frame time differs on every machine.Component.Heat -= 5.f * FApp::GetDeltaTime();
// Right: the fixed tick, in fixed point.Component.Heat -= Component.CoolPerSecond * DeltaTime;Test it
Section titled “Test it”- Value. Play with Heat
50. It reaches0after 10 seconds. - Save. Call Save Match at Heat
25, wait until it is0, then Load Match. Heat returns to25and cools again. See Save and Load a Match. - Network. Host a two-player match in a packaged build or in editor windows with Determinism Check Interval Turns set to
1and Desync Policy set to Abort the Match with a Report. Raise and lower heat for five minutes. No abort means both machines agree. - Replay. Play back the host’s recording. When you stop it, the log reports that every checksum matched. See Record and Play Replays.
Troubleshooting
Section titled “Troubleshooting”- The match does not start, and the log names a system. The name is missing, or two systems share it. Names are not case-sensitive.
- The match does not start, and the log names a struct member. A
float,double, actor reference or delegate sits in simulation data. Use fixed-point types, or mark a numberSeinPresentation. - Heat never changes. The system is not registered: check the host subsystem compiles into a loaded module. A menu map with Auto-Start Simulation off runs no ticks. The component must be added on the Blueprint the match spawns.
- Heat is the same on two machines until one cools faster. Something in the system reads machine-specific data. Compare against the table above, then see Debug a Desync.
GetComponentStorageMutablereturns null. No entity has held the component yet, which is normal, or you are inside a read-only callback, such as a tick-completed delegate. Change state only inTick.- Heat is missing from the Add menu. The class must derive from
USeinActorComponent, carryBlueprintSpawnableComponent, and compile in a module the editor loads.