# Player Sign-in Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/player-sign-in # Player Sign-in Nothing replicates until a player is signed in. Once sign-in succeeds the SDK opens the realtime connection itself, so this is the one step every page in this section assumes has already happened. This page shows the most basic way to do it and nothing more. ## When you touch this Once per project, at startup, before any entity, event, or property. ## Sign in with a password The Game Instance signs in from `Init`, after `Super::Init()` has created its subsystems: bind **On Login** and **On UDP Connection Success** on the Crowdy SDK Subsystem, then call `Login` with an email and password read from `Config/DefaultGame.ini`. The first handler reports the sign-in; the second fires when the connection is up. ```cpp // LanternGameInstance.h #include "Subsystem/CrowdySDKSubsystem.h" #include "LanternGameInstance.generated.h" UCLASS(Config = Game) class ULanternGameInstance : public UGameInstance { GENERATED_BODY() public: virtual void Init() override; // A development account read from Config/DefaultGame.ini. Never ship credentials in a game. UPROPERTY(Config) FString Email; UPROPERTY(Config) FString Password; private: UFUNCTION() void HandleLogin(bool bSuccess, FString Message); UFUNCTION() void HandleConnected(); }; // LanternGameInstance.cpp #include "LanternGameInstance.h" void ULanternGameInstance::Init() { Super::Init(); UCrowdySDKSubsystem* Sdk = GetSubsystem(); Sdk->OnLogin.AddDynamic(this, &ULanternGameInstance::HandleLogin); Sdk->OnUDPConnectionSuccess.AddDynamic(this, &ULanternGameInstance::HandleConnected); Sdk->Login(Email, Password); } void ULanternGameInstance::HandleLogin(bool bSuccess, FString Message) { UE_LOG(LogTemp, Log, TEXT("Login %s %s"), bSuccess ? TEXT("ok") : TEXT("failed:"), *Message); } void ULanternGameInstance::HandleConnected() { // From here on entities register on the wire. UE_LOG(LogTemp, Log, TEXT("Connected to the app")); } ``` Make it the project's Game Instance under **Project Settings, Maps & Modes, Game Instance Class**, and give it a test account in `Config/DefaultGame.ini` (`YourModule` is your game module's name): ```ini [/Script/YourModule.LanternGameInstance] Email=you@example.com Password=your-test-password ``` :::caution[A test account belongs in a config file or a pin default, never in shipped code.] A package stages `Config/DefaultGame.ini`, so an account written there ships with the game. Remove the `Email` and `Password` lines before you package, and sign players in from your own sign-in screen instead. ::: Create a Widget Blueprint with two **Editable Text Box** widgets and a **Button**, and two String variables, `Email` and `Password`, each set from its box's **On Text Committed**. The button's **On Clicked** calls a custom event `SignIn`, whose graph reads the two variables into the latent **Login** node and removes the widget from its parent on `On Success`. Add the widget to the viewport from your Game Mode's **Event BeginPlay** or a level Blueprint at startup, not from a Game Instance's **Event Init**, which runs before the SDK's subsystems exist ([why](../services/authentication.md#signing-in)). [Blueprint snippet: signin-widget, see /bp/unreal-sdk/signin-widget.txt] :::warning[Never print, log, or store the token in the result.] The `Result` a success carries holds the player's `UserID` and a token the SDK already keeps for you. The SDK's own **On Login** event on the Crowdy SDK Subsystem carries a message and no credential, on purpose; keep anything you put on screen the same way. ::: A player who has not yet agreed to the current terms sees a prompt over the game before the sign-in completes, and it finishes on its own once they accept; you add nothing for it. [Authentication](../services/authentication.md#let-the-player-agree-to-the-terms) covers what it shows and how to draw your own. If this machine signed in before, restore instead of asking: call `RestoreSession` first and show the widget only on its error path, as [Authentication](../services/authentication.md#restore-a-saved-session) shows; the connection then comes up exactly as after a `Login`. **Success signal.** The log reads `Login ok`, then `Connected to the app`. From then on `Get UDP Connection State` on the subsystem reads connected, and the rest of the Runtime section applies. Start replicating your pawn only from that moment: **On UDP Connection Success** fires once the server has assigned this client and its readiness wait has elapsed, an update sent earlier is not held for it, and the [Quickstart](../quickstart.md#1-make-your-player-a-crowdy-entity) spawns the pawn from the connected handler for that reason. ## Related - [Authentication](../services/authentication.md): register, magic link, social sign-in, restoring a saved session, sign-out, and the events. - [Quickstart](../quickstart.md): this step in the context of one complete lantern, and the pawn that makes the signed-in player present. - [Connection and reconnect](./connection-and-reconnect.md): what the SDK does once the sign-in succeeds. # Connection and Reconnect Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/connection-and-reconnect # Connection and Reconnect The realtime connection opens after sign-in, re-assigns itself a server when it loses one, and tells the game only when that fails. This page is what a game can read about the connection, what it should react to, and the two knobs that shape the traffic. ## When you need this A connection indicator in the HUD, a "reconnecting" overlay, a decision about what to show while the world is not being updated. Everything else on the view plane depends on the connection and needs nothing from this page. ## The states `UCrowdySDKSubsystem::GetUDPConnectionState()` (Blueprint: **Get UDP Connection State**) returns an `EUDPConnectionState`: | State | Meaning | |---|---| | `Disconnected` | Not connected, and no reconnect in progress. | | `Connecting` | The connection is being opened. | | `Connected` | Up and carrying traffic. | | `Reconnecting` | The connection lost its server and is assigning another. Reported, not acted on: it recovers on its own. | | `GateKeep` (shown as Gate Kept) | The server is gatekeeping this client because the app is full. Nothing retries; the player has already been told. | | `Inactive` | The server released the session because the player sent no gameplay input for the app's idle timeout. Nothing reconnects until the game calls **Request UDP Access**; see [When the player goes idle](#when-the-player-goes-idle). | :::note[Poll it. No delegate is needed for a status indicator.] `GetUDPConnectionState` is a pure node, safe to read every frame. Reserve the events below for the moments you must react to. ::: The events on `UCrowdySDKSubsystem`, all Blueprint-assignable: **On UDP Connection Success** (`OnUDPConnectionSuccess`, an `FOnUDPConnectionSuccess`) whenever the connection comes up, including after a re-assignment, since that is a new session; **On UDP Timed Out** (`OnUDPTimedOut`, an `FOnUDPTimedOut`) when the transport gave up on a re-assignment, with the state at `Reconnecting`; **On UDP Session Inactive** (`OnUDPSessionInactive`, an `FOnUDPSessionInactive`) when the server released an idle player's session, with the state at `Inactive`; **On UDP Address Notify** (`OnUDPAddressNotify`, an `FOnUDPAddressNotify` with `bSuccess` and `GateKeep`) when the server answers the access request. `RequestUDPAccess()` asks for the connection; the [Quickstart](../quickstart.md) never calls it because the sign-in does. In C++, `UCrowdyUDPSubsystem` also carries `OnUDPInactive` (an `FUDPInactive`, not assignable from Blueprint) for the same release. Underneath sits `UCrowdyUDPSubsystem`, whose `GetConnectionState()` is the C++ read that needs no game thread and whose `GetUDPNetworkStats()` returns an `FUDPNetworkStatistics` (bytes and datagrams each way, messages per second, `Ping`, the client-notify counters and loss percentage); `ResetUDPNetworkStats()` zeroes it. Coming up does more than flip the state: the same handler that broadcasts **On UDP Connection Success** joins the reliable-RPC channels, which is what makes the [session channel](./channels.md) "always joined". :::note[Connected means the server is ready for your traffic, not only that the socket is open.] After the server assigns this client, it needs a moment to install the session before it accepts spatial traffic. The SDK waits that out itself: the state stays `Connecting` until the assignment plus the readiness wait have elapsed, and only then does it turn `Connected` and broadcast **On UDP Connection Success**. You never time anything. What the SDK does not do is hold your sends for that moment: an actor update or a spatial event sent while the state is still `Connecting` goes out, or is dropped, and is never replayed once connected; the next replication interval is the recovery. So gate the thing that starts sending, the pawn's spawn or the entity component's activation, on this event or on `Get UDP Connection State` reading `Connected`, as the [Quickstart](../quickstart.md#1-make-your-player-a-crowdy-entity) does. A `Multicast` event is the one exception, queued until the channel bootstrap finishes (see the Gotchas). ::: ## When it drops The low-level connection re-assigns a server on its own; the SDK only surfaces it as `Reconnecting`. A failed re-assignment is where the game hears about it: the SDK marks the state `Reconnecting`, broadcasts **On UDP Timed Out**, and immediately asks for the connection again itself, so a handler that polls the state inside that event reads `Reconnecting`, never `Disconnected`. `Disconnected` is what you read only after that request fails too. If the failure was the app being full, the state is `GateKeep` instead and nothing retries. The timeout that starts a re-assignment is `UDPTimeoutSeconds` in the project settings, and the address family is `UDPProtocol` (`ECrowdyUDPProtocol`: `Auto` takes the IPv4 address, `IPv4` records that choice deliberately, `IPv6` takes the IPv6 address and does not fall back). Both are managed by Crowdy Studio and shown read-only in Project Settings; see [Config Sync](../studio/config-sync.md). `StopNetworkOperations()` reports the session as disconnected for the UI to read; it does not close the socket or interrupt a recovery already under way, deliberately. `ToggleNetworkMessageProcessing()` discards received messages for development. :::caution[StopNetworkOperations changes what the UI reads. It does not stop the connection.] The connection belongs to the transport and recovers on its own. Asking the UI to show a disconnect must not be able to cancel that. ::: ## Reacting to a drop There is no reconnect code to write. The SDK asks for the connection again itself, and the game hears two events: **On UDP Timed Out** when a re-assignment failed and the SDK is opening the connection again, and **On UDP Connection Success** when it is back. Bind both once, in your Game Instance's `Init` after `Super::Init()` in C++ or from your Game Mode's Event BeginPlay in Blueprint, and do the visible thing in each. :::note[Do not call RequestUDPAccess from the timeout handler.] The SDK calls it itself as soon as the event has been broadcast. A second request from the game is a second reconnect in flight for the same client. ::: The lantern village dims every placed lantern while the connection is down and restores them when it is back: `WatchConnection`, called from `Init`, binds the two events to `HandleConnectionLost` and `HandleConnectionRestored`. ```cpp // LanternGameInstance.h void WatchConnection(); UFUNCTION() void HandleConnectionLost(); UFUNCTION() void HandleConnectionRestored(); // LanternGameInstance.cpp #include "EngineUtils.h" #include "Lantern.h" void ULanternGameInstance::WatchConnection() { // The SDK reconnects by itself after a timeout; a game only reacts to the two events. UCrowdySDKSubsystem* Sdk = GetSubsystem(); Sdk->OnUDPTimedOut.AddDynamic(this, &ULanternGameInstance::HandleConnectionLost); Sdk->OnUDPConnectionSuccess.AddDynamic(this, &ULanternGameInstance::HandleConnectionRestored); } void ULanternGameInstance::HandleConnectionLost() { for (TActorIterator It(GetWorld()); It; ++It) { It->Light->SetIntensity(0.f); } } void ULanternGameInstance::HandleConnectionRestored() { for (TActorIterator It(GetWorld()); It; ++It) { It->Light->SetIntensity(5000.f); } } ``` In the Game Mode Blueprint, from **Event BeginPlay**, a **Crowdy SDK Subsystem** getter feeds **Bind Event to On UDP Timed Out** and then **Bind Event to On UDP Connection Success**; the custom events `OnConnectionLost` and `OnConnectionRestored` are theirs. Dimming every lantern needs a loop, which is more than a six-node figure shows, so the graph binds the events and stops. [Blueprint snippet: conn-events, see /bp/unreal-sdk/conn-events.txt] ## When the player goes idle A player who sends no gameplay input (movement, voxel edits, messages, voice, video) for the app's idle timeout has their session released by the server. The timeout is 15 minutes unless the app sets its own in Crowdy Studio (Idle timeout, 60 seconds to 24 hours, or off). This is not a drop: the SDK sets the state to `Inactive`, broadcasts **On UDP Session Inactive**, leaves the Leader type, and does not reconnect. While inactive the player sends and receives nothing. So that an idle player can be released at all, the client goes quiet after 30 seconds without keyboard, mouse, touch or gamepad input, counted from the connection coming up at the earliest: it stops the CrowdyState keyframe heartbeat and its 5-second ping, both of which the server counts as input. Values that change still replicate at once, movement still shows, and the heartbeat resumes on its next interval after the first input. A player who joins near an idle one sees that player's CrowdyState values once they change or the idle player acts again, and while the Leader is idle the same holds for replicated subsystems. `crowdy.net.idlequietseconds` sets the 30 seconds, and 0 keeps the heartbeat and the ping going, which means an idle player is never released. When to bring the player back is your game's decision. Call **Request UDP Access** (`UCrowdySDKSubsystem::RequestUDPAccess()`) when it decides the player is back, for example on their next key press or mouse move, or from a "You were away" screen. Call it only while the player is signed in: signed out it opens nothing and logs a warning. The connection comes back on the same app token, and **On UDP Connection Success** fires as after any reconnect. ```cpp // In Init, beside the drop events. Sdk->OnUDPSessionInactive.AddDynamic(this, &ULanternGameInstance::HandleIdle); void ULanternGameInstance::HandleIdle() { bAwayFromVillage = true; // Show "You were away"; the next input calls Return(). } void ULanternGameInstance::Return() { if (!bAwayFromVillage) { return; } bAwayFromVillage = false; GetSubsystem()->RequestUDPAccess(); } ``` From **Event BeginPlay**, a **Crowdy SDK Subsystem** getter feeds **Bind Event to On UDP Session Inactive**; its custom event sets an `AwayFromVillage` flag and shows the "You were away" widget. The input event that should bring the player back checks the flag, clears it, and calls **Request UDP Access** on the same subsystem. :::note[Nothing reconnects an idle player for you.] A game that never calls **Request UDP Access** after **On UDP Session Inactive** leaves the player offline until they restart. Earlier releases reconnected them automatically, every idle timeout. ::: ## When the server refuses a send A send leaves this client before the server judges it, so a refusal arrives later, on its own. **On Send Refused** on the realtime subsystem (`UCrowdyCppReplicationSubsystem::OnSendRefused`; in Blueprint, **Get Game Instance**, **Get Subsystem (Crowdy Cpp Replication Subsystem)**, **Bind Event to On Send Refused**) fires on the game thread for each one (an `FOnCrowdySendRefused`), with an `FCrowdySendRefusal`: the **Code** and **Code Name**, whether it was a channel message and its **Channel Id**, the **Message Type**, **What** was refused in words and a **Remedy**. The same line goes to the log as a Warning. C++ that reads the bridge's own send errors can turn one into the same struct with `UCrowdyCppReplicationSubsystem::DescribeSendRefusal(Error, OutRefusal)`, which returns false when the server's error names no send this client has on record. The usual one is **Unauthorized** for a permission the player's access tier does not grant. The permissions belong to each access tier of the app: `use_text_chat` for channel messages (party and guild chat, chat rooms, reliable CrowdyEvents such as Multicast events, and CrowdyState sent on a channel) and proximity text, and `use_direct_messages` for a message to one actor (an Owning Client event that carries text, a Host event, and CrowdyState only its owner reads); without them the server refuses every such send from that tier's players. The tiers an app had when these permissions arrived were given both; check a tier's permissions on the web console when its players' sends are refused. A refused channel message can also mean the player is not a member with the send messages permission, and the remedy says both. The server names a refused send only by a one-byte sequence number, so on a busy connection a refusal can be put down to the wrong send. Show it to the player or the log; do not undo game state because of it. ## Bundled sends Outbound replication messages of one network pass are packed into bundle datagrams. `crowdy.net.send.bundle` (default 1) controls it; 0 sends one datagram per message, a diagnostic switch rather than a setting a shipping build needs. The variable is read when a connection opens, so flipping it takes effect on the next connect, not on the live socket. ## Signed inbound bundles Once the connection is up, the transport tells the replication server what this client can read (a `CLIENT_CAPABILITIES` message), and repeats it every 15 seconds so a token refresh or a server-side move, both of which reset the server's record without saying so, never leaves it stale. A server at v0.30.0 or later then packs the notifications it sends you into `MESSAGE_BUNDLE_SIGNED` datagrams: the members inside carry no signature of their own, and one HMAC at the end covers the whole datagram. The transport checks that one signature, drops the datagram if it fails, and delivers the members exactly as it delivers any other notification. Your handlers see no difference; a datagram that used to cost one verification per member costs one. An older server ignores the message and keeps signing every member, which is also what the tagged 2.14.0 plugin receives, since it never announces itself. `crowdy.net.recv.signedbundles` (default 1) is the switch; 0 stops the announcement and keeps the per-member form, for a before-and-after comparison rather than for shipping. Like `crowdy.net.send.bundle` it is read when a connection opens. ## The receive budget Inbound messages are delivered on the game thread, per frame, under two budgets: `crowdy.net.receive.maxmessages` (default 3072) caps how many messages one frame may deliver, and `crowdy.net.receive.maxdrainms` (default 4.0) caps the milliseconds one frame may spend delivering them. Whichever binds first ends that frame's drain and the rest waits for the next frame. The budget covers every message the connection receives, channel notifications and video fragments included, not only actor updates. :::note[Raise the message count first.] If drains keep ending on the time budget instead, delivery is costing more per message than the frame can afford, and the count is not the lever. ::: `crowdy.net.receive.poolactorupdates` (default 1) reuses actor update message objects instead of allocating one per message; `crowdy.net.routes` prints the network router's subscription table; `crowdy.net.trace 1` logs socket, send, and receive activity, and `crowdy.serialize.trace 1` the encode and decode of each payload. `crowdy.serialize.scopes` adds CPU trace scopes inside decode for profiling. ## Gotchas - `Reconnecting` needs nothing from you. Only `Disconnected` after a timeout does. - `Inactive` needs **Request UDP Access** from you, when your game decides the player is back. Do not call it from the **On UDP Session Inactive** handler itself: the player is still away. - `GateKeep` is an answer, not a failure. Retrying against a full app asks a server with no room whether it has room. - Coming up joins the channels. A Multicast event sent before **On UDP Connection Success** is queued and flushed when the bootstrap finishes; see [Channels](./channels.md). - `crowdy.net.send.bundle` and `crowdy.net.recv.signedbundles` changes take effect on the next connect. ## Related - [Channels](./channels.md): what connecting joins. - [Video frames](./video-frames.md): the largest consumer of the receive budget. - [Authentication](../services/authentication.md): the sign-in that requests the connection. - [Console variables](../reference/console-cvars.md). # Entities and Spawning Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/entities-and-spawning # Entities and Spawning An entity is an actor with a `UCrowdyEntityComponent`. A level-placed one needs no spawn call: every client loads it and derives the same NetID. This page is about the other kind, an actor created during play, which one client spawns and every other client rebuilds from a spawn event. For identity policies, NetIDs, and the owner and proxy roles, read [Entities, Identity, and Ownership](../concepts/entities-identity-ownership.md) first. ## When to spawn through the SDK Whenever an actor created at runtime must exist on other clients: a dropped item, a thrown object, a summoned creature. The plain engine `SpawnActor` creates a local actor and tells nobody; the SDK's spawn call creates the same actor and announces it. ## Spawning `UCrowdyEntitySubsystem::SpawnEntity(EntityClass, SpawnTransform, InitialState)` spawns the class locally with a deferred spawn, injects the entity's identity into its component before `BeginPlay`, and broadcasts a spawn event so every client in range spawns the same class as a proxy. The client that called it is the owner; `Role` is `Owner` there and `RemoteProxy` everywhere else. `UCrowdyUtilities::SpawnCrowdyEntity(WorldContextObject, EntityActorClass, SpawnTransform, InitialState)` is the same operation as a static call with a world context pin, which is the form a Blueprint uses. `InitialState` is an `FInstancedStruct` of your own type. It travels with the spawn and lands in the component's `OnCrowdySpawned` event on every client; pass an empty struct when there is nothing to send. The lantern world's runtime spawn is the player arriving with a lantern. `ALanternPlayer` is the player character: a pawn carrying a `UCrowdyEntityComponent` that sends its movement, with PlayerDerived identity, Owned By Player, declared in full on [Continuous state](./continuous-state.md). Once the character knows it is locally owned, `ALanternPlayer::DropLantern` spawns an `ALantern` a short way in front of it, and the new lantern appears there on every client in range. The moment is `OnCrowdyOwnershipAssigned`, not `BeginPlay`: a player pawn spawned during play (`RestartPlayer`) is possessed after its `BeginPlay`, and its Player Derived identity resolves inside that first possession, so `IsLocallyOwned()` is still false at `BeginPlay`. The `AddDynamic` in the block sits in `ALanternPlayer::BeginPlay`, after `Super::BeginPlay()`; the handler fires on the tick after the entity registers, on the first-frame pawn and the runtime-spawned one alike. ```cpp // LanternPlayer.h virtual void BeginPlay() override; UFUNCTION() void HandleOwnershipAssigned(const FGuid& NewOwnerID, ECrowdyRole NewRole, bool bIsLocallyOwned); void DropLantern(); // LanternPlayer.cpp #include "Lantern.h" #include "Utils/CrowdyUtilities.h" void ALanternPlayer::BeginPlay() { Super::BeginPlay(); // A pawn spawned during play registers inside its first possession, after BeginPlay, so the owner answer arrives here. CrowdyEntity->OnCrowdyOwnershipAssigned.AddDynamic(this, &ALanternPlayer::HandleOwnershipAssigned); } void ALanternPlayer::HandleOwnershipAssigned(const FGuid& NewOwnerID, ECrowdyRole NewRole, bool bIsLocallyOwned) { // Each player arrives carrying a lantern; only the owner spawns it, every client then sees it. if (bIsLocallyOwned) { DropLantern(); } } void ALanternPlayer::DropLantern() { const FTransform SpawnAt(GetActorRotation(), GetActorLocation() + GetActorForwardVector() * 150.f); UCrowdyUtilities::SpawnCrowdyEntity(this, ALantern::StaticClass(), SpawnAt, FInstancedStruct()); } ``` Any Actor Blueprint can spawn; nothing on the spawner needs a component. In the player pawn's Blueprint, at **Event BeginPlay**, **Get Crowdy Entity Component** feeds **Bind Event to On Crowdy Ownership Assigned**, whose `Event` pin is wired to a custom event, `OnOwnershipAssigned`, that receives the writer id, the role, and the `Is Locally Owned` flag; the pawn registers inside its first possession, after `BeginPlay`, so this is where the answer arrives. The event's `Is Locally Owned` pin feeds a **Branch** (the owner gate: only the owner spawns), and on the true side **Get Actor Transform** feeds the `Spawn Transform` pin of **Spawn Crowdy Entity**, which takes the entity class and an optional Initial State struct and returns the spawned actor. The class pin in the figure names the sample lantern; pick your own entity class there. A spawner that is not a Player Derived pawn can run the same Branch straight from **Event BeginPlay** with the pure **Is Crowdy Entity Locally Owned** as the condition; only a Player Derived pawn learns its identity after `BeginPlay`. [Blueprint snippet: spawn-entity, see /bp/unreal-sdk/spawn-entity.txt] :::warning[A runtime-spawned entity never consults its Identity Policy or its Owned By.] `SpawnEntity` injects a fresh NetID, `Role = Owner`, and the spawning client's player id before `BeginPlay`, so the component's `IdentityPolicy` and `OwnedBy` settings are not read. Setting Stable on a class you spawn does not give it a stable id, and setting World does not make it the world's; a level-placed `ALanternPost` is how you get both, and [Ownership transfer](./ownership-transfer.md) is how a spawned entity changes hands afterwards. ::: :::danger[Do not spawn an entity with the engine's SpawnActor.] A plain `SpawnActor` never broadcasts the spawn event. The component still registers locally, so the actor looks like an entity on the spawning client and exists nowhere else. ::: :::caution[The spawn event of an entity that replicates movement is a one-shot spatial send, so a client that joins later never receives its `InitialState`.] It reaches the clients within the map profile's **Movement Distance** (eight chunks by default) of the spawn point at that moment and is never replayed. A client that joins afterwards, or comes into range later, still draws an entity that replicates movement from its position updates, but with no spawn event `OnCrowdySpawned` does not fire there. An entity that sends no movement is different: its owner repeats the spawn event every 4 seconds (below), so a late joiner gets the actor, its owner, and `OnCrowdySpawned` with the `InitialState`. Anything a late joiner must see on such an entity belongs in class defaults or in replicated state, and anything that must exist for everyone from the start is level-placed. ::: **Success signal.** On a second client the proxy appears and its `OnCrowdySpawned` fires with `bIsLocallyOwned` false. A single client can only confirm the send: `crowdy.entity.trace 1` logs the registration and the spawn event; `crowdy.rpc.loopback` replays RPC calls, not spawn events, so no proxy appears. ## Destroying Three calls converge on the same path: broadcast a destroy event, then destroy the actor after the component's `DestroyDelay` (0 by default, so immediately). | Call | Where | |---|---| | `UCrowdyEntitySubsystem::DestroyEntity(TargetEntity)` | The subsystem, given the actor. | | `UCrowdyUtilities::DestroyCrowdyEntity(WorldContextObject, TargetEntity)` | The static form with a world context pin; the Blueprint node. `TargetEntity` defaults to self. | | `UCrowdyEntityComponent::DestroyEntity()` | The component, on itself. See [Entity component](./entity-component.md). | On every client `OnCrowdyDestroyed` fires first, with `bIsLocallyOwned` true on the client that called the destroy and false everywhere else; nothing stops a non-owner from destroying an entity. The actor goes after the delay. A `DestroyDelay` above zero is for a dissolve or a fade the actor plays out before it disappears. The entity stops sending updates when the destroy is called, not when the actor goes, and other clients do not draw updates that arrive in the half second after the destroy event, so an update already on its way does not bring the entity back. ```cpp // LanternPlayer.h virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; void PickUpLantern(AActor* Target); // LanternPlayer.cpp #include "Lantern.h" #include "Utils/CrowdyUtilities.h" void ALanternPlayer::NotifyActorBeginOverlap(AActor* OtherActor) { Super::NotifyActorBeginOverlap(OtherActor); // Walking over one of your own lanterns that has gone out picks it up; every client sees it go. const ALantern* Lantern = Cast(OtherActor); if (Lantern && !Lantern->bLit && Lantern->CrowdyEntity->IsLocallyOwned()) { PickUpLantern(OtherActor); } } void ALanternPlayer::PickUpLantern(AActor* Target) { UCrowdyUtilities::DestroyCrowdyEntity(this, Target); } ``` The player picks up a lantern of their own that has gone out: in C++ the character's overlap checks the lantern is unlit and locally owned, then `PickUpLantern` destroys it. The graph is the call alone: from **Event ActorBeginOverlap**, **Destroy Crowdy Entity** takes `Other Actor` on its `Target Entity` pin; the "unlit and yours" check is yours to add in front of it. The removal is visible on every client without any further node. [Blueprint snippet: despawn, see /bp/unreal-sdk/despawn.txt] ## Receiving a spawn on a remote client A remote client that receives the spawn event spawns the named class, injects the identity as `RemoteProxy`, finishes spawning, and broadcasts `OnCrowdySpawned` with the `InitialState` from the event. The event names the spawner's session as the writer and its signed-in user as the owner user, so **Get Owner User ID** on the proxy reads the spawner's user; every client must run the same SDK version to read it. The event carries the class path, so a class that is not loaded yet is streamed in and spawned when it arrives; a destroy event that lands during the load cancels the spawn. If the class ships without a `UCrowdyEntityComponent`, the SDK adds one so the lifecycle callbacks have a home. That actor is the one players see: the actor pool draws it rather than a pooled copy, so whatever your `OnCrowdySpawned` handler set on it stays. When the entity's first update arrives before its spawn event, the pool draws it at once and the spawn event then hands that actor its `InitialState` and its owner instead of spawning a second one. Either way `OnCrowdySpawned` fires once per entity on each client. On a map drawn with the Crowdy Mass Rendering Backend, Mass is the only body of an entity that replicates movement: its crowd row, and the near-tier shell when it is close to the camera. Its spawn event spawns no actor of its own, so `OnCrowdySpawned` does not fire for it there. Its `InitialState` lands in the row instead, through the same Crowdy State fragment fields its replicated properties use: each property of your `InitialState` struct that a field registered with `RegisterStateFragmentField` names, declared as the type that field reads, reaches that field's ingestor (see [Add your own crowd data](../mass/add-your-own-crowd-data.md#land-spawn-data-on-the-row)). Other properties are dropped. An entity that sends no movement sends no updates, so Mass never draws it and it keeps the actor its spawn event makes, with `OnCrowdySpawned`, on every map. :::note[The spawn and destroy payloads are wire format, not something you build.] `FCrowdyEntitySpawnEvent`, `FCrowdyEntityDestroyEvent`, and the registry's `FCrowdyEntityRecord` are Blueprint-visible types because they cross a delegate, but you never construct one. `InitialState` is the only payload you author. ::: ### A moving entity can appear with no spawn event at all An entity that replicates movement (see [Continuous state](./continuous-state.md)) streams position updates, and each update carries the class id and the state struct type. The `UCrowdyActorManager` resolves the class from that (`RegisterStateClass` is filled in for you by each entity component's `BeginPlay`) and asks the rendering backend to draw a proxy, so a moving entity shows up on a client that joined late without any spawn round trip. An entity that sends no movement, spawned with `SpawnEntity`, sends no updates, so its owner repeats the spawn event instead: every 4 seconds while a client owns it, that client sends the spawn event again, from where the entity is now, naming its owner and carrying its `InitialState`. A client that joins later builds the entity from a repeat exactly as if it had seen the spawn, and its `OnCrowdySpawned` fires there. A client that already has the entity ignores repeats, and `OnCrowdySpawned` never fires twice. A repeat costs about 280 bytes plus your `InitialState`: about 70 bytes per second of upload per entity on its owner, and the same in download for each client within the map's **Movement Distance**. A spawn event for an entity destroyed less than 10 seconds earlier is ignored, so a repeat already on its way cannot bring it back; an owner that never received the destroy keeps repeating, and the entity reappears after those 10 seconds. An entity that sends no movement, placed in the level or registered with `RegisterStaticEntity`, sends nothing. :::warning[Preloaded Entity Classes is empty by default, and an observer on this path needs it.] This path resolves the class by id against loaded classes; a spawn event carries the class path and loads it for you, this does not. The startup scan walks loaded classes, and a Blueprint entity class that nobody on this client has spawned yet is not loaded, so an observer that meets it first over the network cannot name it. The actor manager warns `cannot resolve to a loaded class ... Preload the entity class or give it a ClassIDOverride` and the entity stays undrawn. List every Blueprint entity class a client can be shown before it spawns one itself under **Project Settings, Plugins, Crowdy SDK, Replication, Preloaded Entity Classes** (`PreloadedEntityClasses` on `UCrowdySDKDeveloperSettings`). Classes already loaded for another reason need no entry, and a duplicate costs nothing. ::: ## The actor tracker Inbound actor updates arrive at `UCrowdyActorTracker`, a world subsystem the actor manager listens to. Its settings live on the `ActorManagement` struct of the [map profile](./map-profile.md) (`FCrowdyActorManagementConfigStruct`), shown as the profile's **Remote Entities** group. Everything but the switch, the backend and the interpolation delay sits under its **Advanced** row: ![The map profile with Actor Management expanded and an Actor Pool Backend Config assigned: the tracker settings and the backend selection](/img/unreal-sdk/actor-config.png) The shipped default profile leaves **Backend Config** at None and runs on the built-in one; the [map profile page](./map-profile.md#create-the-asset) shows that state and when to assign your own. | Field | Default | Effect | |---|---|---| | `bUseCrowdyActorTracker` (**Draw Remote Entities**) | on | Off means no tracker, no actor manager, and no backend on this map. | | `bDispatchUpdatesOnGameThread` | off | Also broadcast each update batch to `OnUpdatesGameThread` for a Blueprint listener. | | `bEnableOwnerTracking` | on | Track the local player's own actor echo as well: the reflection the [Quickstart](../quickstart.md#2-see-yourself) uses as proof that the server is receiving you. | | `ActorTimeoutThreshold` (**Actor Timeout**) | 12 s | Seconds of silence before an entity is dropped on a guess. The server announces a real departure about five seconds after the last update, so this is the fallback. | | `MaxTrackedActors` | 4096 | How many network-received actors may be tracked at once. A bound on forged ids, not a performance setting; set it above the largest crowd you intend to show. | | `MaxUpdatesPerBatch`, `MaxBatchWaitTime` | 100, 5 ms | How updates for not-yet-seen entities are batched off the game thread. | | `InterpolationDelayMs` | 100 ms | How far behind the server's clock the actor pool draws remote entities. Longer hides late updates but shows everyone further in the past; below one send interval (100 ms at the default 10 Hz) entities overshoot and snap back. Mass-drawn rows ignore it. See [Rendering backends](./rendering-backends.md). | The tracker's events, all on the game thread: `OnRemoteEntityAppeared` (an id seen for the first time, with its `InitialState`), `OnRemoteEntityTimedOut` (this client heard nothing for `ActorTimeoutThreshold`), `OnRemoteEntityLeft` (the server said it is gone, with an `FCrowdyActorLeft` carrying the `ECrowdyActorLeftReason`: `Stale`, or `SessionReleased` when the server ended that actor's session), and `OnRemoteEntityLeftAnnounced` (every departure, including one for an actor this client never held, for code keeping its own per-sender state). Whichever of timed-out and left reaches an actor first is the only one that reports it. The delegate types are `FOnActorSpawnRequested`, `FOnActorTimeoutRequested`, `FOnActorLeftReported` (used by both departure events), and `FOnActorUpdateGameThreadBatch`. `ToggleOwnerTracking` and `ToggleBroadcastUpdatesToGameThread` change those two settings at runtime. `Configure` does not: it applies only before the tracker starts, which is before any Blueprint can call it, so on a running tracker it logs a Warning and changes nothing, and it has no Blueprint node. Set the limits in the [map profile](./map-profile.md) or in the Crowdy SDK developer settings instead. `FCrowdyActorUpdate` is the batch element, carrying `PayloadTypeID`, the payload type id the sender's state blob led with, kept even when no struct is registered for it on this client. `crowdy.replication.tracker.maxgatheredupdates` caps the backlog of gathered updates for actors already on screen. You do not normally touch any of this: the actor manager and the [rendering backend](./rendering-backends.md) consume it for you. ## Looking entities up `UCrowdyEntitySubsystem` is the registry: - `FindEntity(NetID)` returns the actor or null, and `FindEntityID(Actor)` is the reverse lookup. - `IsLocallyOwned(NetID)` is true when this client writes the entity, the same answer as the component's `IsLocallyOwned` (see [The Leader](./leader.md#who-writes-what)). That is when the record names the local player and its role says this client simulates it, or when it is a replicated subsystem and this client is the Leader. A World entity answers false everywhere, and so does a record that contradicts itself. - `GetLocalPlayerID` and `GetAppWriterID` (the Leader) read the two ids everything else is compared against. `SetLocalPlayerID` exists for a game that manages the player id itself; the session normally seeds it for you. `GetLocalUserID` is the signed-in user's id, 0 while signed out, and `FCrowdyEntityRecord::IsOwnedByUser(OwnerUserID, LocalUserID)` compares an owner user with it (0 matches nobody). `IsLocalSender(SenderID)` is true for this client's actor id and the ones it held earlier in this world, so an echo of what it sent before a sign-in changed its id still reads as its own. - `OnLocalPlayerRekeyed` (`FOnCrowdyLocalPlayerRekeyed`, C++ only) fires once the local player's actor id has changed and the registry has re-keyed, with the previous id, the new id, and an `FCrowdyRekeyedID` (`PreviousID`, `NewID`) for each participant salted with the player's id whose id changed too. Bind it if you kept one of those ids. - `OnEntityRegistered` and `OnEntityUnregistered` (`FOnCrowdyEntityRegistered`, `FOnCrowdyEntityUnregistered`) fire with the NetID as records come and go. - In C++, `GetEntitiesByOwnerUser(UserID)` lists the actors whose owner user is that user, from any of its sessions, and nothing for 0. The Blueprint-friendly statics on `UCrowdyUtilities` wrap the same registry: `GetCrowdyEntityID`, `GetCrowdyEntity`, `GetCrowdyEntityWriterID` (the writing session's actor id), `GetCrowdyEntityOwnerUserID` (the owner's user id, 0 when unknown), `IsCrowdyEntityOwnedByLocalUser`, `GetCrowdyEntityRole` (an `ECrowdyRole`), `GetAllCrowdyEntitiesByOwner` (by writer id), `CrowdyIsEntityRegistered`, and `GetLocalPlayerEntityID`. ## Gotchas - `IsLocallyOwned` means two different things: on the subsystem it takes a NetID and asks the record; on the component it takes nothing and asks whether this client is the entity's authority, which no client is for a World entity. See [Entity component](./entity-component.md). - A spawned entity is owned by its spawner, full stop. To hand it over, use [Ownership transfer](./ownership-transfer.md). - `InitialState` reaches `OnCrowdySpawned` once on each client that receives the spawn event, on the actor that client draws. A late joiner receives it for an entity that sends no movement (from a repeat) but not for one that replicates movement. On a Mass map the latter has no actor there, and its `InitialState` reaches the row's registered Crowdy State fields instead. - Two unrelated participants can derive the same NetID (a NetID has 32 bits of real entropy). The incumbent keeps it and the newcomer is refused with a log line; a system that binds state to an id should register through `TryRegisterEntity` and give up its claim when the `ECrowdyEntityRegistration` it returns is `RefusedIdHeldByLiveParticipant` (or `RefusedInvalidNetID` for a record with no usable id) rather than `Registered`. - `UHelperFunctions` has the id helpers a custom identity scheme would reach for: `GetDeterministicID(Seed)` turns a seed into the same `FGuid` on every client, with those same 32 bits of entropy (a player's own id is not one: it is random, new at each sign-in, and kept by the game session), and `GetNewID` and `GetNewUUID` mint random ones. Prefer the component's identity policies; these exist for code that already has a seed. ## Related - [Entities, Identity, and Ownership](../concepts/entities-identity-ownership.md): NetIDs, policies, owner and proxy. - [Entity component](./entity-component.md): every callable and event on the component. - [Ownership transfer](./ownership-transfer.md): moving an entity to another player. - [Rendering backends](./rendering-backends.md): how a proxy is drawn, and the pooled-proxy gotchas. - [Continuous state](./continuous-state.md): Replicate Movement and the executor. # Entity Component Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/entity-component # Entity Component `UCrowdyEntityComponent` is the one component the SDK tracks an actor by. It registers the actor in the entity registry, hands out its identity, optionally feeds the continuous state channel, and raises the lifecycle events. This page is the reference; the concepts are on [Entities, Identity, and Ownership](../concepts/entities-identity-ownership.md). ## Getting the component In C++ the actor usually holds the pointer it created in its constructor. From anywhere else, `UCrowdyUtilities::GetCrowdyEntityComponent(Actor)` (Blueprint: **Get Crowdy Entity Component**, `Actor` defaults to self) resolves it GAS-style: if the actor implements `ICrowdyEntityComponentProvider` its answer is used, otherwise `FindComponentByClass`. Implement the interface when the component lives on a child actor or is chosen at runtime; it is deliberately not a node you call directly. ![The entity component's Details panel](/img/unreal-sdk/entity-component-details.png) ## Settings All `EditAnywhere`, so a constructor, a Blueprint's Class Defaults, or a placed instance can set them. | Setting | Default | One line | |---|---|---| | `ReplicateMovement` (`ECrowdyReplicateMovement`) | Auto | Auto is on for a pawn with a movement component (a Character, for one) and off for anything else. On streams the `StateExecutor` snapshot every replication interval, so a plain actor that should move must set it. Off sends no movement. Unrelated to ownership, events and Crowdy State, which work either way. Auto resolves by class and placement only. | | `IdentityPolicy` (`ECrowdyIdentityPolicy`) | Stable | Stable, PlayerDerived (random, kept by the game session for one sign-in), or Random. Read only when the actor resolves its own identity; a runtime spawn ignores it. | | `OwnedBy` (`ECrowdyOwnedBy`) | Auto | Who writes the entity. Player: this client owns it (`Role = Owner`). World: no client writes it (`Role = WorldOwned`); it applies to an actor placed in the level, and one spawned during play belongs to its spawner. Leader: whichever client [leads](./leader.md#an-npc-the-leader-simulates), placed or spawned. Auto: World when placed, Player when spawned, by class and placement only. Read back in Blueprint as **Get Owned By**. | | `StateHeartbeat` (`ECrowdyStateHeartbeat`) | Inherit | Inherit follows the map profile's keyframe; Off never emits a keyframe for this entity. On-change replication is unaffected. | | `bAutoApproveOwnershipRequests` | off | The current authority grants any transfer request at once instead of raising `OnOwnershipRequested`. | | `StateExecutor` (`UActorUpdateExecutor`) | none | Only when movement is replicated. Builds the snapshot; unset means the SDK's transform-only default. | | `bAutoRegister` | on | Only when movement is replicated. Join the continuous channel at `BeginPlay`; off means you call `StartReplication` yourself. | | `DestroyDelay` (float) | 0 | Seconds between `OnCrowdyDestroyed` and the actor being destroyed. | ## Callables Category **Crowdy SDK, Entity Component** in the Blueprint palette. | Function | One line | |---|---| | `GetNetID()` | The entity's shared id, as an `FGuid`. | | `GetWriterID()` | The actor id of the session that writes the entity (Blueprint node **Get Writer ID**, formerly **Get Owner ID**); invalid for a World (`WorldOwned`) entity. | | `GetOwnerUserID()` | The user id of the player who owns the entity, 0 when unknown: the signed-in user for an entity this session writes, the user its writer claimed for another client's, and 0 for another player's avatar (**Resolve Actor Owner** answers it). A label for display, never a write check. | | `IsOwnedByLocalUser()` | True when the signed-in user owns the entity, from this session or another of theirs. In a second session of the same account it is true while `IsLocallyOwned()` is false. | | `GetRole()` | `ECrowdyRole`: `Owner`, `RemoteProxy`, `WorldOwned`, or `None` before registration. | | `IsLocallyOwned()` | True when this client writes the entity, which means it owns it. False on every client for a World entity. The question to ask before owner work. **Is Crowdy Entity Locally Owned** asks the same of any actor or replicated subsystem without fetching the component. | | `ReplicatesMovement()` | Blueprint node **Replicates Movement**. True when this entity sends its movement, with Auto resolved. `ReplicatesMovementFor(ActorClass)` asks the same of a class's component template, which has no owner. | | `GetStateHeartbeat()` | The setting above, read back. There is no getter for `IdentityPolicy`. | | `StartReplication()`, `StopReplication()` | Join or leave the continuous channel. Meaningful for an entity that replicates movement and this client owns; `bAutoRegister` calls the first one for you. | | `MarkStateDirty(PropertyName)`, `MarkAllStateDirty()` | Schedule one, or every, `CrowdyManualDirty` property to ship on the next replication tick. See [Crowdy State: marking state from outside the actor](./crowdy-state.md#marking-state-from-outside-the-actor). | | `DestroyEntity()` | Broadcast the destroy event and destroy the owner after `DestroyDelay`. The same path as the subsystem's `DestroyEntity(Actor)` and `UCrowdyUtilities::DestroyCrowdyEntity`. | `IsLocallyOwned()` here takes no argument and answers for the client that writes the entity; `UCrowdyEntitySubsystem::IsLocallyOwned(NetID)` answers a narrower question about the record's writer id. Do not treat them as interchangeable. ## Events | Event | Signature | When | |---|---|---| | `OnCrowdySpawned` (`FOnCrowdyEntitySpawned`) | `InitialState`, `bIsLocallyOwned` | Runtime-spawned entities only: fired by `SpawnEntity` on the spawner and by the spawn event on every proxy, with the spawn payload. A level-placed entity never receives it; bind `OnCrowdyOwnershipAssigned` there instead. | | `OnCrowdyDestroyed` (`FOnCrowdyEntityDestroyed`) | `bIsLocallyOwned` | On every client when the entity is torn down, before the delay. | | `OnCrowdyOwnershipAssigned` (`FOnCrowdyOwnershipAssigned`) | `NewOwnerID`, `NewRole`, `bIsLocallyOwned` | Once the entity knows its owner, on the tick after registration (so a bind in `BeginPlay` still gets it), and again on every reassignment. `NewOwnerID` is the writer id, invalid for a World entity. | The example binds all three in `ALantern::BeginPlay`, after `Super::BeginPlay()`; the three `AddDynamic` lines in the block go there. A lantern the player drops at runtime is the kind of entity that receives all three: the spawn path announces `OnCrowdySpawned` right after `BeginPlay`, on the owner and on every proxy, so a bind made there is in place in time. A level-placed post never gets the spawn event; on it only the destroy and ownership handlers ever run. The light shows on spawn, hides on destroy, and brightens or dims as the answer to "do I own this" arrives. ```cpp // Lantern.h UFUNCTION() void HandleSpawned(const FInstancedStruct& InitialState, bool bIsLocallyOwned); UFUNCTION() void HandleDestroyed(bool bIsLocallyOwned); UFUNCTION() void HandleOwnershipAssigned(const FGuid& NewOwnerID, ECrowdyRole NewRole, bool bIsLocallyOwned); // Lantern.cpp CrowdyEntity->OnCrowdySpawned.AddDynamic(this, &ALantern::HandleSpawned); CrowdyEntity->OnCrowdyDestroyed.AddDynamic(this, &ALantern::HandleDestroyed); CrowdyEntity->OnCrowdyOwnershipAssigned.AddDynamic(this, &ALantern::HandleOwnershipAssigned); void ALantern::HandleSpawned(const FInstancedStruct& InitialState, bool bIsLocallyOwned) { // Spawned entities only: the spawn path announces it right after BeginPlay, on the owner and on every proxy. Light->SetVisibility(true); } void ALantern::HandleDestroyed(bool bIsLocallyOwned) { Light->SetVisibility(false); } void ALantern::HandleOwnershipAssigned(const FGuid& NewOwnerID, ECrowdyRole NewRole, bool bIsLocallyOwned) { Light->SetIntensity(bIsLocallyOwned ? 8000.f : 2000.f); } ``` In the spawned lantern's Blueprint, at **Event BeginPlay**, **Get Crowdy Entity Component** feeds **Bind Event to On Crowdy Spawned**, whose `Event` pin is wired to a custom event, `OnLanternSpawned`, that receives the spawn payload and the ownership flag; its body calls **Set Visibility** on `Light`. The other two events bind the same way from the same getter. [Blueprint snippet: ec-on-spawned, see /bp/unreal-sdk/ec-on-spawned.txt] ## Asking a different question than IsLocallyOwned The [Quickstart](../quickstart.md) and the identity page both branch on `IsLocallyOwned()`. The accessor family answers finer questions: `GetRole()` distinguishes the owner from a World entity (`WorldOwned`, which no client writes by default) from a proxy, which the boolean cannot. The example grades the post's light by role. Four more `UCrowdyUtilities` nodes ask role questions without fetching the component: `CrowdyIsRemoteProxy(Entity)` (**Crowdy Is Remote Proxy**) is true when the entity's role is `RemoteProxy`, and `IsCrowdyEntityPlayerControlled(TargetActor)` (**Is Crowdy Entity Player Controlled**) is true for an actor with an entity component that replicates movement or a registered remote-proxy record; `SwitchCrowdyIsRemoteProxy` and `SwitchIsCrowdyEntityPlayerControlled` are the same two answers as exec pins. ```cpp // LanternPost.h void ShowRole(); // LanternPost.cpp void ALanternPost::ShowRole() { // A post a player spawned is Owner there and RemoteProxy elsewhere; a level-placed post is WorldOwned everywhere. switch (CrowdyEntity->GetRole()) { case ECrowdyRole::Owner: Light->SetIntensity(8000.f); break; case ECrowdyRole::WorldOwned: Light->SetIntensity(4000.f); break; default: Light->SetIntensity(1000.f); break; } } ``` The generated graphs branch on booleans, so the three-way role grading of the C++ half is shown as its two-way half: **Get Crowdy Entity Component**, **Is Locally Owned**, a **Branch**, and **Set Intensity** to 8000 on `Light` for the owner. For the full grading in Blueprint, replace the Branch with a **Switch on ECrowdyRole** fed by **Get Role**. [Blueprint snippet: ec-is-owned, see /bp/unreal-sdk/ec-is-owned.txt] ## The two RPC receivers on the component `RequestOwnership_Implementation(RequesterID, RequesterUserID)` and `GrantOwnership_Implementation(NewWriterID, PreviousWriterID, NewOwnerUserID)` are `CrowdyEvent` functions with `CrowdyRecipient = "Multicast"` that carry [ownership transfer](./ownership-transfer.md) over the session channel. Call the static `UCrowdyOwnershipTransfer` nodes instead of these; `GrantOwnershipTo(NewWriterID, NewOwnerUserID)` is the C++ entry the static nodes funnel through. :::caution[These two events are Multicast with no CrowdyChannel on purpose. Do not re-declare them with a channel.] They ride the app's session channel, which the SDK always joins, so a request or a grant reaches every client. Re-declared on a channel of their own they would reach that channel's members instead of the entity's audience. Ownership on this plane is a convention in any case; the enforced kind lives in your server code, on the [truth plane](../concepts/two-planes.md). ::: ## Advanced: the static identity helpers C++ only, pure, and the same functions the SDK's own identity resolution calls. Useful when writing custom identity code; not needed otherwise. | Static | What it answers | |---|---| | `ResolveOwnedBy(OwnedBy, bIsLevelPlaced)` | The owner identity resolution applies: Player, World or Leader, never Auto. Auto is World for an actor placed in the level and Player for one spawned during play. A runtime spawn is always its spawner's. | | `ResolveReplicatesMovement(ReplicateMovement, bIsPawnWithMovement)` | Whether movement is sent, never Auto. Auto is On for a pawn with a movement component and Off for anything else. | | `DeriveAuthority(Ownership, LocalPlayerID, OutRole, OutWriterID)`, `ResolveEffectiveOwnership(AuthoredOwnership, bIsLevelPlaced)` | The role, writer id and applied ownership for an `ECrowdyOwnership`, the enum `RegisterParticipant` takes. | | `DeriveOwner(ResolvedOwnedBy, LocalPlayerID, OutRole, OutWriterID)` | The role and writer id a resolved owner produces. | | `ResolveActorInstanceGuid(Actor)` | The engine's per-placement guid, the Stable identity seed. | | `ShouldUsePlacementGuid(bIsLevelPlaced, bHasInstanceGuid)`, `SelectPlacementGuid(AtRegister, Live)` | When that guid may be used, and why the snapshot taken at `OnRegister` wins over a live read in a cooked build. | | `ComputeStableNetID(bOutUsedPathFallback)` | The Stable NetID for this actor, and whether it fell back to hashing the path. | | `DoesOwnershipMatch(OwnerRole, OwnerNetID, TargetRole, TargetWriterID)` | The ownership test behind `UCrowdyUtilities::DoesCrowdyEntityOwn`: the target's writer id is the owner's NetID, a session question, so another session of the same user does not match. A World entity on either side never matches. | | `ClassifyPlayerDerivedIdentity(Facts)`, `DescribePlayerDerivedIdentity(Verdict)` | Which condition made PlayerDerived fall back to Random, and the sentence the warning uses. | | `ShouldReportHostOwnedAutoRegister(bInReplicatesMovement, bInAutoRegister, Role)` | The authoring diagnostic for a World (`WorldOwned`) entity that replicates movement and so ends `BeginPlay` sending nothing. | | `GetClassID()` | The class hash carried on spawn events. | `InitIdentity`, `AssignPooledIdentity`, `ClearIdentity`, `MarkPooledDormant`, and `IsPooledDormant` are the injection points the entity subsystem and the actor pool use; game code has no reason to call them. ## Gotchas - `OnCrowdyOwnershipAssigned` is announced on the tick after registration, deliberately, so a bind in the actor's own `BeginPlay` is not too late. - A placed entity that replicates movement, Owned By World (or Auto), with `bAutoRegister` on leaves `BeginPlay` sending nothing: auto-register only starts the channel for an entity this client owns outright. The log says so once per component. - `DestroyEntity()` exists in three places with three signatures and one behaviour. Use whichever you already hold a reference for. - The enum getters return the setting, not a live derivation. `GetRole()` is the live answer. ## Related - [Entities, Identity, and Ownership](../concepts/entities-identity-ownership.md): what the settings mean. - [Entities and spawning](./entities-and-spawning.md): the subsystem's spawn, destroy, and lookup calls. - [Ownership transfer](./ownership-transfer.md): the static nodes that replace calling the two receivers. - [Crowdy State](./crowdy-state.md): the properties `MarkStateDirty` serves. - [Continuous state](./continuous-state.md): `ReplicateMovement`, `StateExecutor`, and `bAutoRegister`. # RPC Events in Blueprint Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/rpc-events-blueprint # RPC Events in Blueprint A Blueprint sends and receives CrowdyEvents with no C++: tick one checkbox on a Custom Event, choose a recipient, and call the event by name. The body of the event is the receiver. ## When to use one The same cases as [RPC events in C++](./rpc-events-cpp.md): a moment other clients should see, not a value a late joiner needs. The Blueprint needs a **Crowdy Entity Component** on the actor (or to be a [replicated subsystem](./replicated-subsystems.md)); a Custom Event on an actor without one has no entity to route by. ## Mark the event Select the Custom Event node. Its Details panel gains a **Crowdy SDK** category with a **Crowdy Replicates** checkbox; this is the node's own Details panel, not the actor's. ![The Crowdy Replicates checkbox in a Custom Event's Details panel](/img/unreal-sdk/bp-crowdy-replicates-checkbox.png) Ticking it writes the `CrowdyReplicates` marker onto the event and clears any Unreal replication flag on the node, since the two cannot combine. A status line under the checkbox tells you at once whether the signature is accepted: green `Replicated (N parameters)`, or a red problem naming the parameter, using the same validator the C++ scan runs. Old assets marked with the earlier spelling `CrowdyReplicate` are still recognised. :::warning[Crowdy Replicates cannot combine with Unreal's own replication, and the event must be Public.] The status line reads `Disable Unreal replication - it cannot combine with Crowdy replication`, or `Set Access Specifier to Public - Crowdy Replicates cannot be private`, until you fix the node. A private or protected event is refused because the SDK invokes it from outside the class. ::: :::caution[Toggling the checkbox needs a recompile before it takes effect.] The compiler splices a dispatch gate into the head of a marked event at compile time. Until you press Compile the log says `Custom event 'X' Crowdy Replicates ... Recompile to activate.` and the event still runs locally only. ::: The lantern's `Sparkle` event is the Blueprint twin of the C++ page's `Sparkle_Implementation`, with the style struct flattened into two inputs, `Color` and `Intensity`. Its body is the receiver: **Set Light Color** and **Set Intensity** on `Light`, each fed by a **Get Light** node. The graph below is the whole example; the Details panel of its event node is where Crowdy Replicates is ticked and Spatial Multicast is chosen. [Blueprint snippet: rpc-mark-event, see /bp/unreal-sdk/rpc-mark-event.txt] ## Pick the recipient Once Crowdy Replicates is ticked, three more rows appear. **Recipient** is the `ECrowdyEventRecipient` the C++ page uses, with the same default: ![The Recipient dropdown on a replicated Custom Event](/img/unreal-sdk/bp-recipient-dropdown.png) - **Spatial Multicast** (the default): everyone in range, over the chunk-based path, thinned by decay. - **Multicast**: every member of the app's session channel, whatever the distance, over the channel transport. - **Owning Client**: only the target entity's owner; another client's call becomes a request to that owner. Every client near the target receives the parameters. An event with a text parameter stays a direct message. There is no Host recipient. An event saved with one reads as **Owning Client** and logs a warning that names it. **Decay Rate** and **Replication Distance** sit below the recipient and are greyed out unless the recipient is Spatial Multicast, because only the spatial path reads them. **Channel** appears only for Multicast: type a channel name, or press **Pick** to choose from the app's channels, which the picker fetches live from Crowdy Studio when you are signed in there; free text always works. **Is A One-Shot Action** appears only once a map profile assigned in **Project Settings, Plugins, Crowdy SDK** (a **Map Profiles** entry or the **Default Profile**) selects a backend that draws crowd rows. A project that uses only the actor pool never sees it. See [Play poses and one-shot actions](../mass/play-poses-and-one-shot-actions.md). :::warning[A channel you type here must already exist. Only the session channel is created for you.] A typo, or a channel nobody created, logs a warning at connect time and every call to the event silently reaches nobody. See [Channels](./channels.md). ::: ## Call it Call the event by name from any graph on the actor, exactly like a local Custom Event: drag off an exec pin, type `Sparkle`, and fill the `Color` and `Intensity` pins. There is no separate node kind for the call and none in the figure above; the call node is the ordinary one the editor offers for any custom event. The gate at the head of the event routes the call over the transport and skips the local body when this client is not a recipient; when it is, the body runs here as well. For a Spatial Multicast event the owner runs the body itself and sends it, so the call sits behind an **Is Locally Owned** check the way the [Quickstart](../quickstart.md) does; a proxy's copy of the trigger must not send a second one. ## Receive it There is no second node and no second graph. The same `Sparkle` body shown above is the receiver: on every recipient the SDK replays the call through the event, the gate recognises the replay and lets the body run, and `Color` and `Intensity` arrive on the event's own pins with the values the caller passed. What the checkbox generates is a call to `UCrowdyReplicatedEventLibrary::CrowdyDispatchReplicatedEvent` at the top of the event. It is marked internal-use and never placed by hand; if a marked event ever loses its gate (a manual edit, a bad merge), calling it runs the body locally and announces nothing, which looks exactly like a transport drop. Recompile. **Success signal.** With one client, `crowdy.rpc.loopback 1` and `crowdy.rpc.trace 1` show the send and the looped-back receive; the sparkle then comes from the receive rather than the local run. ## Gotchas - The checkbox lives on the Custom Event node's Details, not the actor's. - A red status line is the fastest signal that a pin type is rejected. Read it before compiling. - The Channel field is join-only. Create the channel in Crowdy Studio or at runtime first. - The Blueprint event body runs on the caller for Spatial Multicast and Multicast, and only where the recipient says for Owning Client. Do not add a second local call. - Cheat-sensitive data never rides a CrowdyEvent; it belongs on the [truth plane](../concepts/two-planes.md), in your server code. ## Related - [RPC events in C++](./rpc-events-cpp.md): the parameter rules and the routing keys in full. - [Recipients and routing](./recipients-and-routing.md): what a chunk is, decay, and targeted sends. - [Channels](./channels.md): creating the channel a Multicast event names. # RPC Events in C++ Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/rpc-events-cpp # RPC Events in C++ A CrowdyEvent is a `UFUNCTION` you call like a normal method. The SDK marshals the arguments by reflection, routes them over the transport, and runs the matching `_Implementation` on the receivers the recipient names. No payload struct, no base class, no manual send call. ## When to use one For a moment, not a value: a flicker, a swing, a chat line, a one-shot trigger. Anything a late joiner must still see is a [Crowdy State](./crowdy-state.md) property; anything a client could gain by lying about belongs on the [truth plane](../concepts/two-planes.md), in your server code. ## The two halves **The receiver** is a reflected `UFUNCTION` named `_Implementation`, declared by you, tagged `meta=(CrowdyEvent)` plus the routing keys. It is what runs on every recipient, the caller included when the recipient says so. **The call site** is `CROWDY_EVENT()`, a macro placed in the class body with no trailing semicolon. It generates a template `(Args...)` that forwards to `FCrowdyRPC::SendChecked`, which checks the argument count and each argument's convertibility against the receiver's declared parameters at compile time, marshals them, and routes the call. Both halves work on any actor or component that carries a `UCrowdyEntityComponent`, and on a [replicated subsystem](./replicated-subsystems.md). :::warning[The receiver must be a literal UFUNCTION you write by hand, never one emitted from inside another macro.] UnrealHeaderTool does not expand macros when it scans for reflected declarations. A `UFUNCTION` produced by a macro is invisible to reflection, so `CROWDY_EVENT` generates only the non-reflected thunk and the routing lives on the receiver's metadata. ::: The lantern's second event is `Sparkle`: the owner announces a one-time ignition sparkle at `BeginPlay`, everyone in range tints the light and reads a set of spark offsets. The four blocks below are facets of that one member. `FLanternSparkleStyle`, the struct the receiver takes, is declared under [Parameters](#parameters) below. ```cpp // Lantern.h // The receiver runs on every client in range; Sparkle() is the call that sends it. UFUNCTION(meta = (CrowdyEvent, CrowdyRecipient = "SpatialMulticast")) void Sparkle_Implementation(const FLanternSparkleStyle& Style, const TArray& SparkOffsets); CROWDY_EVENT(Sparkle) ``` The call, inside `ALantern::BeginPlay` after `Super::BeginPlay()`, behind the owner check that every `SpatialMulticast` send needs: ```cpp // Lantern.cpp // The owner announces its ignition sparkle to everyone nearby. if (CrowdyEntity->IsLocallyOwned()) { FLanternSparkleStyle Style; Style.Color = FLinearColor::Yellow; Style.Intensity = 8000.f; TArray Offsets = { FVector(0.f, 0.f, 40.f), FVector(0.f, 0.f, 80.f) }; Sparkle(Style, Offsets); } ``` ## Routing keys The meta keys are read from the receiver at scan time and baked into a registry, so a packaged build never reads metadata at runtime. | Meta key | Value | Default when omitted | |---|---|---| | `CrowdyEvent` | none | Required. Marks the function as a receiver. | | `CrowdyRecipient` | An `ECrowdyEventRecipient` enumerator name: `SpatialMulticast`, `Multicast`, `OwningClient` | `SpatialMulticast` | | `CrowdyDecay` | An `ECrowdyDecayRate` name | `No_Decay`. Spatial only. | | `CrowdyDistance` | An `ECrowdyReplicationDistance` name | `Eight_Chunks`. Spatial only. | | `CrowdyChannel` | A channel name | Empty, the app's session channel. Multicast only. | Who each recipient reaches, and over which transport, is on [Recipients and routing](./recipients-and-routing.md). There is no `Host` recipient: a saved one reads as `OwningClient` and warns. One more key, `CrowdyAction`, declares that the parameters describe a one-shot action; it changes nothing for an actor that runs the body itself and matters only to a backend that holds the entity as data. ## Parameters `FCrowdyRPC::IsSupportedParamType` decides what may ride the wire. A parameter may be: - a primitive (`bool`, any integer width, `float`, `double`, a byte), an enum, an `FName`, an `FString`, or an `FText`; - a `USTRUCT`; - an object or class reference (`UObject*`, `TSubclassOf`, and their soft forms), resolved by identity on the receiver; - a `TArray` of any of the above, object references included; - a `TSet` or `TMap` whose element, key, and value are not object references. Not supported: a return value, a non-const output reference, a delegate, an interface, a `TSet` or `TMap` of object references, and a container buried inside a struct parameter at any depth a real struct reaches (`FCrowdyRPC::StructTransitivelyContainsContainer` is the check; it stops at eight levels). A `const TArray&` is an input and is fine. :::warning[An unsupported signature is not a compile error. The event is dropped at scan time and every call to it goes nowhere.] The startup scan runs `FCrowdyRPC::DescribeSignatureProblem` on each receiver and logs an error of the shape `[CrowdyAutoRegistry] CrowdyEvent 'ALantern::Sparkle_Implementation' parameter 'X' has unsupported type 'Y' ... not registered; calls to it will be dropped.` Grep the log for `not registered` when an event compiles but never arrives. ::: A struct parameter travels as a value, so a small cosmetic struct is the natural way to pass several fields at once: ```cpp // Lantern.h // Cosmetic view data for the ignition sparkle; server-owned state never goes here. USTRUCT() struct FLanternSparkleStyle { GENERATED_BODY() UPROPERTY() FLinearColor Color = FLinearColor::White; UPROPERTY() float Intensity = 1.f; }; ``` ### Containers and their bounds A container parameter is decoded with a bound of 65536 elements; a count past that is treated as forged and the whole call is dropped on receipt. The struct-buried form is refused at scan time because that decode cannot be bounded. ```cpp // Lantern.cpp void ALantern::Sparkle_Implementation(const FLanternSparkleStyle& Style, const TArray& SparkOffsets) { Light->SetLightColor(Style.Color); // One spark per offset in a real project; here each offset brightens the ignition flash. Light->SetIntensity(Style.Intensity * SparkOffsets.Num()); } ``` :::warning[A Multicast call has a 1024-byte budget. A call that would exceed it is dropped loudly, never truncated.] `CrowdyChannelPayloadMaxBytes` caps the encoded payload of a reliable (`Multicast`) call. A receiver whose fixed-width parameters alone can never fit is refused at registration with an error naming the byte count; a call whose actual encoded size exceeds the cap is dropped at send with `[CrowdyRPC] Reliable '' dropped ... over the 1024-byte channel limit`. A payload that might be large, such as a list of offsets, belongs on `SpatialMulticast`, which fragments across datagrams. ::: ### Object references An object parameter is encoded by stable identity, tagged as one of three kinds: null, a tracked entity (addressed by its NetID), or an asset or class (addressed by its object path). On the receiver an entity resolves against the local registry and a path resolves against loaded objects. A runtime object that is neither a tracked entity nor an asset has no portable identity and is sent as null with a warning. :::caution[A class or asset reference resolves by path on the receiver, and the receiver only finds what is already resident.] By default an asset that is not loaded on the receiving client decodes to null with a warning naming it. `crowdy.rpc.allowObjectLoad 1` opts into loading it on demand; leave that off in a shipping build and make sure the asset is loaded on every client that can receive the call. ::: ## What happens on the wire The call is packed into an `FCrowdyRpcCall`: the declaring class id, a function id hashed from the full signature (class path, name, and the ordered canonical parameter types), and the parameter bytes prefixed with a format version (`CrowdyRpcParamBlobVersion`). The receiving `UCrowdyEventRouter` looks the pair up in the registry `UCrowdyAutoRegistry` built at startup and invokes the `_Implementation` on the local instance of that entity. A signature that drifted between two builds, or a class that is not loaded, drops with `[CrowdyEventRouter] RPC dropped - no function for ClassID=... FunctionID=...`. A receiver that holds the entity as data rather than as an object reads the same parameters by name through `FCrowdyEventParams`, not through a live object. The Crowdy Mass Rendering Backend works this way, and runs your event's body on a stand-in; see [Run your code on a crowd row](../mass/run-your-code-on-a-crowd-row.md). Tracing: ```text crowdy.rpc.trace 1 every send and receive: function, entity, addressing, parameter bytes crowdy.rpc.reliable.trace 1 the channel transport only crowdy.rpc.loopback 1 deliver your own sends to your own receiver, for a single-client test crowdy.rpc.dumpfn BP_Hero_C MyEvent print one function's routing info ``` ## Gotchas - `SpatialMulticast` runs the body on the caller too, so guard the call with `IsLocallyOwned()`; a proxy's copy of the trigger must not send a second one. - A receiver declared with no `CrowdyRecipient` is `SpatialMulticast`. On a subsystem that default is rejected at send; see [Replicated subsystems](./replicated-subsystems.md). - A `SpatialMulticast` reaches only clients with a fresh actor of their own on the map. A client whose pawn is not sending updates is at no position, so it receives none and its own sends reach nobody; see the [Quickstart](../quickstart.md#1-make-your-player-a-crowdy-entity). - A late joiner receives nothing from a past call. If it matters after the moment, it is state. - Delivery is on the game thread, always. A handler may touch actors freely. ## Related - [RPC events in Blueprint](./rpc-events-blueprint.md): the same system with a checkbox instead of a macro. - [Recipients and routing](./recipients-and-routing.md): the recipients, chunks, decay, and targeted sends. - [Channels](./channels.md): where a `Multicast` call travels. - [RPC types](../reference/rpc-types.md) and [RPC meta keys](../reference/rpc-meta-keys.md). # Recipients and Routing Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/recipients-and-routing # Recipients and Routing Every CrowdyEvent names a recipient, and the recipient decides two things: who runs the body, and which transport carries it. This page is the delivery model behind both the [C++](./rpc-events-cpp.md) and the [Blueprint](./rpc-events-blueprint.md) authoring pages. ## The recipients `ECrowdyEventRecipient`, set with `CrowdyRecipient` in C++ or the Recipient dropdown in Blueprint. `SpatialMulticast` is the default when the key is omitted. | Recipient | Travels over | Distance and decay | Who runs the body | |---|---|---|---| | `SpatialMulticast` (default) | The spatial path, addressed by the sender's chunk | Yes: `CrowdyDistance` and `CrowdyDecay` | Every client in range, the caller included | | `Multicast` | A channel: the session channel, or the one `CrowdyChannel` names | No: every member, any distance, never thinned | Every channel member, the caller included | | `OwningClient` | A spatial event named for one client; a direct message if a parameter can hold text; the session channel where neither reaches | No | Only the session that writes the target entity (its writer id): its owner, or the [Leader](./leader.md) for an entity Owned By Leader, and never another session of the same user. A non-owner's call becomes a request to that client; its own call runs locally and sends nothing. | The decision is a pure function of the recipient, the participant kind, and what this client knows about the entity, so it is the same on every client and in every build. "In range" is measured from the position each client's own actor updates registered, so a `SpatialMulticast` reaches only clients with a fresh actor on the map; a client whose pawn is not sending is nowhere and receives nothing. The [Quickstart](../quickstart.md#1-make-your-player-a-crowdy-entity) makes the player's pawn that actor before it sends anything. :::warning[On a replicated subsystem the default recipient is rejected. Set Multicast or Owning Client explicitly.] A subsystem has no world position, so a `SpatialMulticast` event declared on one has nowhere to be sent from. The send logs `uses SpatialMulticast, which has no location; set CrowdyRecipient=Multicast or OwningClient. Dropping.` and consumes the call so a Blueprint caller does not run the body as a fallback. Since `SpatialMulticast` is what an unannotated event gets, every event on a subsystem needs the key written out. See [Replicated subsystems](./replicated-subsystems.md). ::: ## Spatial: chunks, distance, and decay The world is divided into chunks of `ChunkSize` units on a side; a spatial event is sent from the sender's chunk and reaches every client whose actor stands within `CrowdyDistance` chunks of it. `ChunkSize` lives on the game session (`UCrowdyGameSession::GetChunkSize`, `SetChunkSize`) and defaults to 1600 units, so `ECrowdyReplicationDistance::Four_Chunks` is 6400 units at the default. A distance is a chunk count, not a world distance: changing the chunk size changes what every distance value means. To see which chunk a point falls in, `UHelperFunctions::GetChunkCoordinateAtLocation(WorldContextObject, WorldLocation, ChunkX, ChunkY, ChunkZ)` (Blueprint: **Get Chunk Coordinate At Location**) reads the session's chunk size and returns the three `int64` coordinates. `ECrowdyReplicationDistance` runs from `None` through `One_Chunk` to `Eight_Chunks` (the default). `ECrowdyDecayRate` thins delivery with distance: | Value | Effect | |---|---| | `No_Decay` (default) | Every client inside the distance receives the event. | | `Exponential_Decay` | Delivery probability falls off exponentially with distance. | | `Linear_50`, `Linear_25`, `Linear_10`, `Linear_5` | Linear falloff, from the mildest to the most aggressive. | Decay is a server-side filter applied before the event reaches remote clients. Use it for high-rate cosmetic events where a distant client missing some of them is fine. ## Multicast: what reliable means A `Multicast` event rides a [channel](./channels.md). "Reliable" here means coverage: every member of the channel is a recipient, at any distance, with no decay. It does not mean guaranteed delivery. The transport is still UDP with no acknowledgement, no retransmit, and no duplicate suppression. :::warning[Reliable is coverage, not delivery. A late joiner gets nothing from a past Multicast call.] Treat a Multicast event like any other fire-and-forget call for anything that must not be silently missed. If a value has to be right on a client that missed the event or joined afterwards, put it in a [Crowdy State](./crowdy-state.md) property, or in your server code if it is [truth](../concepts/two-planes.md); an event has no history to replay. ::: The payload of a Multicast call is capped at 1024 bytes (see the [C++ page](./rpc-events-cpp.md#containers-and-their-bounds)); a large container belongs on `SpatialMulticast`. ## Targeted: OwningClient `OwningClient` goes out as a spatial event around the chunk the sender draws the target in, reaching one chunk in every direction, and names the client that writes the entity. Every client in that region receives it and every client but the named one ignores it, so a target crossing a chunk border is still reached, unless it moves more than a chunk in about a third of a second. It uses the session channel where there is no region to reach: the entity sends no movement, or it changed hands and this client has not heard from the new writer yet. A session call names its client the same way. A named client that has not heard of the change of owner yet holds the call for up to 0.3 seconds. A Leader entity between Leaders has no writer, so the call is dropped with a warning. An event with a parameter that can hold typed text, meaning an `FString` or `FText`, or a container or struct holding one, stays a direct message: a single-actor message to the one client that sends the id it names, under the rules for private messages between players. Both players need `use_direct_messages`, which some access tiers never grant. It never falls back to the session channel: where no id can be reached it is dropped with a warning. The check reads parameter types, so do not pass text a player typed through an `FName` or a byte array. Private text between players belongs in a Server Function. Whichever way it arrived, an `OwningClient` call runs only on the client that writes the entity. On a subsystem there is no single-actor transport, so it arrives over the channel and is gated by identity on receipt. On a replicated subsystem, `OwningClient` runs on the [Leader](./leader.md), so it is how any client asks the Leader to do something. There is no Host recipient: nothing elects a host. A function that still carries the saved value `Host` reads as `OwningClient` and logs a warning that names the function. On an actor that now means only the actor's owner runs it, not whichever client used to be host. Pick the recipient you mean, or move logic that must be enforced to a [Server Object](../concepts/two-planes.md). :::warning[`OwningClient` limits who runs an event, not who can see or send it.] The parameters reach every client within a chunk of the target, or on the session channel every client of the app, and any client can name any entity. Treat them as untrusted input, keep private data in a Server Object, and call a Server Function for anything that must be refused. ::: :::caution[An entity that sends no movement always uses the session channel.] The session channel reaches every client of the app, however far away, and carries 1024 bytes at most: a longer call is dropped with an error. Keep events to such an entity occasional, or make it replicate movement. ::: :::caution[Every client near the target receives a copy of each call.] Each client in the region downloads and discards a call meant for someone else, so in a crowded area the traffic grows with the square of the players there. Keep `OwningClient` to occasional events, never a per-frame stream. ::: :::caution[The sender needs access to the target's chunk.] The spatial event needs the sender's `access` permission in a grid covering the chunk it is addressed to, not the sender's own chunk. In an app that grants access zone by zone, a client without access there is refused, and the log names the permission. ::: :::caution[A direct message aimed at a moving entity can be lost while it crosses a chunk border.] The sender addresses the chunk it draws the target in, and that trails where the target really is by the interpolation delay plus a network round trip, about a third of a second. A direct message sent in that window is lost with no message. Nothing is wrong with the entity, and the next event arrives. This applies to an `OwningClient` event that carries text and an owner-only Crowdy State value. For anything that must take effect, call a Server Function. ::: Nobody writes a World entity, so an `OwningClient` event aimed at one drops with a warning. To reach everyone instead, send a `SpatialMulticast` or `Multicast` event, or call a Server Function if the change is [truth](../concepts/two-planes.md). The lantern world uses `OwningClient` for a relight: a player who walks up to someone else's dark lantern asks its owner to relight it. The receiver runs on the owner, so a plain write to `bLit` ships to every proxy. `Flicker` from the [Quickstart](../quickstart.md) is the `SpatialMulticast` row; `Multicast` is described in the table above and needs no new member. ```cpp // Lantern.h UFUNCTION(meta = (CrowdyEvent, CrowdyRecipient = "OwningClient")) void RequestRelight_Implementation(); CROWDY_EVENT(RequestRelight) // Lantern.cpp void ALantern::RequestRelight_Implementation() { // This runs on the owner, so a plain write ships to every proxy. bLit = true; OnRep_Lit(); } ``` A `RequestRelight` custom event with Crowdy Replicates ticked and **Recipient** set to **Owning Client**; its body is **Set Visibility** on `Light`, fed by **Get Light**. Call it from any client and it runs on the lantern's owner alone. The figure is the visible half only. To show it on every client as the C++ does, add **Set Lit** to true after it: on the owner, the plain write ships. [Blueprint snippet: recipient-each, see /bp/unreal-sdk/recipient-each.txt] ## Receiving raw notifications in Blueprint `UCrowdyBlueprintReceptionLayer` (**Crowdy Blueprint Reception Layer**) is a Blueprintable object that receives the wire-level notifications behind the systems on this page, for a game that wants to see them before the SDK's own routing does: subclass it in Blueprint, list the payload structs it claims in `SupportedEvents` (empty means unclaimed events only) and the actor update types in `SupportedActorUpdateTypes`, create it with **Create and Register Layer** (`CreateAndRegisterLayer(WorldContextObject, Class)`), and bind its two events. `OnEventNotificationReceived` (`FOnGameEventNotificationReceived`) delivers an `FGameEventNotificationBP` (the sender `UUID`, the chunk, the `Timestamp`, and the `Event` as an instanced struct); `OnActorUpdateReceived` (`FOnActorUpdateReceived`) delivers an `FActorUpdateNotificationBP` with the same envelope around an `ActorUpdate` struct. A layer sees events before the SDK checks who they are for, so it also sees `OwningClient` calls named for another client. A game that uses CrowdyEvents and Crowdy State never needs one; it exists for custom payloads sent with `SendCrowdyEvent` and for diagnostics. ## Delivery is on the game thread Every routing and dispatch entry point in `FCrowdyRPC` and `UCrowdyEventRouter` is game-thread only, and every handler runs there. A handler may spawn, destroy, and touch components without marshalling. ## Sending without an actor Two lower-level entry points exist for callers the ordinary path cannot serve. **A CrowdyEvent for an entity you hold only by identity.** `FCrowdyRPC::SendToTarget(World, Target, Fn, Frame)` sends a receiver function to an entity described by an `FCrowdyRpcTarget`: its `NetID`, an optional `Location`, its `WriterID`, and this client's `Role` toward it. It routes by the function's own recipient, whichever it is, and where this client already holds a registration for the entity the record's owner, role, and position win over the target's fields. It returns false only when there was no transport at all; every drop returns true, so a caller must not run a local body as a fallback for a refused send. Read the location from the entity's own live state, never from a caller's argument, because the location decides which region the message is addressed to. A plain `UObject` that stands for an entity with no actor can also implement `ICrowdyEventSource` and use the ordinary `CROWDY_EVENT` call; the send path asks the interface for the identity and the position it would otherwise read from an actor. The five overrides are `GetEventEntityID` (the entity's NetID), `GetEventLocation` (where it stands right now, or false when unknown), `GetEventWriterID` (the writing session's actor id, invalid for a world entity), `GetEventRole`, and `IsEventLocallyOwned` (only the client that writes the entity may originate). Answer for the entity you stand for, read live; never hand back a location a caller passed in, because the location decides which region the event is addressed to. **A struct payload with no declared receiver.** `UCrowdyUtilities::SendCrowdyEvent(WorldContextObject, TargetEntity, Payload, Recipient, DecayRate, ReplicationDistance)` in C++, **Send Crowdy Event** (`K2_SendCrowdyEvent`, a wildcard struct pin) in Blueprint, broadcasts any `USTRUCT` at a target actor with an explicit recipient. It goes through `UCrowdyEntitySubsystem::DispatchGameEvent`, whose `ECrowdyTarget` (`Everyone`, `Entity`, `Owner`, `AllExceptSender`, and a `Host` value kept for compatibility that the SDK never sends) is the wire-level addressing the recipient enum maps onto; `DispatchGameEventAt` is the same send from an explicit location, `DispatchGameEventView` and `DispatchGameEventViewAt` borrow the payload instead of copying it, and `DispatchSingleActorMessage` and `DispatchSingleActorMessageTo` are the targeted delivery behind OwningClient. A handler receives the struct, and may declare an `FCrowdyEventContext` as an optional second parameter to read the `SenderID`, the `TargetID`, the `Target`, and `bSentByLocalPlayer`. An `OwningClient` struct send names the entity's owner, so it reaches nobody on a World entity, and it has none of the session fallback a `CrowdyEvent` gets. :::caution[The struct send has none of the compile-time checking a CrowdyEvent receiver gets.] Any struct is accepted, there is no `_Implementation` naming convention to tie a sender to a receiver, and a mismatch is found at runtime or not at all. Prefer a `CrowdyEvent` unless you are building a system on top of the SDK. ::: ## Gotchas - Omitting `CrowdyRecipient` means `SpatialMulticast`. Write the key out on anything that is not an actor. - Decay and distance are read only for `SpatialMulticast`. Setting them on a `Multicast` event does nothing. - `OwningClient` on a World entity nobody writes drops with a warning. - A call around a change of owner can still be lost if it reaches the old owner by a targeted send. - Changing `ChunkSize` changes the meaning of every distance in the project. ## Related - [RPC events in C++](./rpc-events-cpp.md) and [in Blueprint](./rpc-events-blueprint.md). - [Channels](./channels.md): what the Multicast path rides, and the session channel. - [The Leader](./leader.md): who an event on a replicated subsystem reaches. - [Replicated subsystems](./replicated-subsystems.md): the non-spatial participant. - [Enums](../reference/enums.md). # Crowdy State Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/crowdy-state # Crowdy State Mark a `UPROPERTY` with `meta=(CrowdyState)` and the client that owns the entity diffs it at the map's replication cadence and ships only the changed values to every proxy, which write them back onto their own copy of the actor. No wire struct, no executor, no manual send unless you ask for one. It replicates single values: POD leaves and `USTRUCT`s made of them, never containers or object references, and it says so once at startup for each property it drops. ## When to use it For view state that has to be the same on every client, late joiners included: a lantern's lit flag, an animation stance, a cosmetic colour. It works whether or not the entity sends movement, and on a [replicated subsystem](./replicated-subsystems.md). :::danger[Authoritative or cheat-sensitive state never belongs in Crowdy State.] This is the view plane. The owner writes a value and every other client believes it. Hit points, currency, inventory: your server code, always. See [The Two Planes](../concepts/two-planes.md). ::: ## Prerequisites The actor carries a `UCrowdyEntityComponent`, and the map profile's `bUseStateReplicator` is on (the default). A property the class declares is discovered at startup by the auto registry, which builds the class's replication layout once; the layout is baked into the [registry](../studio/inspector-and-registry.md) for packaged builds, so no metadata is read at runtime. ## The metadata keys All on the `UPROPERTY`, all spelled exactly as shown. | Key | Value | Effect | |---|---|---| | `CrowdyState` | none | The marker. The property replicates on the view plane. | | `CrowdyOnRep` | a function name | A parameterless `UFUNCTION` run after the value is written, on the receiver and on the sender. Read the property for the new value; there is no previous-value argument. | | `CrowdyOwnerOnly` | none | Delivered only to the owning client, over the targeted path, never on the spatial broadcast. Scope, not secrecy. | | `CrowdyHeartbeat` | none | Opt in to the periodic keyframe: the property is re-sent every `StateKeyframeIntervalSeconds` even when unchanged, so a late or desynced observer converges. Off by default in C++; the Blueprint dropdown turns it on. | | `CrowdyContinuous` | none | The value rides the entity's movement updates instead of going as a delta: sent on change and on every keyframe. For a value that changes as often as the movement. See [Send your own values with the movement](./continuous-state.md#send-your-own-values-with-the-movement). | | `CrowdyManualDirty` | none | Never auto-diffed. The value ships only when you mark it, with `MarkStateDirty`. For a property that is expensive to compare every tick. See [Marking state from outside the actor](#marking-state-from-outside-the-actor). | :::warning[An enum without CrowdyHeartbeat can show a stale value to a late joiner.] An enum is held state: sent on change, never re-sent. A client that starts observing after the last change, or that loses the one datagram carrying it, shows the wrong value until it changes again. The startup scan warns once per such property; `crowdy.state.heartbeat.advisories` lists every one it found. Add `CrowdyHeartbeat`, or tick Keyframe heartbeat in the variable's Crowdy Replication settings, unless the value is meant to be transient. ::: ## Mark a property The Quickstart's `bLit` is the plain form: assign, and the change ships. This page adds a second property to `ALantern`, `TimesLit`, marked `CrowdyManualDirty`, so the count is pushed once per lighting instead of compared every tick. `RecordLighting` (a plain `void RecordLighting();` member you declare in the header) is called from the owner-gated overlap of the Quickstart's step 3; it increments the count and marks it, and every proxy's `OnRep_TimesLit` scales the light by the count. ```cpp // Lantern.h // A manual-dirty property ships only when you schedule it, not every tick. UPROPERTY(meta = (CrowdyState, CrowdyManualDirty, CrowdyOnRep = "OnRep_TimesLit")) int32 TimesLit = 0; UFUNCTION() void OnRep_TimesLit(); // Lantern.cpp void ALantern::RecordLighting() { ++TimesLit; CrowdyEntity->MarkStateDirty(TEXT("TimesLit")); } void ALantern::OnRep_TimesLit() { Light->SetIntensity(2000.f * TimesLit); } ``` Add an Integer variable `TimesLit`, set its **Replication** dropdown under **Crowdy Replication** to **Replicated**, and tick **Update manually** there (the other two toggles are **Keyframe heartbeat** and **Only send to owner**). From **Event ActorBeginOverlap**, the pure **Is Crowdy Entity Locally Owned** feeds a **Branch**; on the true side **Get TimesLit** feeds a **+**, **Set TimesLit** stores the result, and the static **Mark Crowdy State Dirty** schedules it with `TimesLit` on the Property Name pin and `Target` left as self (the member form on the component would need a component getter as well). Seven nodes, one of them the owner gate the lantern's C++ overlap handler has: on a proxy the mark is not ignored. [Blueprint snippet: state-mark, see /bp/unreal-sdk/state-mark.txt] ## The notify `CrowdyOnRep` names a parameterless function, GAS-style. It fires wherever the value genuinely moved since the last send: on every receiver after the write, and on the sender itself, because a sent delta never comes back to its sender and the owner would otherwise never run it. A keyframe re-sending an unchanged value fires nothing, and a manual dirty mark on a value that did not move fires nothing either. Each slot fires at most once per tick, and a change the notify makes to its own property is folded into the sent baseline rather than re-sent. The [Quickstart](../quickstart.md) lantern is the `state-onrep` example: `bLit` with `CrowdyOnRep = "OnRep_Lit"`, and a notify that sets the light's visibility. ```cpp // Lantern.h // View state: a wrong value is a visual glitch, not a cheat, so it belongs on the Crowdy State plane. UPROPERTY(meta = (CrowdyState, CrowdyOnRep = "OnRep_Lit")) bool bLit = true; UFUNCTION() void OnRep_Lit(); // Lantern.cpp void ALantern::OnRep_Lit() { Light->SetVisibility(bLit); } ``` Select the variable, set **Crowdy Replication** to **Replicated**, and a **RepNotify** field appears; the editor creates the `OnRep_` function. The variable's Get and Set nodes then carry the replication badge: ![The replication badge on a Crowdy-replicated variable's Get and Set nodes](/img/unreal-sdk/bp-replication-badge.png) The body of the notify, drawn here as a custom event named `OnRep_Lit` because a generated graph cannot draw the editor-made function itself: **Get bLit** feeds **Set Visibility** on `Light`. [Blueprint snippet: state-onrep, see /bp/unreal-sdk/state-onrep.txt] :::caution[The notify runs on the sender too, at the next replication tick, and only on a real change.] Write the notify as the one place the value is applied to the world, the way `OnRep_Lit` drives the light, and keep it idempotent. The Quickstart calls `OnRep_Lit` itself right after the assignment for an immediate local response; the replicator runs it once more on the tick that ships the change, which is harmless for a notify that only applies the current value and wrong for one that counts its own calls. ::: ## What ships, and when Only the owning client diffs. A remote proxy never diffs; it applies. The cadence is the map profile's `ReplicationIntervalHz` (1 to 10, default 10), the same clock the continuous channel uses, though the two send independently. Each tick the replicator compares every auto-diffed property of every entity this client drives against a shadow copy of the last sent value and encodes the changed ones into an `FCrowdyStateDelta`; owner-only properties go out as a second, targeted delta. Every `StateKeyframeIntervalSeconds` (default 2, on the map profile; 0 turns it off) each entity also emits a keyframe carrying its `CrowdyHeartbeat` properties, unless the entity's `StateHeartbeat` is Off. A delta travels as far as the profile's `StateRelevanceDistance` (Eight Chunks by default). One delta holds about 1 KB of state: 1029 bytes on an actor, and 969 on a replicated subsystem, which rides the session channel. A larger update is split into several deltas in the same tick, so its properties can land a moment apart. A single property too big for one delta is not sent. It stays pending, clients keep their old value, the owner's notify does not run, and a warning names the property and entity once. It goes as soon as it fits, and the rest of the update does not wait for it. A value that can grow that far belongs elsewhere: see [Where the list you wanted belongs](#where-the-list-you-wanted-belongs). A struct with a native net serializer (`FVector_NetQuantize`, `FRotator`) rides the engine's own quantized serializer automatically; a plain `FVector` stays exact. Quantization is chosen by type, not by a key. See [What a state property may be](#what-a-state-property-may-be). Every delta carries a layout hash that folds each property's name and canonical type in declaration order. A receiver whose own hash for the class differs drops the delta cleanly rather than reading bytes by position, so adding, removing, reordering, or retyping a replicated property on one build and not another costs you deltas, not corruption. An enum property is carried as its underlying integer (blob version 2, `CrowdyStateBlobVersion`); a peer on the older format drops these deltas rather than misparsing them, so every client of an app runs one build. ## What a state property may be You marked a property `CrowdyState` and nothing arrives, or you are about to mark one and want to know if it will. The classifier every surface shares, `FCrowdyStateLayoutBuilder::ClassifyStateProperty` (with `IsStateReplicatable` as the yes-or-no form and `DescribeStateSupport` for the sentence), decides at discovery; the Blueprint compiler's variable check and the variable-details dropdown reuse it, so every surface reports the same reason. ### Accepted | Kind | Examples | Notes | |---|---|---| | Numeric | `int32`, `int64`, `uint8`, `float`, `double` | Diffed and sent as their bytes. | | Boolean | `bool` | | | Enum | `enum class E : uint8`, `TEnumAsByte` | Carried as the underlying integer. Consider `CrowdyHeartbeat`; see [The metadata keys](#the-metadata-keys). | | Name and string | `FName`, `FString` | | | Plain struct | any `USTRUCT` whose fields, at every depth, hold no container | One slot in the layout; diffed and sent as one unit. | | Net-serialized struct | `FVector`, `FRotator`, `FVector_NetQuantize`, any struct with a native net serializer | Rides its own `NetSerializeItem`, quantized as the engine defines it, and exempt from the nested-container check because its serializer bounds the decode. | ### Rejected :::warning[Containers and object references are rejected at discovery, in any position, including inside a struct. Use a CrowdyEvent, or your server code.] The error names the escape hatch: `CrowdyState: property 'Players' on '/Script/MyGame.Lantern' is a container; CrowdyState does not replicate containers; use a CrowdyEvent RPC or a Server Object. Omitting it.` A list of who lit the lantern is a `TArray` parameter on a [CrowdyEvent](./rpc-events-cpp.md) if it is a moment, or a [Server Object](../exec/overview.md) if it is [truth](../concepts/two-planes.md). Never re-attempt it here. ::: | Rejected | The reason discovery logs | |---|---| | `TArray`, `TSet`, `TMap` | `is a container; CrowdyState does not replicate containers; use a CrowdyEvent RPC or a Server Object` | | A plain struct that holds a container at any depth | `is a USTRUCT that transitively contains a container (TArray/TSet/TMap); such nested containers are rejected because a forged element count would drive an unbounded allocation on decode` | | A fixed-size C array (`float Values[4]`) | `is a fixed-size array; CrowdyState replicates only single-value POD and USTRUCT properties (its positional diff would miss changes past element 0)` | | `UObject*`, `TSubclassOf`, soft object and class references, interfaces, delegates | `is an object/interface/delegate reference; CrowdyState replicates only POD and USTRUCT values` | | Anything else, `FText` for one | `has an unsupported type 'X'; CrowdyState replicates only POD and USTRUCT values` | A rejected property is omitted from the class's layout, so it never corrupts the positional wire order of the ones that were accepted; the rest of the class replicates normally. The line is an error and is not gated by `crowdy.state.trace`, so it is in the log whether or not tracing is on. ### Structs A plain `USTRUCT` is a single slot. The whole struct is compared with the engine's `Identical` and, when any field differs, the whole struct is sent; on the receiver every field lands together, before the notify runs. That is the reason to use one: two fields that must always be seen together, a colour and an intensity, cannot arrive half-applied the way two separate properties can. The lantern's glow is such a pair. `FLanternGlow` holds a colour and an intensity; `WarmGlow` on the owner changes both, and `OnRep_Glow` applies both to the light in one step. ```cpp // Lantern.h // A plain struct rides CrowdyState as one value; its fields always arrive together. USTRUCT() struct FLanternGlow { GENERATED_BODY() UPROPERTY() FLinearColor Color = FLinearColor::White; UPROPERTY() float Intensity = 1.f; }; UPROPERTY(meta = (CrowdyState, CrowdyOnRep = "OnRep_Glow")) FLanternGlow Glow; UFUNCTION() void OnRep_Glow(); // Lantern.cpp void ALantern::WarmGlow() { Glow.Color = FLinearColor(1.f, 0.6f, 0.2f); Glow.Intensity += 500.f; } void ALantern::OnRep_Glow() { Light->SetLightColor(Glow.Color); Light->SetIntensity(Glow.Intensity); } ``` A Blueprint variable of a C++ struct type replicates the same way: set its **Crowdy Replication** dropdown to **Replicated** and give it a RepNotify, exactly as for a scalar. Authoring a new struct type in Blueprint for this is unusual, so this section has no Blueprint graph of its own; the mechanics of marking and notifying are under [Mark a property](#mark-a-property) and [The notify](#the-notify). :::caution[A struct diffs and ships as one unit.] Changing one field of a five-field struct re-sends all five. Five scalar properties diff independently and each ships alone. Group fields into a struct when they must land together; keep them separate when they change at different times. ::: ### Where the list you wanted belongs | You wanted | Put it on | |---|---| | The names of the players who lit the lantern this match | Your server code, if it is truth the server should hold; otherwise a `TArray` parameter on a `Multicast` CrowdyEvent when it changes. | | A ring buffer of recent positions | The [continuous state](./continuous-state.md) snapshot, as fixed fields, or nothing: the proxy interpolates for you. | | A reference to another actor | Its NetID as an `FGuid`, resolved with `FindEntity` on the receiver. | | A list of active effects | Your server code. | ## Marking state from outside the actor `UCrowdyStateBlueprintLibrary` has two static nodes that schedule a `CrowdyManualDirty` property to ship without first fetching the actor's Crowdy Entity Component: **Mark Crowdy State Dirty** and **Mark All Crowdy States Dirty**. Each resolves the target actor's component and forwards to its `MarkStateDirty` or `MarkAllStateDirty`. Use them whenever the caller does not already hold the component: a graph on another actor, a function library, a UI widget. From the actor's own graph either form works; the static one needs no component reference wired in. ### The two nodes | Node | C++ | What it does | |---|---|---| | **Mark Crowdy State Dirty** | `UCrowdyStateBlueprintLibrary::MarkCrowdyStateDirty(Target, PropertyName)` | Schedules one manual-dirty property on the target's entity for the next replication tick. | | **Mark All Crowdy States Dirty** | `UCrowdyStateBlueprintLibrary::MarkAllCrowdyStatesDirty(Target)` | Schedules every manual-dirty property on that entity. | Both are `DefaultToSelf` on `Target`: from an actor's own graph you wire nothing and pick the property. From a component graph or a plain object graph, self is not an actor, so wire the actor in; the node shows a "Wire an Actor into Target" hint until you do. Both are safe no-ops, never a crash, when the target is null, has no entity component, or the map runs no state replicator. On an entity this client does not write, both are ignored and log a warning. That includes an entity another client owns and one Owned By World, which no client writes. On an entity this client does drive, marking a property that is auto-diffed anyway is a no-op logged at verbose level as `ignored: not a manual-dirty property`, never an error. The example is the same `TimesLit` member [Mark a property](#mark-a-property) added; this is the alternate call site, not a second gameplay moment. ```cpp // Lantern.cpp #include "Replication/State/CrowdyStateBlueprintLibrary.h" void ALantern::PushTimesLit() { // Schedule the same property from anywhere, without fetching the component first. UCrowdyStateBlueprintLibrary::MarkCrowdyStateDirty(this, TEXT("TimesLit")); } ``` From **Event ActorBeginOverlap**, the pure **Is Crowdy Entity Locally Owned** feeds a **Branch**, and the true side calls **Mark Crowdy State Dirty** with `Target` left unwired (self) and `TimesLit` picked from the Property Name dropdown. No component reference is needed. The branch is the owner gate the C++ caller has: on a proxy the same mark would still send, which is not what an overlap on a proxy means. [Blueprint snippet: state-static-dirty, see /bp/unreal-sdk/state-static-dirty.txt] ### The property picker The Property Name pin carries a dropdown, supplied in the editor by `FCrowdyStatePropertyPinFactory`, listing the resolved target class's properties that are marked `CrowdyManualDirty` and pass the type check. The dropdown is editor-only metadata scanning; the name you pick bakes into the compiled Blueprint as a literal `FName`, so a packaged build never reads metadata for this node. :::note[If your property is not in the dropdown, it is either auto-diffed already or it failed the type check.] An auto-diffed property does not need marking; assign it and it ships. A property that failed the check was omitted from the layout at startup with an error; see [What a state property may be](#what-a-state-property-may-be). ::: ## A field that silently does nothing The first thing to check. Discovery logs an unconditional error for every marked property it cannot carry, of the shape `CrowdyState: property 'X' on '/Script/MyGame.Lantern' is a container; CrowdyState does not replicate containers; use a CrowdyEvent RPC or a Server Object. Omitting it.` The reasons are a container, a struct that buries a container, a fixed-size array, an object or interface or delegate reference, or an otherwise unsupported type such as `FText`; [Rejected](#rejected) lists them. One more line to know: a property whose name and type also appear in the actor's continuous-state executor struct is dropped with `also lives in its executor state struct ... Dropping it from the CrowdyState layout`, so a field lives on exactly one channel. These fire at class registration and are not gated by the trace variable. Grep the log for `CrowdyState: property`, which all three lines share, before turning anything on. When the property is in the layout but the change is not arriving, that is the other question: ```text crowdy.state.trace 1 per delta: entity, changed-property count, byte size, spatial or owner-only or keyframe crowdy.state.loopback 1 decode your own deltas onto a local mirror entity, for a single-client test ``` Two read-only diagnostics on `UCrowdyStateReplicator` answer the same questions from code or Blueprint: `IsStateReplicated(Actor)` is true when the actor's class carries at least one accepted property, whichever client drives it, and `GetLastSentStateBytes(Actor)` is the blob size this client last sent for the actor, or -1 when this client does not drive it. `crowdy.state.scopes` adds a CPU trace scope around each delta decode for profiling. ## Gotchas - Grep for `CrowdyState: property` first. A property that is not in the layout replicates nothing and says so once, at startup, as an error. - The notify has no parameters and no old value. Keep the previous value yourself if you need it. - A Blueprint variable that is both natively Replicated and Crowdy Replicated fails to compile. In C++, keep `Replicated` off a `CrowdyState` property. - `CrowdyOwnerOnly` is delivery scope, not secrecy. The value still travels in the clear to the owner. - `StateKeyframeIntervalSeconds` at 0 stops the baseline re-send only; on-change replication is unaffected. - The loopback and trace variables are test aids. Leave them off in a normal session. - `FText` is not accepted on this plane, though it is on a CrowdyEvent. Use an `FString` or an `FName`. - A struct that is net-serialized is exempt from the nested-container check only because its serializer bounds the decode. A plain struct with a `TArray` inside is rejected however small the array. - Quantization is decided by the struct's type. To ship a quantized position, declare `FVector_NetQuantize`, not `FVector`. - `Target` on the static nodes defaults to self only where self is an actor. In a component or widget graph, wire the actor. - The push is scheduled, not sent. It goes out on the next replication tick with the value the property holds then. - Marking twice in one tick sends once. - No client writes an entity Owned By World by default, so assigning a plain property on it ships nothing. See [The Leader](./leader.md#who-writes-what). ## Related - [Continuous state](./continuous-state.md): the sibling channel for many fields that move together. - [Map profiles](./map-profile.md): the cadence, the relevance distance, and the keyframe interval. - [State meta keys](../reference/state-meta-keys.md). - [RPC events in C++](./rpc-events-cpp.md): containers and object references as event parameters. - [The Two Planes](../concepts/two-planes.md): what belongs on the truth plane instead. - [The Leader](./leader.md): who writes what. - [Ownership transfer](./ownership-transfer.md): making another client the owner of an entity. # Continuous State Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/continuous-state # Continuous State Continuous state is how a moving entity moves on every other client. When the entity component replicates movement, every replication interval the owner sends a snapshot of the actor's location, rotation and aim pitch; each other client within the map profile's [Movement Distance](./map-profile.md) (eight chunks by default) applies it to a proxy through the [rendering backend](./rendering-backends.md). There is nothing to write for that: the SDK's default executor takes the snapshot for you. ## When to use it Almost always the default is enough: a pawn, a player, an AI that moves. To send a value of your own with the movement, a lean, a stance, how far a character is leaning into a turn, mark the property [continuous](#send-your-own-values-with-the-movement). Write a custom snapshot only when you need to replace what the snapshot holds. For many small independent values that change at different times, prefer plain [Crowdy State](./crowdy-state.md) properties: they diff per property and ship only what changed. The two are independent channels, not alternatives; an entity can use both. :::warning[Replicate Movement is unrelated to ownership and to Crowdy State property replication.] `ReplicateMovement` on the entity component chooses whether the continuous channel runs. It does not decide where your replicated properties go, and Off does not disable them or events; all of them work either way. Turn movement on for a moving entity and nothing else changes. ::: ## The default: no executor at all `ReplicateMovement` is `Auto` by default: on for a pawn with a movement component (a Character, for one), off for anything else. So a character sends its movement with no setup, and a plain actor that should move must set `ECrowdyReplicateMovement::On`. `Off` sends no movement. `ReplicatesMovement()`, Blueprint node **Replicates Movement**, reads the answer. Leave `StateExecutor` unset. The SDK's `UCrowdyDefaultActorUpdateExecutor` snapshots the actor into `FCrowdyActorState`: a `Location`, a `Rotation`, and an `AimPitch` and deliberately nothing else. `AimPitch` is a float in degrees, filled from where a pawn is looking. With `bAutoRegister` on (the default) the component joins the channel at `BeginPlay`; off, you call `StartReplication` yourself, and `StopReplication` leaves the channel. The lantern world's mover is `ALanternPlayer`, the player character from the [Quickstart](../quickstart.md): a `UCrowdyEntityComponent` that sends its movement, with PlayerDerived identity, Owned By Player, and a `Torch` point light, so a moving light is what every other client sees. ```cpp // LanternPlayer.h #include "Components/PointLightComponent.h" #include "Replication/Components/CrowdyEntityComponent.h" #include "LanternPlayer.generated.h" UCLASS() class ALanternPlayer : public ACharacter { GENERATED_BODY() public: ALanternPlayer(); virtual void BeginPlay() override; UPROPERTY(VisibleAnywhere, Category = "Lantern") TObjectPtr Torch; UPROPERTY(VisibleAnywhere, Category = "Crowdy") TObjectPtr CrowdyEntity; }; // LanternPlayer.cpp #include "LanternPlayer.h" ALanternPlayer::ALanternPlayer() { Torch = CreateDefaultSubobject(TEXT("Torch")); Torch->SetupAttachment(RootComponent); // A character sends its movement by default; Player Derived names the entity after the signed-in user, Owned By Player makes this client its sender. CrowdyEntity = CreateDefaultSubobject(TEXT("CrowdyEntity")); CrowdyEntity->IdentityPolicy = ECrowdyIdentityPolicy::PlayerDerived; CrowdyEntity->OwnedBy = ECrowdyOwnedBy::Player; } ``` A Character sends its movement by default, so leave **Replicate Movement** at **Auto** and **State Executor** empty. On a plain actor that should move, set **Replicate Movement** to **On**. There is no graph to build: **Auto Register** joins the channel at BeginPlay. ## Animating a remote character A remote character on the actor pool animates with no custom code. The policy gives a proxy's stopped movement component a velocity and an acceleration from the snapshots, and sets its remote view pitch from `AimPitch`. An Animation Blueprint that reads velocity and **Get Base Aim Rotation** works unchanged. Two limits: - A proxy plays no jump or fall animation, because its movement mode is None. - **Get Base Aim Rotation** reads 0 to 360 on a proxy, so looking down at -40 degrees reads 320. An aim offset must run the pitch through **Normalize Axis** first. Mass rows ignore aim pitch. Start the pawn only once the SDK reports the connection up (`OnUDPConnectionSuccess`, or `GetUDPConnectionState()` at `Connected`); the Quickstart spawns it from that event, and the Gotchas say why. **Success signal.** On a second client the player's torch moves with the owner. `crowdy.entity.trace 1` logs the registration; if nothing moves, check [the backend config](./map-profile.md) before the executor. :::caution[A World-owned entity that replicates movement leaves BeginPlay sending nothing.] `bAutoRegister` starts the channel only for an entity this client owns outright. A level-placed entity that replicates movement, Owned By World (or Auto) has no owner at `BeginPlay`, so nothing is sent; the component logs this once. No client writes a World entity, so it stays still for everyone. An owner drives it after an [ownership transfer](./ownership-transfer.md). ::: ## Send your own values with the movement Mark a [Crowdy State](./crowdy-state.md) property continuous and it travels on the entity's movement updates instead of as a delta of its own. You write no executor, no state struct and no rendering policy. Use it for a value that changes as often as the movement does, so that a delta per change would cost more than the update it can ride. `ALanternPlayer`'s torch sways with every step: ```cpp // LanternPlayer.h // Sways with every step, so it rides the movement updates rather than going as a delta of its own. UPROPERTY(BlueprintReadOnly, Category = "Lantern", meta = (CrowdyState, CrowdyContinuous, CrowdyOnRep = "OnRep_TorchSway")) float TorchSway = 0.f; UFUNCTION() void OnRep_TorchSway(); // LanternPlayer.cpp void ALanternPlayer::OnRep_TorchSway() { Torch->SetRelativeRotation(FRotator(0.f, 0.f, TorchSway)); } ``` Select the variable, and in the Details panel set **Crowdy Replication** to **Replicated (Continuous)**. The **RepNotify** row works as it does for **Replicated**. **Advanced** is hidden, because none of its options apply. Recompile. What you get: - **Every client in range.** The value goes when it changes and on every keyframe, so a client that joins later gets it within `ActorKeyframeIntervalSeconds`. A steady value costs nothing between keyframes. A change lost on the way is repaired by the next change or keyframe. - **Applied on arrival.** The value lands as the update arrives, about one interpolation delay ahead of the drawn position. Its `CrowdyOnRep` runs on every client that took a new value and on the owner. - **On Mass rows too.** An entity drawn as a crowd row receives the value through a [state fragment field](../mass/add-your-own-crowd-data.md), as it does any Crowdy State property. A row has no notify. :::warning[A continuous value is for a class that replicates movement.] On a class that does not, the property warns once and replicates as ordinary Crowdy State, so nothing is lost. The same happens with `CrowdyOwnerOnly` or `CrowdyManualDirty` on the property: a movement update reaches everyone near and has its own clock. On an entity whose updates are stopped, with `StopReplication` or before `StartReplication`, the property goes as a delta and on every keyframe until they start. ::: Continuous values are for properties on the actor class, not on its components, and together they share one datagram with the movement: about 1,000 bytes, less your snapshot. Past that they are left off and the log says so. Keep long strings in plain Crowdy State. ## A custom executor Subclass `UActorUpdateExecutor` when the snapshot needs more than a transform. Two functions: `GetActorState(UpdateComponent)` returns the `FInstancedStruct` snapshot (`UpdateComponent` is the entity component; `GetOwner()` on it is the actor), and `GetStateStruct()` returns the `UScriptStruct` it is made of, which registers the type for the wire; the struct needs no annotation. :::danger[Override the `_Implementation` functions, with `const`, never the bare event names.] Both are `BlueprintNativeEvent`s, so the bare names are not virtual in the generated C++. A native subclass declares `GetActorState_Implementation(const UActorComponent*) const override` and `GetStateStruct_Implementation() const override`; `UCrowdyDefaultActorUpdateExecutor` is the shipped example of the correct shape. Marking `GetActorState` itself `override` does not compile, because there is nothing virtual to override. ::: `ULanternPlayerExecutor` snapshots `FLanternPlayerState`: the transform the default carries plus one field of the player's own, `bTorchLit`, so a proxy's torch can follow its owner's. The struct is declared next to the executor, and the executor is assigned to `StateExecutor` in the character's constructor. On the other clients the snapshot is applied by the backend's [replication application policy](./rendering-backends.md#the-replication-application-policy), which is what moves a remote player's proxy: the shipped one applies `Location` and `Rotation`, and a policy of your own replaces it, so write one only when your executor sends more than the transform, and then apply the transform yourself first. ```cpp // LanternPlayer.h #include "Replication/Executor/ActorUpdateExecutor.h" // The custom snapshot: the transform the default carries, plus one field of your own. USTRUCT() struct FLanternPlayerState { GENERATED_BODY() UPROPERTY() FVector Location = FVector::ZeroVector; UPROPERTY() FRotator Rotation = FRotator::ZeroRotator; UPROPERTY() bool bTorchLit = true; }; UCLASS() class ULanternPlayerExecutor : public UActorUpdateExecutor { GENERATED_BODY() public: virtual FInstancedStruct GetActorState_Implementation(const UActorComponent* UpdateComponent) const override; virtual UScriptStruct* GetStateStruct_Implementation() const override; }; // LanternPlayer.cpp CrowdyEntity->StateExecutor = CreateDefaultSubobject(TEXT("Executor")); FInstancedStruct ULanternPlayerExecutor::GetActorState_Implementation(const UActorComponent* UpdateComponent) const { FLanternPlayerState State; if (const ALanternPlayer* Player = UpdateComponent ? Cast(UpdateComponent->GetOwner()) : nullptr) { State.Location = Player->GetActorLocation(); State.Rotation = Player->GetActorRotation(); State.bTorchLit = Player->Torch->IsVisible(); } return FInstancedStruct::Make(State); } UScriptStruct* ULanternPlayerExecutor::GetStateStruct_Implementation() const { return FLanternPlayerState::StaticStruct(); } ``` Create a Blueprint with **Actor Update Executor** as its parent class. In **My Blueprint**, under Functions, press **Override** and pick the two functions: ![Get Actor State and Get State Struct in the override list of an Actor Update Executor Blueprint](/img/unreal-sdk/bp-executor-overrides.png) **Get State Struct** returns the struct type; **Get Actor State** builds the snapshot with **Make InstancedStruct** from the owning actor's transform. Then set the character's **State Executor** to the new class in the Details panel. An override on an executor subclass is not an actor event graph, so the screenshot above is the reference. :::caution[Only the owner runs GetActorState. Keep it a read-only snapshot.] A remote proxy is fed from the network and never calls it, so a side effect inside the override happens on one client only; a value the proxy needs comes from the backend's policy. Read the actor, fill the struct, return it. ::: The owner evaluates `GetActorState` every interval (`ReplicationIntervalHz`, 10 by default, 1 to 10 Hz, one clock shared with Crowdy State; `bUseAutoReplicator` off means no polling at all). With `bSendActorStateOnlyOnChange` on, the default, an unchanged snapshot does not repeat: a full keyframe goes out every `ActorKeyframeIntervalSeconds` (3 s), which is what other players receive from an idle entity and so what keeps it on their screens, and a heartbeat every `ActorHeartbeatIntervalSeconds` (1 s), which only keeps its presence on the server from going stale; off, the snapshot goes out every interval whether it changed or not. The [map profile](./map-profile.md) page lists each field. A field lives on exactly one channel: a `CrowdyState` property whose name and canonical type also match a field of the executor struct is dropped from the Crowdy State layout at discovery, with an error mentioning `also lives in its executor state struct`. ## Teleporting a player To teleport your own player, move the pawn: `SetActorLocation` with teleport physics, or `TeleportTo`. Nothing else is needed for other players to see a snap. On the actor pool backend and on the Mass backend (crowd rows), a copy glides between updates, but an update farther than the map profile's **Snap Distance** (default 10 m) from the one before it places the copy at the new spot: no glide across the gap and nothing drawn past it. Each client decides this from the positions alone, so it works for any sender, an older Unreal client or the web SDK included. On the actor pool it is the shipped `UCrowdyTransformRepPolicy` (or a subclass) that snaps, given the distance with `SetSnapDistance`; a [replication policy](./rendering-backends.md) of your own glides across a teleport unless it snaps itself. Anything that moves farther than Snap Distance between two updates snaps on every update instead of gliding. At the default Send Rate of 10 updates a second and 10 m, that is anything faster than 100 m/s (360 km/h), so characters are never affected; a map with fast vehicles sets a larger **Snap Distance**. A burst of lost packets on a fast mover can also snap instead of glide. **Request Teleport Permission** on the Crowdy SDK subsystem asks the platform whether the destination chunk may be entered. It is optional and separate: it moves nothing. See [Grids](../studio/grids.md). ## Gotchas - `ReplicateMovement` is orthogonal to `OwnedBy` and to Crowdy State. Do not set it On hoping to make properties replicate; they already do. - `_Implementation`, `const`, `override`. The shipped default is the template. - Nothing is held until the connection is up. `OnUDPConnectionSuccess` already includes the server's readiness wait after assignment, so you never time anything; but an actor update sent before it is neither held nor replayed, so it is lost, mostly silently, until the next interval's update or keyframe repairs it. An entity you own that replicates movement and begins play early heals that way; spawn a player pawn from the event instead, as the Quickstart does. - An unchanged actor is not silent. Set both intervals to 0 and an idle entity sends nothing after its first snapshot, and its observers time it out after the tracker's `ActorTimeoutThreshold`. - The policy is what moves the proxy. With no Backend Config the shipped `UCrowdyTransformRepPolicy` applies `FCrowdyActorState`, interpolating across a ring of recent samples with bounded extrapolation; a custom struct like `FLanternPlayerState` is skipped until the profile names a policy that reads it, and that policy must apply the transform itself, or the proxy stands still while the owner moves. - Class identity travels on every update, so several entity classes may share one state struct; the receiver never derives the class from the struct. This is what lets the default executor serve every entity in a project. - `RegisterStateClass` on `UCrowdyActorManager` is filled for you at `BeginPlay`; you never call it. ## Related - [Quickstart](../quickstart.md): the player pawn as an entity that replicates movement, spawned once connected, and your own reflection as the first thing you see. - [Entity component](./entity-component.md): `ReplicateMovement`, `StateExecutor`, `bAutoRegister`, `StartReplication`. - [Rendering backends](./rendering-backends.md): the policy that moves a proxy from the snapshot. - [Map profiles](./map-profile.md): the cadence and the keyframe and heartbeat intervals. - [Connection and reconnect](./connection-and-reconnect.md): what `OnUDPConnectionSuccess` and `Connected` mean. - [Crowdy State](./crowdy-state.md): the per-property alternative. # The Leader Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/leader # The Leader Some view-plane state belongs to no player: a village clock, a weather phase. One client has to write it, and that client is the **Leader**. A Server Object the SDK deploys for you picks it: the first player to join leads, and when that player goes, the longest-standing member takes over. There is one Leader per app. Choosing the Leader on the server keeps the choice in one place. It does not make what the Leader writes trustworthy: that is still [view plane](../concepts/two-planes.md) state, which a modified client can lie about. ## Who writes what | What | Who writes it | |---|---| | An entity Owned By **Player** | Its owner: the player who spawned it, or the player it was [transferred](./ownership-transfer.md) to. | | An entity Owned By **World** (an actor placed in the level, by default) | No client. Keep what changes about it on the [truth plane](../concepts/two-planes.md), in a Server Object. Its events still work: any client can send one. | | An entity Owned By **Leader** | The Leader, whoever that is now. See [An NPC the Leader simulates](#an-npc-the-leader-simulates). | | A [replicated subsystem](./replicated-subsystems.md) | The Leader. | ## Deploy the server code once The Leader lives in a Server Object type the SDK adds to every deploy (`crowdy_leader`, shown in [Server Compute](../exec/deploy-with-server-compute.md) as the SDK's own). There is nothing to create. Deploy your app's server code once, then restart what still runs older code, from Server Compute or with: ``` UnrealEditor-Cmd.exe MyGame.uproject -run=CrowdyServerCompute -op=deploy -yes UnrealEditor-Cmd.exe MyGame.uproject -run=CrowdyServerCompute -op=restart -yes ``` A running root type keeps the code it started with, and the Leader asks the root whether a player is still in the world, so the restart is not optional. Until the code is deployed there is no Leader. Each signed-in client tries again every 10 seconds and logs one warning. Server code deployed with an SDK older than this one has no **Enter** on the Leader type. Then each client logs one warning per sign-in that the server code must be deployed again and its running instances restarted, and tries again quietly every 60 seconds. Nothing writes Leader-owned entities or replicated subsystems until you deploy. **Success signal.** With two clients signed in and each with a Player Derived pawn, `Get Leader User ID` returns the same id on both, and `Is Local Leader` is true on exactly one. ## Checking who writes an entity `UCrowdyUtilities::IsCrowdyEntityLocallyOwned(Entity)` returns true when this client writes `Entity`: it owns the entity, or `Entity` is a replicated subsystem and this client is the Leader. It is a pure node, **Is Crowdy Entity Locally Owned**, in Blueprint; **Switch Is Crowdy Entity Locally Owned** (`SwitchIsCrowdyEntityLocallyOwned`) is the same answer as two exec pins. `Entity` is an entity actor or a replicated subsystem, and defaults to Self. Ask this before you write something, and pass the thing you are about to write. For a World entity the answer is false on every client, because no client writes it. When something needs a writer and has none, such as marking a World entity's state dirty, the SDK logs a warning. In C++, `UCrowdyEntitySubsystem::GetAppWriterID()` returns the actor id the Leader type publishes for the Leader (empty while there is none, see [When the Leader leaves](#when-the-leader-leaves)), and `GetWriterID(Record)` returns the client that writes a record with no owner: the Leader for a replicated subsystem, nobody for a World entity. Every ownership check follows one rule, `FCrowdyEntityRecord::IsWrittenBy`, which `UCrowdyEntitySubsystem::IsRecordLocallyOwned(Record)` applies with this client's ids. Two more helpers on `UCrowdyUtilities` answer ownership questions without a round trip. `DoesCrowdyEntityOwn(OwnerActor, TargetActor)` is true when the first actor's session writes the second. It asks about sessions, so a second session of the same account does not own what the first writes; for the account, compare **Get Crowdy Entity Owner User ID** or use **Is Crowdy Entity Owned By Local User**. A World entity owns nothing and is owned by no one, the Leader included. `CrowdyIsConnectedToServer` says whether there is a connection at all. **Switch Crowdy Has Authority** and **Crowdy Has Authority** are gone. They asked whether this client is the host, with no entity to ask about: use **Is Local Leader** for the same question, true on one client only. Use **Switch Is Crowdy Entity Locally Owned** only to gate a write to an entity or subsystem you own, and put logic that must be enforced in a Server Object. ## Follow the Leader `UCrowdyLeaderSubsystem` is a game-instance subsystem in the `CrowdyExec` module, so a C++ caller adds `CrowdyExec` to its `Build.cs` and includes `CrowdyLeaderSubsystem.h`. `GetLeaderUserID()` is the Leader's user id, 0 while there is none or it is not known yet. `IsLocalLeader()` says whether this client leads. `OnLeaderChanged` (`FOnCrowdyLeaderChanged`, `NewLeaderUserID`, `PreviousLeaderUserID`, on the game thread) fires when the lead moves, and a user id of 0 means there is no Leader. Bind the event rather than reading the answer once at `BeginPlay`: the Leader is not known that early on a fresh sign-in, and it changes when the Leader leaves. A map loaded after the Leader is known hears no change, so also read the answer once. The lantern world shows the lead on its posts: an `ALanternPost` burns bright on the client that leads and dim everywhere else, and the bright post moves when the lead does. ```cpp // LanternPost.h void WatchLeader(); UFUNCTION() void HandleLeaderChanged(int64 NewLeaderUserID, int64 PreviousLeaderUserID); // LanternPost.cpp #include "CrowdyLeaderSubsystem.h" #include "Engine/GameInstance.h" void ALanternPost::WatchLeader() { UCrowdyLeaderSubsystem* Leader = GetGameInstance()->GetSubsystem(); Leader->OnLeaderChanged.AddDynamic(this, &ALanternPost::HandleLeaderChanged); // A post that loads after the Leader is known hears no change, so it reads the answer once. HandleLeaderChanged(Leader->GetLeaderUserID(), 0); } void ALanternPost::HandleLeaderChanged(int64 NewLeaderUserID, int64 PreviousLeaderUserID) { const UCrowdyLeaderSubsystem* Leader = GetGameInstance()->GetSubsystem(); Light->SetIntensity(Leader->IsLocalLeader() ? 5000.f : 1000.f); } ``` At **Event BeginPlay**, a **Crowdy Leader Subsystem** getter feeds **Bind Event to On Leader Changed**, whose custom event `OnLeadMoved` calls **Set Intensity** on `Light`. **Is Local Leader**, off a second getter, picks the value through a **Select Float** with `A` at 5000 and `B` at 1000. To cover a post that loads after the Leader is known, also call `OnLeadMoved` after the bind. [Blueprint snippet: leader-gate, see /bp/unreal-sdk/leader-gate.txt] :::danger[The Leader is a convention, not enforcement. Never gate cheat-sensitive state on it.] Nothing on the wire is rejected for not coming from the Leader, and a modified client can act as if it leads. Use the Leader to pick who writes shared cosmetic state; anything a player could gain by leading is decided by your server code, on the [truth plane](../concepts/two-planes.md). ::: **Success signal.** With two clients, the post is bright on exactly one of them. Close that client and the post brightens on the other. The effect is local by design: a value the whole village must see is a [Crowdy State](./crowdy-state.md) property on a replicated subsystem. ## When the Leader leaves The longest-standing member takes over, and `OnLeaderChanged` fires on every client. How long that takes depends on how the Leader went. | The Leader's client | The new Leader takes over | |---|---| | Leaves or signs out | At once. | | Crashes | About half a second later, when its connection closes. | | Loses only its realtime connection | About 10 seconds later, when the server hears it left the realtime world. A client that sees its own connection fail leaves by itself, which is sooner. | | Freezes with its connection open | About 10 seconds later, for the same reason. | Only a player in the realtime world with an actor id can lead. A client joins once its realtime connection is up and it holds an actor id (a Player Derived pawn, a Crowdy Spectator component or a chat message mints it), and leaves when the SDK reports that the connection failed. A client with no actor id stays out, so it cannot lead while writing nothing. A project where nothing mints an actor id has no Leader, and the SDK warns once per sign-in if a client still has none a second after it could have joined. The new Leader starts writing from the values it last received, so a subsystem carries on where the old Leader stopped, minus anything that had not reached it yet. A player's actor id is random, so no client can work out the Leader's from its user id. Each client joins the Leader type with its own actor id (its **Enter** function). The type publishes the Leader's id in the same change that moves the lead, so every client goes straight from the old Leader's id to the new one's. Each client takes Leader-owned writes only under the id of the player who leads now. A client enters again when a sign-in gives it a new id. Of two sessions of one user, only the last to enter leads. A client that becomes the Leader before its id is published hears **On Leader Changed** once it can write. ## An NPC the Leader simulates Some entities need one client to simulate them for everyone: an NPC that walks the navmesh or falls under physics. Set **Owned By** to **Leader** on its [entity component](./entity-component.md), with **Replicate Movement** **On** (an NPC that is not a pawn with a movement component needs it), and simulate only on the client that writes it. The lamplighter walks the lane on whichever client leads, and every other client draws it. ```cpp // Lamplighter.h #include "GameFramework/Actor.h" #include "Lamplighter.generated.h" class UCrowdyEntityComponent; UCLASS() class ALamplighter : public AActor { GENERATED_BODY() public: ALamplighter(); virtual void Tick(float DeltaSeconds) override; private: UPROPERTY(VisibleAnywhere) TObjectPtr CrowdyEntity; }; // Lamplighter.cpp #include "Lamplighter.h" #include "Replication/Components/CrowdyEntityComponent.h" #include "Utils/CrowdyUtilities.h" ALamplighter::ALamplighter() { PrimaryActorTick.bCanEverTick = true; CrowdyEntity = CreateDefaultSubobject(TEXT("CrowdyEntity")); CrowdyEntity->ReplicateMovement = ECrowdyReplicateMovement::On; CrowdyEntity->OwnedBy = ECrowdyOwnedBy::Leader; } void ALamplighter::Tick(const float DeltaSeconds) { Super::Tick(DeltaSeconds); // Asked every tick: the client that writes the lamplighter changes when the lead moves. if (!UCrowdyUtilities::IsCrowdyEntityLocallyOwned(this)) { return; } AddActorWorldOffset(GetActorForwardVector() * 100.f * DeltaSeconds); } ``` On the component, set **Owned By** to **Leader**. In the graph, **Event Tick** runs a **Branch** on **Is Crowdy Entity Locally Owned**, and its **True** pin runs **Add Actor World Offset**. [Blueprint snippet: leader-npc, see /bp/unreal-sdk/leader-npc.txt] **Success signal.** With two clients, the lamplighter moves on both and `Is Crowdy Entity Locally Owned` is true on exactly one. Close that client: the lamplighter stops on the other, then moves on from there once that client leads. - **Ask each tick, not once.** Who writes the entity changes when the lead moves, so a check at `BeginPlay` goes stale. - **Only the Leader spawns or destroys one.** On any other client **Spawn Crowdy Entity** returns null and logs a warning, so check **Is Local Leader** first. **Destroy Entity** is refused the same way. - **Its owner follows the lead.** [Ownership requests and grants](./ownership-transfer.md) on it are refused with a warning. - **Through a hand-off the body stays put.** Other clients keep it where it stopped until the next Leader sends. A new Leader's pawn movement is switched back on when it takes over, and with **Auto Register** off it waits for your `StartReplication` call. :::caution[One Leader, for players who share a map.] There is one Leader per app, and it writes only what it has a body for: the entities it spawned, and the ones it already drew when it took over. A Leader takes no entity it never had, because a spawn event or an update can be forged. So when the lead moves to a player on another map, or to one who was never near the entity, nobody writes it: other clients hold a spawned body for 20 seconds and then release it, and a body placed in the level stays where it stopped. For NPCs across maps or a large open world, use [hub NPCs](../exec/use-game-kit-starters.md), which run on the server and need no Leader. Leader entities need an actor pool map: on a [crowd-row map](./rendering-backends.md) the SDK warns once per class, because a row has no actor for a new Leader to take over. ::: ## Gotchas - `Get Leader User ID` is 0 until the client has joined. `Is Local Leader` is false until then, which does not mean someone else leads. - For a moment around a hand-off, two clients can both believe they lead. Keep what a Leader writes safe to write twice. - A new Leader sends the values it holds. If it joined late and missed one, its value replaces the one other clients had. Anything that must survive a hand-off belongs in a Server Object. - A World entity's plain property does nothing when you assign it, and marking it dirty logs a warning: no client writes it. - **Is Crowdy Entity Player Controlled** is false for an entity Owned By Leader, on every client. - A client that walks out of a Leader entity's range holds its spawned body for 20 seconds too, so count that when you size **Max Pool Size Per Class**. - The Leader's user id is a user id, not the actor id entities are written under. Compare it with your own user id, or use `IsLocalLeader()`. To ask whether an actor is the Leader's, run **Resolve Actor Owner** on its id and compare the user with **Get Leader User ID**, after checking that is not 0. ## Related - [A Coordinator Is a Convention](../concepts/host-is-a-convention.md): why a client chosen to coordinate is not a referee. - [Replicated subsystems](./replicated-subsystems.md): what the Leader writes. - [Server Objects](../exec/overview.md): where World entities keep their truth. - [Entity component](./entity-component.md): `OwnedBy` and `IsLocallyOwned`. # Ownership Transfer Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/ownership-transfer # Ownership Transfer An entity spawned at runtime belongs to its spawner. Ownership transfer moves it: a client asks, the entity's owner grants or ignores, and the grant lands on every client. `UCrowdyOwnershipTransfer` is a static Blueprint library with the three verbs. ## When to use it A player takes over a lantern post another player built, a vehicle changes driver. Anything where "who simulates this" should change hands without destroying and respawning. A level-placed entity Owned By World has no writer, so nobody answers a request for it. An entity [Owned By Leader](./leader.md#an-npc-the-leader-simulates) follows the Leader instead, so requests and grants for it are refused with a warning. A player's avatar is not meant to change hands: every client, the player's own included, refuses a grant for a player's avatar, whatever the grant says. Other clients cannot tell a grant from a modified client apart, as the warning below says. :::warning[Ownership is a coordination convention on the view plane, not enforcement, and a transfer is transient.] No server checks who may request or grant. And a client that first observes the entity after a grant sees the spawn-time owner, or re-baselines from proxy defaults, not necessarily the transferred one. Cheat-sensitive ownership belongs on the [truth plane](../concepts/two-planes.md), in your server code. ::: ## The flow 1. A client that does not own the entity calls **Request Ownership Transfer**. The request travels as a Multicast `CrowdyEvent` on the session channel (`UCrowdyEntityComponent::RequestOwnership_Implementation`), so every client sees it, and only the entity's owner reacts. 2. On the owner, either `bAutoApproveOwnershipRequests` on the component is on and the grant happens at once, or `UCrowdyEntitySubsystem::OnOwnershipRequested` fires for game code to decide. 3. Game code approves by calling one of the two grant nodes, or ignores the request. There is no deny node; silence is the rejection. 4. The grant travels the same way (`GrantOwnership_Implementation`), every client re-points the entity's record through `UCrowdyEntitySubsystem::ReassignOwnership`, and `OnEntityOwnershipChanged` fires everywhere once ownership has actually moved. ## The three nodes | Node | C++ | Who calls it | |---|---|---| | **Request Ownership Transfer** | `RequestOwnershipTransfer(WorldContextObject, TargetEntity)` | Any client that does not own the entity. A no-op when the target is not a registered entity or this client already writes it. | | **Grant Ownership Transfer** | `GrantOwnershipTransfer(WorldContextObject, TargetEntity, NewOwner)` | The current owner. `NewOwner` is any entity the new owner's player owns, typically their avatar. The grant names the session that writes `NewOwner` (for another player's avatar, that player's session; for a record with a writer, that writer) and the user this client knows for it, 0 for another player's avatar. A `NewOwner` that is neither names nobody, and the grant is refused. | | **Grant Ownership Transfer To Player** | `GrantOwnershipTransferToPlayer(WorldContextObject, TargetEntity, NewOwnerPlayerID, NewOwnerUserID = 0)` | The current owner, with the requester's id and user straight from `OnOwnershipRequested`; no local actor of theirs is needed. `New Owner User ID` left at 0 makes the new owner's user unknown to other clients; it never changes who writes the entity. | Every node resolves the target's entity component and subsystem and is a safe no-op, never a crash, on a null or unregistered target. Both grants funnel through the component's C++ `GrantOwnershipTo(NewWriterID, NewOwnerUserID)`, which is also a no-op with a warning unless this client is the current owner. :::caution[Grant Ownership Transfer refuses a NewOwner that is not client-owned.] Passing an actor no client owns (a World entity, `WorldOwned`) or an unregistered actor logs a warning and does nothing. ::: The lantern world's transfer is a player claiming a lantern post another player spawned. A post spawned during play belongs to its spawner; the second player asks for it, and the owner approves. The request: the post's overlap, when this client does not own the post, calls `TryClaim`: ```cpp // LanternPost.h // A player who walks into a post they do not own asks to carry it. virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; void TryClaim(); // LanternPost.cpp #include "Replication/Ownership/CrowdyOwnershipTransfer.h" void ALanternPost::NotifyActorBeginOverlap(AActor* OtherActor) { Super::NotifyActorBeginOverlap(OtherActor); if (!CrowdyEntity->IsLocallyOwned()) { TryClaim(); } } void ALanternPost::TryClaim() { UCrowdyOwnershipTransfer::RequestOwnershipTransfer(this, this); } ``` The grant, on the owner: `HandleOwnershipRequested`, bound to `OnOwnershipRequested` in `BeginPlay`, ignores requests for other entities and grants the post to the requester: ```cpp // LanternPost.h UFUNCTION() void HandleOwnershipRequested(AActor* TargetEntity, AActor* RequesterActor, const FGuid& RequesterID, int64 RequesterUserID); // LanternPost.cpp #include "Replication/Ownership/CrowdyOwnershipTransfer.h" #include "Replication/Subsystems/CrowdyEntitySubsystem.h" GetWorld()->GetSubsystem()->OnOwnershipRequested.AddDynamic(this, &ALanternPost::HandleOwnershipRequested); void ALanternPost::HandleOwnershipRequested(AActor* TargetEntity, AActor* RequesterActor, const FGuid& RequesterID, int64 RequesterUserID) { if (TargetEntity != this) { return; } UCrowdyOwnershipTransfer::GrantOwnershipTransferToPlayer(this, this, RequesterID, RequesterUserID); } ``` From **Event ActorBeginOverlap**, **Request Ownership Transfer** with `Target Entity` wired to a Self reference; the "not already mine" check the C++ makes is a no-op inside the node anyway, since a request for an entity you already own does nothing: [Blueprint snippet: own-request, see /bp/unreal-sdk/own-request.txt] The grant: at **Event BeginPlay**, a **Crowdy Entity Subsystem** getter feeds **Bind Event to On Ownership Requested**, whose custom event `OnClaimRequested` compares its `Target Entity` with a Self reference (**==** into a **Branch**, because the event fires for every entity this client owns) and, when they match, passes its `Requester ID` and `Requester User ID` to **Grant Ownership Transfer To Player** with `Target Entity` wired to self. Eight nodes; the compare is the guard the C++ has: [Blueprint snippet: own-grant, see /bp/unreal-sdk/own-grant.txt] **Success signal.** `OnEntityOwnershipChanged` fires on both clients with the new owner's id, the post's `IsLocallyOwned()` turns true on the requester and false on the old owner, and `OnCrowdyOwnershipAssigned` on the post's component fires with `bIsLocallyOwned` matching. ## The two events On `UCrowdyEntitySubsystem`, both Blueprint-assignable, both on the game thread: | Event | Parameters | Fires | |---|---|---| | `OnOwnershipRequested` (`FOnCrowdyOwnershipRequested`) | `TargetEntity`, `RequesterActor`, `RequesterID`, `RequesterUserID` | On the entity's owner only, when another client requests it. `RequesterActor` is the requester's avatar when this client holds it, else null; `RequesterID` is always valid; `RequesterUserID` is the user the requesting session claims, 0 when it was signed out, so pass it on to the grant. | | `OnEntityOwnershipChanged` (`FOnCrowdyEntityOwnershipChanged`) | `TargetEntity`, `NetID`, `NewOwnerID`, `PreviousOwnerID` | On every client once the writer has actually changed. Both ids are writer ids; `NewOwnerID` is invalid when the entity went back to the world. | `bAutoApproveOwnershipRequests` is authored config on the component, read on the owner when a request arrives. Changing it at runtime on one client affects only the requests that client receives while it owns the entity. ## What happens to in-flight state The entity record is the single source of truth for both planes, so re-pointing its owner is the whole transfer: RPC routing and Crowdy State tracking follow. The old owner stops sending the moment it relinquishes; the new owner builds a fresh shadow of the entity's properties and starts diffing; bystanders are untouched. The actor's NetID never changes, so every address stays valid. On the wire, each owner of an entity that replicates movement sends under an actor id of its own, made from the NetID and the owner, because the server keeps an id for the first session that sends it. Every client reads that id back to the same NetID, keeps one body, and drops anything the old owner still sends. An **Owning Client** event finds the current owner the same way. You never see these ids in game code. They do mean every client has to run the same SDK version: an older one reads the new id as another entity and draws a second body. :::caution[There is a brief window with no writer.] Between the old owner relinquishing and the reliable grant landing on the new owner, nobody diffs the entity. There is never a double writer, but for that short window there is no writer at all, by design. The continuous channel of an entity that replicates movement moves with the owner the same way: the new owner joins it and the old one leaves. ::: A grant carries the previous writer's id, and `ReassignOwnership` compares and swaps on it, so a stale or duplicate grant is dropped rather than applied twice. A client that joined after the entity spawned may not know its owner, and takes the grant anyway. The user a grant names is stored with the new writer, or left unknown for 0; it never takes part in the swap. A grant that keeps the writer only fills in a user the client did not know, and fires no ownership event. The grant and the request have new function ids, so rebuild and repackage a packaged game. ## Gotchas - Silence is the rejection. If you want the requester to know, send them an `OwningClient` event yourself. - The request short-circuits on the component's `IsLocallyOwned()`, so the client that already writes an entity cannot request it by accident. - Granting to a player id with no local presence orphans the entity until it is granted again. Check the requester is still in the session before you grant. - A new owner that never observed the entity re-baselines from proxy defaults. The durable truth lives in your server code, not on the view plane. - Two Multicast events on the component carry all of this. Never give them a `CrowdyChannel`; see [Entity component](./entity-component.md). ## Related - [The Leader](./leader.md): who writes what, and why a World entity has no writer. - [Entity component](./entity-component.md): `bAutoApproveOwnershipRequests`, `OnCrowdyOwnershipAssigned`, and the two receivers. - [Crowdy State](./crowdy-state.md): the shadow and the diff the transfer restarts. - [Entities, Identity, and Ownership](../concepts/entities-identity-ownership.md). # Replicated Subsystems Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/replicated-subsystems # Replicated Subsystems A UE subsystem is not an actor, but it can take part in both view-plane mechanisms: `meta=(CrowdyState)` properties diff and replicate on it exactly as on an actor, and `meta=(CrowdyEvent)` functions ride the reliable channel. Two abstract bases do the enrollment; a function library exists for the cases they do not cover. One client writes a replicated subsystem for everyone: [the Leader](./leader.md). The subsystem is auto-diffed on the Leader, so assign the property and the change ships. Its deltas ride the reliable channel with no spatial filter. For this to work the app's server code must be deployed once, which [the Leader page](./leader.md#deploy-the-server-code-once) covers. ## When to use one For a world-level value that belongs to nobody in particular and every client should agree on: a village clock, a weather phase, a match state on the view plane. A subsystem is a singleton every client resolves by class path with no handshake, so it is the natural home for "the one of these". :::danger[Written by the Leader, on the view plane. A replicated subsystem is not where a score lives.] The Leader is a convention here as everywhere on this plane. A match score, a winner, anything a client could gain by lying about, belongs on the [truth plane](../concepts/two-planes.md); a subsystem is for the shared cosmetic state around it. ::: ## Inherit a base | Base | Extends | Enrolls | |---|---|---| | `UCrowdyReplicatedWorldSubsystem` | `UWorldSubsystem` | Once, in its own `Initialize`; unenrolls in `Deinitialize`. Created only in Play in Editor and game worlds. | | `UCrowdyReplicatedGameInstanceSubsystem` | `UGameInstanceSubsystem` | Per world: into each new world's registry when that world's actors are initialized, out again as the world is cleaned up. It outlives worlds, and the entity registry it enrolls into is per world. | A replicated subsystem is always written by the Leader: a per-owner proxy makes no sense for a class every client holds exactly once. There is nothing to override to choose its writer. The lantern village's night clock is a world subsystem: `ULanternNightSubsystem` holds one Crowdy State property, `NightPhase`, marked `CrowdyHeartbeat` so a late joiner converges, with a notify, `OnRep_NightPhase`, that sets every lantern's intensity from the phase, two CrowdyEvents, `AnnounceDawn`, a Multicast that resets the phase on every client, and `RequestNextPhase`, an Owning Client event any client can send to ask the Leader for the next phase, and a `BlueprintCallable`, `AdvanceNight`, the Leader calls to step it. ```cpp // LanternNight.h #include "Replication/RPC/CrowdyEvent.h" #include "Replication/Subsystems/CrowdyReplicatedSubsystem.h" #include "LanternNight.generated.h" // A world subsystem replicates both planes at once: a CrowdyState property and a CrowdyEvent. UCLASS() class ULanternNightSubsystem : public UCrowdyReplicatedWorldSubsystem { GENERATED_BODY() public: UPROPERTY(meta = (CrowdyState, CrowdyHeartbeat, CrowdyOnRep = "OnRep_NightPhase")) uint8 NightPhase = 0; UFUNCTION() void OnRep_NightPhase(); UFUNCTION(meta = (CrowdyEvent, CrowdyRecipient = "Multicast")) void AnnounceDawn_Implementation(); CROWDY_EVENT(AnnounceDawn) // Any client can ask; it runs on the Leader, whose write ships. UFUNCTION(meta = (CrowdyEvent, CrowdyRecipient = "OwningClient")) void RequestNextPhase_Implementation(); CROWDY_EVENT(RequestNextPhase) UFUNCTION(BlueprintCallable, Category = "Lantern") void AdvanceNight(); }; // LanternNight.cpp #include "LanternNight.h" #include "EngineUtils.h" #include "Lantern.h" void ULanternNightSubsystem::OnRep_NightPhase() { for (TActorIterator It(GetWorld()); It; ++It) { It->Light->SetIntensity(NightPhase * 1000.f); } } void ULanternNightSubsystem::AnnounceDawn_Implementation() { NightPhase = 0; OnRep_NightPhase(); } void ULanternNightSubsystem::RequestNextPhase_Implementation() { AdvanceNight(); } void ULanternNightSubsystem::AdvanceNight() { ++NightPhase; OnRep_NightPhase(); } ``` The game-instance twin is `ULanternCalendarSubsystem` on the other base: a `DayCount` declared the same way, which survives travel between village levels and needs no override of `Initialize` at all. The block is the declaration only; a notify and a caller are yours to add: ```cpp // LanternNight.h // A game instance subsystem outlives worlds, so a day count survives travel between village levels. UCLASS() class ULanternCalendarSubsystem : public UCrowdyReplicatedGameInstanceSubsystem { GENERATED_BODY() public: UPROPERTY(meta = (CrowdyState, CrowdyHeartbeat)) int32 DayCount = 0; }; ``` A replicated subsystem is defined in C++; a Blueprint may not subclass one. Once the class exists, its Blueprint surface appears by itself: a **Get Lantern Night Subsystem** getter node (the editor offers one for every `BlueprintType` world or game-instance subsystem), and off it every `BlueprintCallable` and `BlueprintPure` the class declares, `Advance Night` here. A `CrowdyState` property with `BlueprintReadWrite` is readable the same way. There is no pasted graph on this page because a graph would name your class, not one the site can ship; the shape is Event BeginPlay, the getter, the call, behind a [**Switch Is Crowdy Entity Locally Owned**](./leader.md#checking-who-writes-an-entity) with the subsystem in `Entity`, since only the Leader's write to a replicated subsystem ships. :::warning[If you override Initialize or Deinitialize, call Super. Enrollment lives inside the base's override.] There is no separate hook and no runtime check. A subclass that overrides `Initialize` without calling `Super::Initialize` is never enrolled, and nothing it replicates ever leaves the machine. ::: :::danger[A world subsystem must null-check GetGameInstance() in Initialize.] Any further work you add to `Initialize` after `Super::Initialize` runs on a transient game world the engine creates at startup, whose game instance is set only after the world exists. `GetGameInstance()` returns null there, and reaching through it crashes with an access violation on launch that Play in Editor never reproduces. The SDK's own world subsystems guard for it; so must yours. ::: **Success signal.** On the Leader, call `AdvanceNight` and every client's `OnRep_NightPhase` runs at the next tick; `crowdy.state.trace 1` logs the delta. `AnnounceDawn` shows up in `crowdy.rpc.trace 1` as a reliable send over the session channel. ## What a subsystem cannot do Two consequences of having no actor. :::warning[Every CrowdyEvent on a subsystem needs an explicit CrowdyRecipient: Multicast or Owning Client.] The default recipient, `SpatialMulticast`, needs a world position to send from. A subsystem has none, so the send is rejected with `uses SpatialMulticast, which has no location; set CrowdyRecipient=Multicast or OwningClient. Dropping.` `OwningClient` runs on the Leader, delivered over the channel and gated on receipt, so it is how a client asks the Leader to do something. There is no Host recipient; a saved one reads as `OwningClient`. ::: - A `CrowdyOwnerOnly` property never transmits on a subsystem: the targeted path addresses an actor's owner, and a subsystem has none. The replicator logs `is non-spatial; owner-only propert(ies) not emitted` once and moves on. - There is no spawn event and no `InitialState`. A subsystem's first values on a late joiner come from its class defaults and then the keyframe, which is why `CrowdyHeartbeat` belongs on every property a newcomer must see. ## The library, for cases the bases do not cover `UCrowdyReplicatedSubsystemLibrary` is what the bases call. **Register Crowdy Replicated Subsystem** (`RegisterCrowdyReplicatedSubsystem(Subsystem)`, `Subsystem` defaults to self) resolves the entity subsystem from the caller's world and enrolls it, returning the participant's NetID or an invalid `FGuid` on failure; **Unregister Replicated Subsystem** reverses it. The world-free C++ core is `RegisterReplicatedSubsystemInto(Registry, Subsystem)`, which takes no ownership argument. In a world with no entity subsystem, which is any editor world, unregister is silent and register logs a warning and enrolls nothing. :::caution[Do not call Register Crowdy Replicated Subsystem from a game-instance subsystem.] Its world is the ambiguous "current" world. Inherit `UCrowdyReplicatedGameInstanceSubsystem`, which enrolls per world, instead. ::: Underneath both is the two-call pattern on `UCrowdyEntitySubsystem`, `RegisterParticipant(Participant)` and `UnregisterParticipant(Participant)`, which any `UObject` may use. A participant registered this way is written by the Leader, and a destroy event naming its id is ignored: its id is public, and only an actor can be destroyed. If you write it by hand in a world subsystem's `Initialize`, the order below is not optional. :::warning[Initialize both dependencies before enrolling: the entity subsystem, then the state replicator.] `Collection.InitializeDependency(UCrowdyEntitySubsystem::StaticClass())` and then `Collection.InitializeDependency(UCrowdyStateReplicator::StaticClass())`, before the register call. The replicator binds the registration event in its own `Initialize`; enroll first and the broadcast fires before anyone is listening, the subsystem is never tracked, and no later rescan recovers it. Depending on the entity subsystem alone does not pull the replicator in. ::: ## Gotchas - Both bases are `Abstract`. Your concrete subclass is what the engine instantiates. - A subsystem's NetID is the hash of its class path. Rename the class and every client agrees on the new id at the same time, because they all run one build. - The world base is created only in PIE and game worlds. In an editor world it does not exist, and that is correct. - The game-instance base ignores worlds owned by another game instance, so two PIE clients in one process each enroll their own. - A subsystem's traffic shares the session channel with the two ownership-transfer events. Its reliable sends have the same 1024-byte payload cap as any [Multicast call](./rpc-events-cpp.md#containers-and-their-bounds). ## Related - [Crowdy State](./crowdy-state.md): the properties a subsystem replicates. - [RPC events in C++](./rpc-events-cpp.md): the events it declares. - [Recipients and routing](./recipients-and-routing.md): why the default recipient is rejected here. - [Channels](./channels.md): the transport a subsystem's deltas and events ride. - [The Leader](./leader.md): who writes a subsystem, and how to follow it. # Channels Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/channels # Channels A channel is a named message group within one app: create it, join it, publish to it, and every member receives the message wherever they stand. It is also the transport a `Multicast` CrowdyEvent and a [replicated subsystem](./replicated-subsystems.md)'s state deltas ride, and every client joins one channel, the session channel, whether or not it ever creates another. `UCrowdyChannels` is a game-instance subsystem. Every server call on it is asynchronous and answers through exactly one of two delegates, success or `FOnChannelError`, including when the request never reaches the server. Publishing is not one of those calls: it goes out over UDP and is not acknowledged. ## When to use one Guild chat, a party's coordination, a village-wide announcement, trade broadcasts: anything that must reach a group regardless of distance. For a moment that only nearby players need, a `SpatialMulticast` event is cheaper; for a value, [Crowdy State](./crowdy-state.md), or your server code if it is [truth](../concepts/two-planes.md). ## The session channel Every app has one channel every client joins on connect, named `__crowdy_session_`, created on demand when it does not exist and the app's creation policy lets a member create one (otherwise create it once in Crowdy Studio, or the log warns that default-channel events will drop). It is an SDK-owned transport, not a place for your own messages. It carries every `Multicast` CrowdyEvent with no `CrowdyChannel` of its own and every replicated subsystem's Crowdy State delta. :::warning[A message you publish on the session channel, or on any channel a Multicast event names, never reaches OnChannelMessageReceived.] Every channel the connect-time bootstrap joins (the session channel and each channel a Multicast event names) and every channel you hand to `RegisterReliableRpcChannel` is an RPC transport: a payload arriving on it goes to the RPC decoder and is never broadcast to the game. Publish your own notices on a channel of your own, one channel per purpose. ::: `GetSessionChannelId()` is its resolved id, 0 until joined or created, and `AreReliableChannelsReady()` turns true once the connect-time bootstrap has joined every channel the app's Multicast events name plus the session channel. Both are pure nodes you can poll. :::warning[A channel a Multicast event names must already exist. Only the session channel is created for you.] The bootstrap joins named channels; it never invents one, because a missing name is usually a typo. It logs `[CrowdyChannels] Multicast channel 'X' was not found for this app - RPCs targeting it will drop. Create it (or fix the name) in Crowdy Studio.` A channel you create at runtime after the bootstrap has run needs `RegisterReliableRpcChannel(ChannelId, Name)` once you have joined it, or events naming it still drop. Registering it makes it an RPC transport: raw `PublishChannelMessage` payloads on it are decoded as RPC frames and are not delivered to `OnChannelMessageReceived`, so keep one channel per purpose. ::: ## Create and join `CreateChannel(Name, Description, MembershipPolicy, bMembersCanSend, bMembersCanSpeak, OnSuccess, OnError)` creates one; the creator becomes its owner with the system `leader` role, which holds every permission including `send_messages`. `ECrowdyChannelMembershipPolicy` decides how others get in: `Open` (join at once), `Request` (a join request awaits approval), `Invite` (managers add members), `Admin` (app admins only). `bMembersCanSend` true creates a default `member` role granting `send_messages` to everyone who joins; false makes an announce-only channel where joiners receive but cannot post until given a role. `bMembersCanSpeak`, which follows it (**Members Can Speak** on the Blueprint node, off by default), does the same for `send_voice`; see [Let members speak](#let-members-speak). The app's `FCrowdyChannelPolicy` (read with `GetChannelPolicy`) holds who may create channels at all (`ECrowdyChannelCreationPolicy`: `Admin`, `Member`, `Anyone`), the default membership policy, and the caps `MaxMembers` and `MaxChannelsPerUser` (0 means none); `SetChannelPolicy` sets the two policies, and the caps are set in Crowdy Studio. The lantern village creates a `village` channel for lit notices once the connection is up: `CreateVillageChannel`, called from the game instance's connected handler (the create needs the game token), and `HandleVillageChannelCreated` stores the id behind `GetVillageChannelId`, the one place the id lives. ```cpp // LanternGameInstance.h #include "Queries/Data/Channels/Types/FCrowdyChannel.h" UFUNCTION(BlueprintPure, Category = "Lantern") int64 GetVillageChannelId() const { return VillageChannelId; } private: int64 VillageChannelId = 0; void CreateVillageChannel(); UFUNCTION() void HandleVillageChannelCreated(FCrowdyChannel Channel); // LanternGameInstance.cpp #include "Subsystem/CrowdyChannels.h" void ULanternGameInstance::CreateVillageChannel() { // Called once connected (the create needs the game token); one client creates, the rest join. UCrowdyChannels* Channels = GetSubsystem(); FOnChannelSuccess Created; Created.BindDynamic(this, &ULanternGameInstance::HandleVillageChannelCreated); Channels->CreateChannel(TEXT("village"), TEXT("Lantern lit notices"), ECrowdyChannelMembershipPolicy::Open, true, false, Created, FOnChannelError()); } void ULanternGameInstance::HandleVillageChannelCreated(FCrowdyChannel Channel) { VillageChannelId = Channel.ChannelId; } ``` In the Game Mode Blueprint, at **Event BeginPlay** a **Crowdy SDK Subsystem** getter feeds **Bind Event to On UDP Connection Success**, whose custom event `OnConnected` calls **Create Channel**, a latent node with `Name`, `Description`, `Membership Policy`, `Members Can Send`, and `Members Can Speak` inputs and **On Success** (a `Channel` struct) and **On Error** pins. Binding to the connection is what keeps the create after sign-in; at BeginPlay there may be no token yet and the create would answer on **On Error**. The Game Mode belongs to one map, so keep the id in a variable on the Game Instance if the next map needs it. (Do not start from the Game Instance's **Event Init**: it runs before the SDK's subsystems exist, see [Authentication](../services/authentication.md#signing-in).) To keep the id, drag a **Break Crowdy Channel** off the `Channel` pin on the success branch and set an Integer64 variable `VillageChannelId` from `Channel Id`. [Blueprint snippet: ch-create, see /bp/unreal-sdk/ch-create.txt] Every connecting client running this asks the server to create the channel. A real game has one client create it, the Leader for instance, or calls `GetChannels` first and creates only on a miss; the server's creation policy is the real gate on who may. `JoinChannel(ChannelId, ...)` joins an open channel and `RequestToJoinChannel` files a request on a `Request` channel; `LeaveChannel` leaves. The creator is already a member and needs neither, though the local cache (`HasCachedChannels`, `IsPlayerInChannel`) does not show the new channel until `GetMyChannels` has run. ## Let members speak A channel can carry voice as well as messages; see [Talk to a channel](../services/voice-chat.md#talk-to-a-channel). Sending voice needs the `send_voice` permission (`ECrowdyChannelPermission::SendVoice`, the **Send Voice** flag of `FCrowdyChannelPermissions`) on one of the sender's roles, and the player needs voice chat allowed. The `leader` role holds it, so the player who creates a channel can always talk on it. **Members Can Speak** on **Create Channel** gives the default `member` role `send_voice`; it is off by default, so on a channel made without it the server drops a member's voice until a role with the permission is granted; such members join the channel's voice in **Listen** mode. The SDK logs that refusal as a warning naming Send Voice. Receiving voice needs only membership. A change to the signature: in C++, `CreateChannel` takes `bMembersCanSpeak` right after `bMembersCanSend`, so existing calls need the new argument. The Blueprint node gains the pin, off. ## Ban a member A manager removes a member for good with `BanChannelMember(ChannelId, UserId, Reason, OnSuccess, OnError)`. It takes the user out of the channel and refuses every later join, request to join and add of that user until a manager lifts the ban with `UnbanChannelMember(ChannelId, UserId, OnSuccess, OnError)`. The caller needs the manage-members permission, and the channel's owner and the caller themselves cannot be banned. A user who is not a member yet can be banned too, and leaving or being removed does not lift a ban. `Reason` is optional and at most 500 characters. A longer one fails at once with a `PolicyViolation` error, and nothing is sent. Ban answers the member record, whose `Status` is `banned`; unban answers `bWasBanned`, which is false when the user had no ban. The village's elder bans a member from the `village` channel. `VillageChannelId` is the id the game instance kept when it created the channel. A Ban button on the member list calls `BanFromVillageChannel` with the member picked. `HandleChannelBanned` receives the member record, and `HandleChannelBanFailed` the error. ```cpp // LanternGameInstance.h #include "Queries/Data/Channels/Types/FCrowdyChannelMember.h" #include "Queries/Data/Channels/Types/FCrowdyChannelError.h" public: // A Ban button on the member list calls this for the member picked. void BanFromVillageChannel(int64 UserId, const FString& Reason); UFUNCTION() void HandleChannelBanned(FCrowdyChannelMember Member); UFUNCTION() void HandleChannelBanFailed(FCrowdyChannelError Error, FString Message); // LanternGameInstance.cpp #include "Subsystem/CrowdyChannels.h" void ULanternGameInstance::BanFromVillageChannel(int64 UserId, const FString& Reason) { UCrowdyChannels* Channels = GetSubsystem(); FOnChannelMemberSuccess Banned; Banned.BindDynamic(this, &ULanternGameInstance::HandleChannelBanned); FOnChannelError Failed; Failed.BindDynamic(this, &ULanternGameInstance::HandleChannelBanFailed); // Needs the manage-members permission; the owner and yourself cannot be banned. A Reason over 500 characters fails before it is sent. Channels->BanChannelMember(VillageChannelId, UserId, Reason, Banned, Failed); } void ULanternGameInstance::HandleChannelBanned(FCrowdyChannelMember Member) { UE_LOG(LogTemp, Log, TEXT("User %lld is banned from the village channel"), Member.UserId); } void ULanternGameInstance::HandleChannelBanFailed(FCrowdyChannelError Error, FString Message) { UE_LOG(LogTemp, Warning, TEXT("The ban failed: %s"), *Message); } ``` **Ban Channel Member** is a latent node with `Channel Id`, `User Id` and `Reason` inputs. The figure bans the user that the `OnBanPressed` event passes in, for a fixed reason. **On Success** carries the member record; **On Error** carries `Error` and `Message`, and the figure opens `Error` with **Break Crowdy Channel Error** to print its `Code` and the `Message`. [Blueprint snippet: ch-ban-node, see /bp/unreal-sdk/ch-ban-node.txt] ## Handle a ban on join A banned user's `JoinChannel`, `RequestToJoinChannel`, or a manager's `AddChannelMember` for them, fails with the error code `Banned` in `ECrowdyChannelErrorCode`. The code comes from the server's own error code, not from the message text, so it is safe to branch on. A ban lasts until a manager lifts it, so do not retry: tell the player instead. A Join the Village button calls `JoinVillageChannel`. Its failure handler checks the code first. ```cpp // LanternGameInstance.h #include "Queries/Data/Channels/Types/FCrowdyChannelError.h" public: // A Join the Village button calls this. void JoinVillageChannel(); UFUNCTION() void HandleVillageJoinFailed(FCrowdyChannelError Error, FString Message); // LanternGameInstance.cpp #include "Subsystem/CrowdyChannels.h" void ULanternGameInstance::JoinVillageChannel() { FOnChannelError Failed; Failed.BindDynamic(this, &ULanternGameInstance::HandleVillageJoinFailed); GetSubsystem()->JoinChannel(VillageChannelId, FOnChannelMemberSuccess(), Failed); } void ULanternGameInstance::HandleVillageJoinFailed(FCrowdyChannelError Error, FString Message) { // A ban stays until a manager lifts it, so trying again is pointless; tell the player instead. if (Error.Code == ECrowdyChannelErrorCode::Banned) { UE_LOG(LogTemp, Warning, TEXT("You are banned from the village channel: %s"), *Message); return; } UE_LOG(LogTemp, Warning, TEXT("Could not join the village channel: %s"), *Message); } ``` On the **Join Channel** node's **On Error** pin, open `Error` with **Break Crowdy Channel Error** and compare `Code` with **Banned** in a **Branch**; the figure prints the `Message` on the banned branch. [Blueprint snippet: ch-banned-join, see /bp/unreal-sdk/ch-banned-join.txt] ## Handle a full channel A join, a request to join, an add or a create fails with the error code `LimitReached` (**Limit Reached** on the Blueprint enum) when the channel is full, or when the player is already in as many channels as the app allows. Teams report the same code for their caps. Retrying does not help until someone leaves, so tell the player instead. Branch on it the way [Handle a ban on join](#handle-a-ban-on-join) does for `Banned`. Both caps are set in Crowdy Studio, and the Application API names the code `GROUP_LIMIT_REACHED`. ## Publish and receive `PublishChannelMessage(ChannelId, Payload)` sends raw bytes to every active member except the sender. The caller must already be a member holding `send_messages`; an open channel's default member role grants it. The server caps a channel message payload at 1024 bytes. `PublishChannelMessageAs(ChannelId, SenderUuid, Payload)` sends under a sender id you choose, as the Game Kit's chat does, since the session's own id is empty until the player's entity resolves; a receiver sees that id, which proves nothing. `CanPublishChannelMessage()` is true once the game session exists and the realtime connection is routing. :::warning[Publishing is unacknowledged UDP: no ordering, no delivery guarantee, and the caller is never told if it was dropped.] It is the right tool for a notice, not for a value. Put anything that must be right on every client in a state property, or in your server code if it is truth. ::: The lantern's `PublishLit`, called from the owner-gated overlap, publishes a one-byte notice, its lit flag, on the village channel, reading the id from the game instance's `GetVillageChannelId`: ```cpp // Lantern.cpp #include "LanternGameInstance.h" #include "Subsystem/CrowdyChannels.h" void ALantern::PublishLit() { // Tell every village member the lantern changed, over the channel the game instance created. const ULanternGameInstance* Game = GetGameInstance(); UCrowdyChannels* Channels = Game ? Game->GetSubsystem() : nullptr; if (Channels) { Channels->PublishChannelMessage(Game->GetVillageChannelId(), { uint8(bLit) }); } } ``` From **Event ActorBeginOverlap**, behind an **Is Crowdy Entity Locally Owned** branch (the owner gate the C++ has): a **Crowdy Channels** subsystem getter feeds the `Target`, **Get VillageChannelId** (the Integer64 variable the create graph set) the `Channel Id`, and a one-element **Make Array** the `Payload` byte array of **Publish Channel Message**. The array's one element is the lit byte, 0 in the figure; wire your lit flag into it. It is a plain call with no result pins. [Blueprint snippet: ch-publish, see /bp/unreal-sdk/ch-publish.txt] `OnChannelMessageReceived` fires on the game thread for every delivery, with the channel id, the sender's `SenderUUID`, and the payload. The village's `HandleVillageNotice`, bound by `WatchVillageChannel` from `Init`, reads the one byte and sets every lantern's visibility from it; the check on the payload's length before the read is the validation the caution below asks for. ```cpp // LanternGameInstance.h void WatchVillageChannel(); UFUNCTION() void HandleVillageNotice(int64 ChannelId, FString SenderUUID, const TArray& Payload); // LanternGameInstance.cpp #include "EngineUtils.h" #include "Lantern.h" #include "Subsystem/CrowdyChannels.h" void ULanternGameInstance::WatchVillageChannel() { GetSubsystem()->OnChannelMessageReceived.AddDynamic(this, &ULanternGameInstance::HandleVillageNotice); } void ULanternGameInstance::HandleVillageNotice(int64 ChannelId, FString SenderUUID, const TArray& Payload) { // A channel message is not server-signed; validate it before acting. Here the one byte is the lit flag. const bool bLit = Payload.Num() > 0 && Payload[0] != 0; for (TActorIterator It(GetWorld()); It; ++It) { It->Light->SetVisibility(bLit); } } ``` There is no Blueprint figure for the receive side: `OnChannelMessageReceived` carries a byte-array `Payload`, and the generated graphs on this site cannot express a bound event with an array parameter. In your own Blueprint, drag off a **Crowdy Channels** subsystem getter, choose **Bind Event to On Channel Message Received**, and create the matching custom event from the `Event` pin; it receives `Channel Id`, `Sender UUID`, and `Payload` as an array of bytes. :::caution[A channel message is not signed on the way down. Validate the payload before acting on it.] The server does not sign the delivery, and any member with `send_messages` could have sent it. Treat the bytes as untrusted input: bound every length, clamp every value, and never let one decide an outcome that must hold against a modified client. The SDK does not filter payloads on a channel: every payload you are sent reaches your handler, whatever text it begins with. ::: ## The full surface Cache and queries, on `UCrowdyChannels`: `HasCachedChannels` (has `GetMyChannels` ever completed), `GetCachedMyChannels` (the memberships, no round trip), `IsPlayerInChannel`, `GetMyChannelById`, `IsInAnyChannel`, `HasPermissionInChannel` (an `ECrowdyChannelPermission`: `SendMessages`, `ManageChannel`, `ManageMembers`, `ManageRoles`, `InviteMembers`, `SendVoice`), `GetMyChannels`, `GetChannel`, `GetChannels`, `GetChannelMembers`, `GetChannelRoles`, `GetChannelPolicy`, `GetPendingJoinRequests`. `OnMyChannelsCacheChanged` fires when the cached membership list changes. Mutations: `CreateChannel`, `UpdateChannel`, `DeleteChannel`, `JoinChannel`, `RequestToJoinChannel`, `LeaveChannel`, `AddChannelMember`, `RemoveChannelMember`, `BanChannelMember`, `UnbanChannelMember`, `CreateChannelRole`, `UpdateChannelRole`, `DeleteChannelRole`, `SetChannelMemberRoles`, `SetChannelPolicy`. Every query and mutation also exists as a latent Blueprint node with **On Success** and **On Error** pins, one class each: `UCrowdyChannels_GetMyChannels` (**Get My Channels**), `UCrowdyChannels_GetChannel`, `UCrowdyChannels_GetChannels` (**Get All Channels**), `UCrowdyChannels_GetChannelMembers`, `UCrowdyChannels_GetChannelRoles`, `UCrowdyChannels_GetChannelPolicy`, `UCrowdyChannels_GetPendingJoinRequests`, `UCrowdyChannels_CreateChannel`, `UCrowdyChannels_UpdateChannel`, `UCrowdyChannels_DeleteChannel`, `UCrowdyChannels_JoinChannel`, `UCrowdyChannels_RequestToJoinChannel` (**Request to Join Channel**), `UCrowdyChannels_LeaveChannel`, `UCrowdyChannels_AddChannelMember`, `UCrowdyChannels_RemoveChannelMember`, `UCrowdyChannels_BanChannelMember` (**Ban Channel Member**), `UCrowdyChannels_UnbanChannelMember` (**Unban Channel Member**), `UCrowdyChannels_SetChannelMemberRoles`, `UCrowdyChannels_CreateChannelRole`, `UCrowdyChannels_UpdateChannelRole`, `UCrowdyChannels_DeleteChannelRole`, `UCrowdyChannels_SetChannelPolicy`. A list result arrives wrapped (`FCrowdyChannelsResult`, `FCrowdyMyChannelsResult`, `FCrowdyChannelMembersResult`, `FCrowdyChannelRolesResult`) so a **Break** node unwraps it. `PublishChannelMessage` has no latent twin; it is a plain call on the subsystem. **On Success** and **On Error** of a node share one set of data pins: the result (`Channel`, `Member`, `Channels`, and so on; a node that returns nothing has none), then `Error` and `Message`. On **On Success**, `Error` and `Message` are empty. On **On Error** the result is empty, `Error` is an `FCrowdyChannelError` (break it to read its `Code`) and `Message` is the text to show. The types: | Type | Holds | |---|---| | `FCrowdyChannel` | `ChannelId`, `AppId`, `Name`, `Description`, `OwnerUserId`, `MembershipPolicy`, `Status`, `CreatedAt`. | | `FCrowdyChannelMember` | `ChannelMemberId`, `ChannelId`, `UserId`, `Status` (`active`; `pending` while a request waits; `banned` in the answer to a ban), `Roles` sorted by rank, `CreatedAt`. | | `FCrowdyChannelMembership` | Your own membership of one channel: `Channel`, `Roles`, the effective `Permissions` across them, `JoinedAt`. | | `FCrowdyChannelRole` | `ChannelRoleId`, `ChannelId`, `RoleName`, `Rank`, `bIsSystem`, `Permissions`, `CreatedAt`. Every channel has a non-deletable `leader` role. | | `FCrowdyChannelPermissions` | The six flags: `bSendMessages`, `bManageChannel`, `bManageMembers`, `bManageRoles`, `bInviteMembers`, `bSendVoice`. | | `FCrowdyChannelPolicy` | `AppId`, `CreationPolicy`, `DefaultMembershipPolicy`, `MaxMembers`, `MaxChannelsPerUser`. | | `FCrowdyChannelError` | An `ECrowdyChannelErrorCode` (`Unknown`, `NotFound`, `Forbidden`, `PolicyViolation`, `AlreadyMember`, `NotMember`, `NetworkError`, `ServerError`, `Banned`, `LimitReached`) and the `Message` to show. All but `Banned` and `LimitReached` are a best-effort classification of the message text; those two come from the server's own error code. | Every id is an `int64`; the server's ids are 64-bit. In C++ each call takes a pair of dynamic delegates: a success type shaped for its result (`FOnChannelSuccess` with an `FCrowdyChannel`, `FOnChannelsSuccess` with the array, `FOnChannelMemberSuccess`, `FOnChannelMembersSuccess`, `FOnChannelRoleSuccess`, `FOnChannelRolesSuccess`, `FOnMyChannelsSuccess` with the memberships, `FOnChannelPolicySuccess`, `FOnChannelVoidSuccess` for the calls that return nothing, `FOnChannelUnbanSuccess` with a `bWasBanned` for an unban) and `FOnChannelError`. The two events are `FOnMyChannelsCacheChanged` and `FOnChannelMessageReceived`. The latent nodes expose the same shapes as multicast pins that also carry `Error` and `Message`: `FChannelAsyncResult`, `FChannelsAsyncResult`, `FMyChannelsAsyncResult`, `FChannelMemberAsyncResult`, `FChannelMembersAsyncResult`, `FChannelRoleAsyncResult`, `FChannelRolesAsyncResult`, `FChannelPolicyAsyncResult`, `FChannelUnbanAsyncResult`, and `FChannelAsyncOnError` for the nodes that return nothing. ## What rides a channel from the SDK itself A `Multicast` CrowdyEvent is encoded into a channel payload and published over the session channel, or the channel its `CrowdyChannel` names once this client has joined it. A replicated subsystem's Crowdy State delta travels the same way. Both are capped at 1024 bytes by the SDK's own codec and dropped loudly, never truncated, when they would exceed it; a Multicast event whose parameters can never fit is refused at registration. "Reliable" on this path means every member is a recipient, not that delivery is guaranteed; see [Recipients and routing](./recipients-and-routing.md#multicast-what-reliable-means). `crowdy.rpc.reliable.trace 1` logs the reliable sends and receives on the channel transport. ## Gotchas - The session channel is always joined, even in a project with no Multicast event. - A named channel is join-only from the SDK's side. Create it in Crowdy Studio or at runtime, then `RegisterReliableRpcChannel` if you created it after connecting. - `send_messages` gates publishing, not membership. An announce-only channel is a channel whose joiners lack it. - The sender never receives an echo of its own message. - Channel management is an Application API call and needs the app-scoped token the sign-in gives you; see [Authentication](../services/authentication.md). The wire protocol and the GraphQL calls are on the [Application API channels page](/application-api/channels). ## Related - [Recipients and routing](./recipients-and-routing.md): the Multicast recipient. - [RPC events in C++](./rpc-events-cpp.md): the `CrowdyChannel` key and the payload cap. - [Replicated subsystems](./replicated-subsystems.md): deltas over the session channel. - [Connection and reconnect](./connection-and-reconnect.md): when the channel bootstrap runs. - [Teams and channels in Studio](../studio/teams-and-channels.md): authoring channels without code. - [Play together](../services/play-together.md): chat rooms and party chat as text, with Send Chat and On Chat Message. # Map Profiles Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/map-profile # Map Profiles A map profile is a `UCrowdyMapProfile` data asset: one asset configures one map end to end. A map you configure nothing for runs on the profile the plugin ships; a profile of your own is how you change a map's settings, or switch the SDK off there. A configured row whose asset fails to load resolves to no profile, and that map has no networking however correct the code is. ## When you need one When a map needs settings the shipped default does not have: a Backend Config of your own, a different send cadence, a tighter relevance distance. The [Quickstart](../quickstart.md) authors none and runs on the shipped default. A map that should run without the SDK gets a profile with **Handle Events and Spawns**, **Draw Remote Entities**, **Send Movement** and **Replicate Crowdy State** unticked; that records the intent, and it is the only way to switch the SDK off on one map. ## Create the asset In the Content Browser, **Add**, **Miscellaneous**, **Data Asset**, pick **Crowdy Map Profile**. The Details panel groups the settings by what they decide: **Events**, **Remote Entities**, **Movement**, **Crowdy State**, **Voice** and **Emotes**. Tuning settings that most maps never change sit under the **Remote Entities** group's **Advanced** row. ![The shipped default map profile asset in the Details panel](/img/unreal-sdk/map-profile-asset.png) The screenshot is the SDK's own shipped default profile. **Backend Config** is empty on it, which is fine: the actor pool runs on a built-in config when none is set. | Field (shown as) | Default | What it controls | |---|---|---| | `bEnableNetworking` (**Handle Events and Spawns**) | on | Spawn and destroy events, Crowdy Events and Crowdy State arriving over the realtime connection. Off does not stop movement, drawing or sending: those have their own switches below. | | `ActorManagement` (the **Remote Entities** group) | see [Entities and spawning](./entities-and-spawning.md#the-actor-tracker) | **Draw Remote Entities**, the **Backend Class** and **Backend Config** that draw them, the **Interpolation Delay**, and the tracker's tuning under **Advanced**. Pick **Crowdy Mass Rendering Backend** as the **Backend Class** to draw a crowd; see [Turn Mass on for a map](../mass/turn-mass-on-for-a-map.md). | | `bUseAutoReplicator` (**Send Movement**) | on | The continuous channel: each entity's movement, or its executor's state. See [Continuous state](./continuous-state.md). | | `MovementDistance` (**Movement Distance**, Movement) | Eight Chunks | How far each entity's movement and its spawn event travel, in chunks around it (`ECrowdyReplicationDistance`): other players see it only within this range. At the default chunk size of 1600 units, eight chunks is 128 m in each direction. Keep it at least as large as **Voice Distance** and **Relevance Distance**, or players hear someone they cannot see, and a Crowdy State change arrives for a player who has no copy. | | `MovementDecay` (**Movement Decay**, Movement) | No Decay | Thins movement updates with distance, so far players get fewer of them. It uses the decay rates events use: **No Decay**; **Exponential Decay**, where each ring of chunks gets half the updates of the ring before; **Linear 50 Decay**, **Linear 25 Decay**, **Linear 10 Decay** and **Linear 5 Decay**, where the farthest ring gets that percentage, in one block of a 20-update cycle. The spawn announce is never thinned. Read [Thinning movement with distance](#thinning-movement-with-distance) before turning it on. | | `SnapDistance` (**Snap Distance**, Movement) | 1000 cm (10 m), minimum 0 | Other players' copies jump straight to an update that lands farther than this from the one before it, as a teleport does, instead of gliding there. Keep it above the farthest anything on the map moves between two updates a player receives (its top speed divided by **Send Rate**, and farther where **Movement Decay** thins far updates); something faster snaps on every update. 0 never snaps. See [Teleporting a player](./continuous-state.md#teleporting-a-player). | | `ReplicationIntervalHz` (**Send Rate**) | 10 Hz (1 to 10) | How many times a second movement and Crowdy State are sent. Editable while either is on. | | `bSendActorStateOnlyOnChange` (**Send Only On Change**) | on | An unchanged entity sends the keyframes and heartbeats below instead of restating its state every interval. | | `ActorKeyframeIntervalSeconds` (**Keyframe Interval**, Movement) | 3 s | Full re-send of an unchanged entity's state. It is the only thing other players receive from an entity standing still, so it is what keeps it on their screens and lets a late observer catch up. 0 turns keyframes off. | | `ActorHeartbeatIntervalSeconds` (**Heartbeat Interval**) | 1 s | A cheap "still here" for an unchanged entity: the spatial header and no state. It keeps the entity's presence on the server, which goes stale after about 5 s; other players never receive it. 0 turns heartbeats off. | | `bUseStateReplicator` (**Replicate Crowdy State**) | on | Crowdy State property replication. See [Crowdy State](./crowdy-state.md). | | `StateRelevanceDistance` (**Relevance Distance**) | Eight Chunks | How far a Crowdy State change travels, as a chunk count (`ECrowdyReplicationDistance`). | | `StateKeyframeIntervalSeconds` (**Keyframe Interval**, Crowdy State) | 2 s | Full re-send of every property marked `CrowdyHeartbeat`. 0 turns the keyframe off map-wide; changes still send. | | `VoiceDistance` (**Voice Distance**, Voice) | One Chunk | How far a player's voice reaches on this map, in chunks, unless the game calls **Set Voice Chat Distance**. See [How far your voice reaches](../services/voice-chat.md#how-far-your-voice-reaches). | | `EmoteDistance` (**Emote Distance**, Emotes) | Two Chunks | How far an emote travels from the player who sends it. | ## Thinning movement with distance **Movement Decay** trades update rate for reach. A copy that is not updated is removed after the **Actor Timeout** (12 s on the **Remote Entities** group's **Advanced** row), and an entity that stands still sends only keyframes, one every **Keyframe Interval** (3 s by default). A steep decay at long range can therefore starve a far copy until it times out. With **Exponential Decay** at the default eight chunks, the outermost ring gets 1 update in 128. A player in it sees a player standing still update once every 384 s, so the copy is gone long before the next one. The **Linear** decays do not spread updates out evenly: the server delivers each ring in one block of a 20-update cycle and skips it for the rest. The farthest ring under **Linear 50 Decay** gets 10 updates in a row and then misses 10, so with a 3 s **Keyframe Interval** a player standing still there goes 33 s between updates. At the defaults, every Linear decay times far copies out, at any distance beyond the sender's own chunk: the outermost ring gets the same share however far it is. Only a longer **Actor Timeout** helps, or a **Keyframe Interval** under the timeout divided by 11, 16, 19 or 20 for **Linear 50**, **25**, **10** or **5 Decay** (about 1.09, 0.75, 0.63 or 0.6 s at the default 12 s). The SDK logs a warning when a map starts if the expected gap at the edge reaches the **Actor Timeout**. Fix it with a gentler decay, a shorter **Keyframe Interval**, a longer **Actor Timeout**, or, for **Exponential Decay**, a shorter **Movement Distance**. ## Checks when you save Saving a profile, or running **Validate Assets** on it, reports two mistakes that otherwise only show up as a quiet bug in play: - **An idle entity goes silent.** With **Send Only On Change** on, an entity that stops moving sends only keyframes and heartbeats. Other players see it through its keyframes alone, so a **Keyframe Interval** of 0, or one at least the **Actor Timeout** (12 s), lets them drop it while it stands still. The server keeps relaying it only while a keyframe or a heartbeat arrives more often than every 5 s, so the shorter of the two must be under 5 s. - **The Backend Config does not match the Backend Class.** The actor pool refuses a config of another backend's class when the map starts, and the Mass backend ignores one. Pick the backend's own config class, or clear **Backend Config**. :::note[An empty Backend Config means the built-in default, not a disabled backend.] `ActorManagement.BackendClass` defaults to `UCrowdyActorPoolBackend`. With `ActorManagement.BackendConfig` left empty, the backend creates a transient **Actor Pool Backend Config** and applies remote movement with `UCrowdyTransformRepPolicy`, the shipped policy that reads the default executor's `FCrowdyActorState` (location and rotation) and interpolates across a ring of recent samples, extrapolating briefly when an update is late. Set a config of your own when your executor sends a state struct of its own, when you want pool sizes per class, or when you want a different pool policy. The actor pool refuses a config of another backend's class with a warning naming the field. The Crowdy Mass Rendering Backend takes its own Backend Config, and ignores a config of another class without a word. See [Rendering Backends](./rendering-backends.md) and [Turn Mass on for a map](../mass/turn-mass-on-for-a-map.md). ::: ## Assign the profile Open **Project Settings, Plugins, Crowdy SDK** and find the **Map Profiles** category of `UCrowdySDKDeveloperSettings`: ![The Map Profiles category in Project Settings: Default Profile and the Map Profiles map](/img/unreal-sdk/map-profiles-settings.png) - `MapProfiles` maps a level asset to a profile. The lookup is by the map's short name, with the Play in Editor prefix stripped, so a PIE session resolves the same entry as a packaged build. - `DefaultProfile` covers every map without an entry. The SDK resolves the profile for a world through `UCrowdySDKDeveloperSettings::ResolveProfileForWorld`, in this order: 1. A `MapProfiles` entry whose map matches the current one. 2. `DefaultProfile`, if set. 3. The profile a plugin ships. The Crowdy SDK plugin registers its own `DA_CrowdySDKDefaultProfile` at module startup through `RegisterShippedDefaultProfile`, so a project that sets nothing at all runs on that asset rather than going inactive. The log says so once per world. 4. Nothing: the SDK stays inactive on the map and logs a warning, once per world, naming the map and the fix. :::caution[An entry that names an asset that fails to load is a broken setting, not an absent one. Resolution stops there.] A `MapProfiles` row or a `DefaultProfile` that points at an asset the build cannot load returns no profile and does not fall through to the next step. The warning names the asset path; check that it still exists and is packaged. ::: Every SDK subsystem resolves through the same function, and both warnings are reported once per world rather than once per subsystem, so you will see one line, not a dozen. ## Check it from code A lantern that never lights for other players is nearly always a map whose profile did not resolve. The example, `CheckMapProfile`, called from the lantern's `BeginPlay`, asks the same question the SDK asks, once, so the answer is in the log before anything else is suspected. ```cpp // Lantern.cpp #include "Data/CrowdyMapProfile.h" #include "Utils/CrowdySDKDeveloperSettings.h" void ALantern::CheckMapProfile() { // A lantern that never lights for other players usually has no active profile; rule that out first. const UCrowdyMapProfile* Profile = UCrowdySDKDeveloperSettings::ResolveProfileForWorld(GetWorld()); if (!Profile || !Profile->bEnableNetworking) { UE_LOG(LogTemp, Warning, TEXT("ALantern: no active map profile; this lantern will not replicate.")); } } ``` `ResolveProfileForWorld` is a plain C++ static. There is no Blueprint node for it. There is no Blueprint node for profile resolution: assigning a profile is Project Settings and Data Asset editing only, which the two screenshots above cover. What a Blueprint can read is the connection, `Get UDP Connection State` on the Crowdy SDK Subsystem; a connected state with dead entities is the profile symptom. **Success signal.** With a resolved profile the entity subsystem logs registrations once `crowdy.entity.trace 1` is on. Without one, the log carries a single `resolved no map profile` warning for the map and no entity ever registers. ## The shipped default, in one paragraph The plugin registers a shipped profile under the provider name `CrowdySDK`, and only one registration is in effect at a time: a second plugin offering a different profile is refused and logged, so which one a map runs on never depends on module load order. `UnregisterShippedDefaultProfile` withdraws an offer at module shutdown; `GetShippedDefaultProfilePath` and `GetShippedDefaultProfileProvider` report what is currently offered; `ResolveShippedDefaultProfile` returns the asset, or null with a reason when an offer exists but its asset failed to load. None of these is something a game calls; they exist so a plugin can carry a profile. ## Gotchas - A `MapProfiles` row or `DefaultProfile` naming an asset that did not load means no networking on that map. Check this first when a map looks dead; the warning names the asset. - The shipped default profile has no `BackendConfig`, which means the built-in transform policy draws remote entities. On 2.14.0 and earlier nothing was drawn from the continuous channel in that state; see [What's Changed](../guides/whats-changed.md#2026-09-22-sdk-v2150). - A non-networked map wants a profile with its four switches off, not no profile. The warning text asks for exactly that. **Handle Events and Spawns** alone is not an off switch: movement still sends and draws. - `StateKeyframeIntervalSeconds` is a safety net, not the mechanism. Changed properties ship on change whatever the interval; 0 only stops the periodic baseline for `CrowdyHeartbeat` properties. - `ReplicationIntervalHz` is one clock for two channels: continuous state and Crowdy State share it but send independently. ## Related - [Rendering backends](./rendering-backends.md): `BackendClass`, `BackendConfig`, and the policy classes. - [Turn Mass on for a map](../mass/turn-mass-on-for-a-map.md): choose the Crowdy Mass Rendering Backend and give it a Backend Config. - [Continuous state](./continuous-state.md): what `bUseAutoReplicator` and the keyframe and heartbeat intervals drive. - [Crowdy State](./crowdy-state.md): what `bUseStateReplicator`, `StateRelevanceDistance`, and `StateKeyframeIntervalSeconds` drive. - [Config Sync](../studio/config-sync.md): the network half of the same settings class, written by Crowdy Studio. # Rendering Backends Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/rendering-backends # Rendering Backends A rendering backend turns the [continuous state](./continuous-state.md) a remote entity's owner sends into something on screen for everyone else. The SDK ships two: the actor pool, which is the default, and the Crowdy Mass Rendering Backend, which draws remote entities as crowd rows (see [Draw a crowd with Mass](../mass/draw-a-crowd-with-mass.md)). A project customises the actor pool through two policy classes, or replaces the backend by implementing four methods. ## When you touch this When an entity that replicates movement moves on its owner and not on anyone else, when you want your own state struct applied to a proxy, or when pooled actors of the entity's class are the wrong way to draw a crowd; see [Draw a crowd with Mass](../mass/draw-a-crowd-with-mass.md). An entity that sends no movement never comes through here: its proxy is the actor its spawn event made, driven by Crowdy State and events, and a client that joined after the spawn builds it from a repeat of that event. ## The default: the actor pool `FCrowdyActorManagementConfigStruct::BackendClass` on the map profile defaults to `UCrowdyActorPoolBackend`, so a profile that never chose a backend gets this one. It uses `UCrowdyActorPoolSubsystem` to keep a pool of pre-spawned actors per entity class, checks one out when a remote entity appears, registers it in the entity registry so entity-targeted events reach it like any actor, and hands every update to a `UCrowdyRepApplicationPolicy`: the shipped `UCrowdyTransformRepPolicy` unless you provide one. ![The Actor Management category of a map profile: Backend Class and Backend Config](/img/unreal-sdk/map-profile-backend-select.png) The screenshot is the SDK's shipped default profile, and its **Backend Config** reads None: the backend runs on a built-in config in that case. :::note[No Backend Config means the built-in one: the actor pool with the transform policy.] When `BackendConfig` is empty, `UCrowdyActorPoolBackend::InitializeBackend` creates a transient **Actor Pool Backend Config** and, since it names no policy, instantiates `UCrowdyTransformRepPolicy`: it reads the default executor's `FCrowdyActorState` and sets the pooled actor's location and rotation, interpolated across a ring of recent samples with bounded extrapolation. A `BackendConfig` of another backend's class is refused: the backend logs `Backend Config is a , but this backend needs a CrowdyActorPoolBackendConfig` and returns false, the actor manager logs `could not initialize, so no remote entity will be drawn on this map`, and remote entities arriving as continuous-state updates are tracked with nothing on screen. Spawn-event proxies and Crowdy State are unaffected either way. See [Map profiles](./map-profile.md). The fallback arrived in 2.15.0. On 2.14.0 and earlier an empty Backend Config, or one with no Replication Policy Class, tracks remote entities and draws nothing, and the fix there is an **Actor Pool Backend Config** naming `UCrowdyTransformRepPolicy`. See [What's Changed](../guides/whats-changed.md#2026-09-22-sdk-v2150). ::: ### Configure it `UCrowdyActorPoolBackendConfig`, set as the profile's `BackendConfig`: | Field | Default | Effect | |---|---|---| | `ReplicationPolicyClass` | none | Your `UCrowdyRepApplicationPolicy` subclass. Unset means `UCrowdyTransformRepPolicy`, which moves the proxy from `FCrowdyActorState`; set it when your executor sends more than the transform, and move the proxy yourself in it. | | `PoolPolicyClass` | none, optional | A `UCrowdyActorPoolPolicy` subclass. Unset means the concrete base, which already hides pooled actors, shows them on activation, and strips proxy movement. | | `DefaultPoolSizePerClass` | 8 | Pools are created lazily per entity class with this many actors made up front. | | `PerClassPoolOverrides` | empty | A per-class up-front size; a class listed here is also pre-warmed at map load. | | `MaxPoolSizePerClass` | 256 | How far a class's pool may grow. When every actor is in use, the pool spawns one more, up to this cap (never below the up-front size). | | `bRenderLocalOwner` | off | Also draw a pooled copy of entities this client owns, driven by the server's echo of its own updates. Off, the owner sees only its real actor. Turn it on to watch the round trip on a single client. | When an entity's spawn event already made an actor of the entity's class, the pool draws that actor and takes nothing from the pool, so what `OnCrowdySpawned` set on it stays. When ownership of a drawn entity moves to this client, the pool lets go of the actor, which this client now moves; when it moves away, the pool draws this client's actor from the new owner's updates. A pool that is full grows by one actor at a time, spawned during play with collision off until it is activated. At the cap, a new entity of that class waits: it is activated as soon as another entity of the class leaves, or, if its spawn event already made an actor for it, that actor is kept and drawn instead of being replaced. Nothing is dropped. The cap is there so a flood of made-up entity ids from a misbehaving peer cannot make your client spawn without limit; raise it if you legitimately expect more than 256 live remote entities of one class. :::caution[A custom executor needs a matching policy. The default policy reads FCrowdyActorState and refuses anything else.] `UCrowdyTransformRepPolicy` skips an update whose struct is not `FCrowdyActorState`, so an entity that replicates movement and whose executor sends its own struct stands still until its profile names a policy that reads it. `UCrowdyRepApplicationPolicy` has two pure virtuals and requires a subclass; `UCrowdyActorPoolPolicy` ships full bodies and is meant to be instantiated as is. ::: ### The replication application policy A policy of your own can animate a character the way the default does. Keep one `CrowdyActorPool::FProxyMotion` per slot, call `CrowdyActorPool::ApplyProxyMotion` after placing the actor each frame, and `CrowdyActorPool::ResetProxyMotion` when the slot is released. `CrowdyActorPool::IsPlaceable` refuses a position no actor can stand at, so check it on values from another client. The policy is what moves a remote player's proxy. Continuous state is how pawns, players, and AI move, so a policy's first job is to take the location and rotation out of each update and put the proxy where the owner was at `RenderTimeMs`. The shipped `UCrowdyTransformRepPolicy` does exactly that for `FCrowdyActorState`, and for a pawn that only moves it is all you need. You write your own only when your executor sends more than the transform, and then you apply the transform yourself first and your extra fields after, because a custom policy replaces the shipped one rather than adding to it: `UCrowdyActorPoolBackend::ResolvePolicyClass` instantiates the config's class instead of `UCrowdyTransformRepPolicy`, so a policy that never sets location and rotation leaves every proxy under it standing still. `UCrowdyRepApplicationPolicy` reads a state struct out of each update and applies it to the pooled actor each frame: | Override | Called | What you do | |---|---|---| | `ExtractFields(State, ServerTimestampMs, SlotId)` | Per update, per slot | Read your struct out of `State` into your own per-slot buffers. Return false when the struct type is wrong and the update is skipped. | | `ApplyToActor(Actor, SlotId, RenderTimeMs)` | Per frame, per active slot | Apply the buffered state, interpolated to `RenderTimeMs`, to the actor. | | `OnInstanceActivated(Actor, InitialState)` | Once, when a slot activates | A `BlueprintNativeEvent`: set initial state on the actor. | | `OnInstanceDeactivated(SlotId)` | When the entity leaves | Clean up per-slot state. | | `GetExpectedSlotCount()` | At startup | How many slots to pre-allocate; 64 by default. Match your expected player count. | #### The sample ring Both the shipped policy and the example below keep their per-slot history in `TInterpolatedField`, a small ring buffer the SDK ships in `Data/TInterpolatedField.h`, 32 samples deep by default. `TInterpolatedField::Push(Value, TimestampMs)` stores one sample with the server timestamp the update carried. `TInterpolatedField::Sample(RenderTimeMs, LerpFn)` finds the two samples that bracket the render time by binary search and blends between them with the function you pass (`FMath::Lerp` for a location; a quaternion slerp for a rotation). When the render time runs past the newest sample, `Sample` extrapolates from the last two by calling the same function with an alpha above 1, for at most one update interval beyond the newest (100 ms at the default 10 Hz) and never more than 0.2 seconds; after that it holds the value extrapolated to that point, so a player who stops is drawn no more than one step past where they stopped. The step is measured over at least the average gap of the last four samples (50 ms when only two are held), so two updates that arrive almost together after a sender hitch extrapolate at the sender's normal pace instead of throwing the proxy far ahead for a frame. A render time older than the oldest sample holds the oldest sample; a slot is in that state only briefly after activation, until the render time, which runs one interpolation delay behind, catches up with the samples already held. A location follows that extrapolation in full; the rotation slerp clamps its alpha to 1.2, so a rotation extrapolates by at most a fifth of a step. With one sample it returns that sample; with none, the default you pass. `Newest()` is the newest sample, meaningful only while one is held. `PhysicalIndex` is the ring's own index arithmetic, nothing you call. The reason a proxy built on it does not jitter is the render time itself: the actor manager renders at the estimated server time minus the interpolation delay (**Interpolation Delay** in the [map profile](./map-profile.md)'s Remote Entities group, 100 ms by default), so the proxy is always drawn a little behind the newest sample, between two samples it already holds, and never snaps to the latest one as it lands. Extrapolation only runs when an update is late, and its cap keeps a lost stream from sliding a proxy across the map. #### The example: the same shape, with your own field added `ULanternRepPolicy` is what the shipped policy does, plus one field. `FLanternPlayerState`, the struct the [continuous state](./continuous-state.md) page's executor sends for `ALanternPlayer`, carries `Location`, `Rotation`, and `bTorchLit`. The policy keeps one `TInterpolatedField` and one `TInterpolatedField` per slot: `ExtractFields` refuses any other struct type and pushes the location and rotation with the update's server timestamp; `ApplyToActor` samples both at `RenderTimeMs`, calls `SetActorLocationAndRotation` on the proxy, and only then applies the torch flag to the proxy's `Torch` light. The flag is applied as the latest value: a boolean is not something to blend. `OnInstanceDeactivated` resets the slot so a reused slot never starts from a departed player's history. The policy header includes `LanternPlayer.h` for the struct, so this snippet depends on the [`executor-override` block](./continuous-state.md#a-custom-executor) being in your project first. ```cpp // LanternRepPolicy.h #include "Data/CrowdyRepApplicationPolicy.h" #include "Data/TInterpolatedField.h" #include "LanternPlayer.h" #include "LanternRepPolicy.generated.h" // Replaces the shipped transform policy, so it moves the proxy itself and then applies the one field of its own. UCLASS() class ULanternRepPolicy : public UCrowdyRepApplicationPolicy { GENERATED_BODY() public: virtual bool ExtractFields(const FInstancedStruct& State, int64 ServerTimestampMs, int32 SlotId) override; virtual void ApplyToActor(AActor* Actor, int32 SlotId, int64 RenderTimeMs) override; virtual void OnInstanceDeactivated(int32 SlotId) override; private: TArray> Positions; TArray> Rotations; TArray bTorchLitBySlot; void EnsureSlot(int32 SlotId); }; // LanternRepPolicy.cpp #include "LanternRepPolicy.h" #include "Components/PointLightComponent.h" bool ULanternRepPolicy::ExtractFields(const FInstancedStruct& State, int64 ServerTimestampMs, int32 SlotId) { const FLanternPlayerState* Player = State.GetPtr(); if (!Player) { return false; } // Each slot keeps a ring of timestamped samples; Sample reads them back at whatever render time the pool asks for. EnsureSlot(SlotId); Positions[SlotId].Push(Player->Location, ServerTimestampMs); Rotations[SlotId].Push(Player->Rotation, ServerTimestampMs); bTorchLitBySlot[SlotId] = Player->bTorchLit; return true; } void ULanternRepPolicy::EnsureSlot(int32 SlotId) { if (SlotId >= Positions.Num()) { Positions.SetNum(SlotId + 1); Rotations.SetNum(SlotId + 1); bTorchLitBySlot.SetNumZeroed(SlotId + 1); } } ``` ```cpp // LanternRepPolicy.cpp void ULanternRepPolicy::ApplyToActor(AActor* Actor, int32 SlotId, int64 RenderTimeMs) { if (!Positions.IsValidIndex(SlotId)) { return; } const FVector Location = Positions[SlotId].Sample(RenderTimeMs, [](const FVector& A, const FVector& B, float T) { return FMath::Lerp(A, B, T); }); const FRotator Rotation = Rotations[SlotId].Sample(RenderTimeMs, [](const FRotator& A, const FRotator& B, float T) { return FQuat::Slerp(A.Quaternion(), B.Quaternion(), FMath::Clamp(T, 0.f, 1.2f)).GetNormalized().Rotator(); }); // The transform first, then the field of your own: the proxy's torch follows the owner's. Actor->SetActorLocationAndRotation(Location, Rotation); if (const ALanternPlayer* Player = Cast(Actor)) { Player->Torch->SetVisibility(bTorchLitBySlot[SlotId]); } } void ULanternRepPolicy::OnInstanceDeactivated(int32 SlotId) { if (!Positions.IsValidIndex(SlotId)) { return; } Positions[SlotId] = {}; Rotations[SlotId] = {}; bTorchLitBySlot[SlotId] = false; } ``` `ExtractFields` and `ApplyToActor` are C++ only, so the policy class is C++. Set it as **Replication Policy Class** on the Actor Pool Backend Config in the map profile's Details panel. `OnInstanceActivated` is the one hook a Blueprint subclass of the policy may implement. ### The pool policy `UCrowdyActorPoolPolicy` decides what a pooled actor does at three moments, each a `BlueprintNativeEvent` a Blueprint subclass can implement without C++: `OnActorPooled(Actor)` once per actor right after it is spawned into the pool, `OnActorActivated(Actor, InitialState)` when it is checked out (its `InitialState` is empty in the shipped pool, and the identity lands on the component right after it returns), and `OnActorDeactivated(Actor)` when it goes back. The base hides and shows the actor and disables proxy movement; subclass only to add per-actor behaviour at those moments. Pooled actors are genuinely spawned (`SpawnActorDeferred` and `FinishSpawning`), so their constructors and Blueprint-added components run. Before `BeginPlay` the pool marks any entity component on them dormant, so a pre-warmed actor registers no entity and no listener while it stands for nothing. `UCrowdyActorPoolSubsystem::RegisterPool(FCrowdyPoolConfig)` (`ActorClass`, `PoolPolicyClass`, `PoolSize`, `MaxPoolSize`) is what the backend calls to create a pool, a no-op for a class that already has one, and `HasPool(Class)` says whether one exists; `AcquireActor` checks an actor out, growing the pool up to `MaxPoolSize` when every actor is in use, and `ReleaseActor` checks it back in. `crowdy.pool.trace 1` logs spawn, release, reuse, and growth. ## What a pooled proxy does and does not do - The proxy of a spawned entity is the actor its spawn event made, with what `OnCrowdySpawned` gave it, in either arrival order (see [Entities and spawning](./entities-and-spawning.md#receiving-a-spawn-on-a-remote-client)). A client that never received the spawn event, such as one that joined after an entity that replicates movement spawned, draws a pooled actor that has only class defaults and the replicated state. - The owner of an entity is not shown a pooled copy driven by the server's echo of its own updates; **Render Local Owner** (`bRenderLocalOwner`) on the Actor Pool Backend Config brings that copy back. - A proxy's `GetNetID()`, `GetRole()`, `GetWriterID()` and `GetOwnerUserID()` work: the backend assigns the identity to the pooled actor's component when it checks it out, and a spawn event that arrives afterwards fills in the writer and the owner user. `RemoteProxy` is the role it reports. - An entity no spawn event announced, whose class's Crowdy Entity Component uses Player Derived identity and which has not been heard under a tagged id, is drawn as another player's avatar, so a grant to it names that player's session and a grant for it is refused. The pool asks each class once. Its writer id reads invalid and its owner user 0 on this client, and no grant changes that; **Resolve Actor Owner** on its NetID answers the user. An entity a game spawns, or a Player Derived pawn that fell back to a random id, sends under a tagged id from the start and is never taken for an avatar. The one gap is a Player Derived pawn that registers before the local player's id arrives: it still sends under its bare id and reads as an avatar to other clients. ## Swapping at runtime `UCrowdyActorManager::SetBackend(NewBackend)` (Blueprint: **Set Backend**) swaps the active backend: the previous one is deinitialized, slot state is preserved, and the new one receives `ApplyInterpolation` from the next tick. The new backend must already be initialized, and `InitializeBackend` is C++ only, so this is a C++ operation in practice. `GetActiveBackend()` is the live backend, null when none initialized; a backend that refused to initialize is absent here and present in the profile, which is how to tell the two apart from code. ## Writing a backend Subclass `UCrowdyRenderingBackend` and pair it with a `UCrowdyRenderingBackendConfig` subclass carrying whatever your backend needs (an instanced mesh, a pool size). Four overrides are required and seven optional: | Override | Required | Contract | |---|---|---| | `ActivateInstance(SlotId, UUID, EntityClass, InitialState)` | yes | A remote instance became visible. Acquire the rendering resource for `SlotId`. `EntityClass` is never null. | | `DeactivateInstance(SlotId, UUID)` | yes | It left. Release the resource and the per-slot state. | | `ExtractUpdate(State, ServerTimestampMs, SlotId)` | yes | An update arrived. Parse the struct into your interpolation buffers. | | `ApplyInterpolation(SlotId, RenderTimeMs)` | yes | Apply the interpolated state; `RenderTimeMs` is already offset by the interpolation delay. | | `InitializeBackend(World, Config)` | no | Acquire subsystems, read the config. Return false, after logging the reason and the remedy, when you cannot draw with what you were given; the manager refuses you rather than installing you. | | `DeinitializeBackend()` | no | Release what you held. | | `IsInstanceActive(SlotId)` | no | Whether `SlotId` holds something drawn. Return false when `ActivateInstance` could not acquire a resource (a full pool), and the actor manager calls `ActivateInstance` again once capacity may have freed or the entity registers. The default, true, never retries. | | `TakeSpawnData(UUID, InitialState)` | no | Only on a backend whose `DrawsEntitiesAsCrowdRows()` is true: the spawn event of an entity that replicates movement, with no actor spawned for it. Land the data on its representation. | | `ReleaseDestroyedInstance(SlotId, UUID)` | no | A destroy event named the entity. Return true when you stopped drawing it; the default returns false. | | `TryGetDrawnLocation(SlotId, OutLocation)` | no | Where the slot's entity is drawn now. `UCrowdyActorManager::TryGetRemoteLocation(UUID, OutLocation)` answers from it, and voice chat plays and ranks speakers by it. The default returns false, so on your backend spatial voice plays from the centre of the speaker's chunk and every speaker ranks as farthest. | | `GetBackendConfigClass()` | no | The config class your backend reads, so saving a map profile that pairs your backend with another config reports it. Read off the class default object; the default, null, skips the check. | `DrawsEntitiesAsCrowdRows()` is one more, for a backend that represents entities without spawning an actor of the entity's class; the editor reads it off the class default object to decide whether to show authoring surfaces that only make sense on that representation. The default is false. The Crowdy Mass Rendering Backend that ships in the SDK is the one backend that returns true; choose it as the map profile's **Backend Class** and see [Turn Mass on for a map](../mass/turn-mass-on-for-a-map.md). A backend that returns true is also the only body of an entity that replicates movement on its map: a spawn event for one spawns no actor and calls `TakeSpawnData(UUID, InitialState)` instead, which you override to land the data on your representation now, or once the entity's first update has made it. Spawn events can be forged, so bound anything you hold for an entity not drawn yet. `ReleaseDestroyedInstance(SlotId, UUID)` is the other half: a destroy event names the entity (`SlotId` is `INDEX_NONE` when no slot holds it), and returning true says you stopped drawing it, so the actor manager draws it again only from an update that arrives after the half-second destroy window. The defaults do nothing and return false, which is right for a backend that draws actors: the destroyed actor going away is how its slot notices. `SlotId` is a stable index the actor manager assigns for the instance's lifetime; keep your per-instance state in arrays indexed by it. :::danger[A custom backend must never subscribe to the actor tracker itself.] The actor manager is already the single caller of `ActivateInstance` and `DeactivateInstance`. A backend that also subscribes to `UCrowdyActorTracker` activates every entity twice and spawns everything double. The four overrides are your only entry points. ::: ## Gotchas - `BackendClass` alone draws the default executor's movement through `UCrowdyTransformRepPolicy`. A custom state struct needs `BackendConfig` with a `ReplicationPolicyClass` that reads it, and that policy replaces the shipped one: apply `Location` and `Rotation` yourself before anything else, or every proxy stands still. - A policy built on `TInterpolatedField` is the smooth choice for anything that moves. Sample it at `RenderTimeMs`, never at the newest sample: the delay is what hides the network. - `bUseCrowdyActorTracker` off on the profile means no tracker, no manager, and no backend at all. - A spawned entity's proxy has its spawn payload only on clients that received the spawn event; elsewhere its look comes from class defaults or the state struct. - A pool at its cap warns once per class, naming the class and `MaxPoolSizePerClass`; each entity it could not draw is a `crowdy.pool.trace` line, not a warning, since it is retried. Raise `MaxPoolSizePerClass` if you see the warning. On 2.16.0 and earlier, a pool never grew past `DefaultPoolSizePerClass` (8), every entity past that was dropped with a warning and never retried, and its spawn-event actor was destroyed first; see [What's Changed](../guides/whats-changed.md#2026-09-26-sdk-v2170). - A class that arrives over the wire before it is loaded cannot be drawn; see Preloaded Entity Classes on [Entities and spawning](./entities-and-spawning.md). ## Related - [Map profiles](./map-profile.md): where `BackendClass` and `BackendConfig` live. - [Draw a crowd with Mass](../mass/draw-a-crowd-with-mass.md): the Crowdy Mass Rendering Backend, which draws remote entities as crowd rows. - [Continuous state](./continuous-state.md): the executor that produces what the policy consumes. - [Entities and spawning](./entities-and-spawning.md): the actor tracker and the spawn event. - [Entity component](./entity-component.md): the identity a pooled actor is given. # Voxel Chunks Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/voxel-chunks # Voxel Chunks The platform stores a voxel world for every app: chunks of 16 by 16 by 16 cells. Mods, Server Objects, the Application API and other SDKs write them. **Fetch Chunks Around** and **Fetch Chunk** bring chunks into Unreal, decoded and ready to place, so your game can draw them, collide with them, count them or read the data a block carries. ## When you touch this When your game shows blocks the platform holds: a build area, what a mod built, the cells another client painted. A fetch is a one-off copy. When players build together and should see each other's blocks as they are placed, use the **Crowdy Voxel World** instead (see [Keeping a live world](#keeping-a-live-world)): it keeps the chunks around your players loaded, merges everyone's edits as they happen, and sends your player's own. ## The nodes The fetches live on the **Crowdy Voxels** subsystem (`UCrowdyVoxels`, a Game Instance subsystem). The helpers are on **Crowdy Voxel Library** (`UCrowdyVoxelLibrary`) and work with no game instance. All of them are under **Crowdy SDK > Voxels**. Your module needs `CrowdyServices` in its Build.cs. | Blueprint | C++ | Does | |---|---|---| | **Fetch Chunks Around** | `UCrowdyVoxels::FetchChunksAround(int64 ChunkX, int64 ChunkY, int64 ChunkZ, int32 Range, TFunction OnDone)` | Every chunk the platform stores within Range of a chunk. Latent: **On Fetched** or **On Failed** fires once. | | **Fetch Chunk** | `UCrowdyVoxels::FetchChunk(int64 ChunkX, int64 ChunkY, int64 ChunkZ, TFunction OnDone)` | One chunk, whether or not the platform stores it. Latent, like the one above. Needs Application API v2.70.0; an older one refuses it with `GRAPHQL_VALIDATION_FAILED`. | | **Get Voxel** | `UCrowdyVoxelLibrary::GetVoxel(const FCrowdyVoxelChunk& Chunk, FIntVector Position)` | The voxel at one position, with its type and state. | | **Get Filled Voxels** | `UCrowdyVoxelLibrary::GetFilledVoxels(const FCrowdyVoxelChunk& Chunk)` | Every voxel of a chunk whose type is not 0, with its position, type and state. | | **Get Chunk Origin** | `UCrowdyVoxelLibrary::GetChunkOrigin(WorldContextObject, ChunkX, ChunkY, ChunkZ)` | The chunk's minimum corner in your level. | | **Get Voxel Size** | `UCrowdyVoxelLibrary::GetVoxelSize(WorldContextObject)` | The edge of one cell in world units: the chunk size over 16, 100 by default. | | **World To Voxel** | `UCrowdyVoxelLibrary::WorldToVoxel(WorldContextObject, Location, ChunkX, ChunkY, ChunkZ, Position)` | The chunk a world location is in, and its cell there, each axis 0 to 15. | | **Voxel To World** | `UCrowdyVoxelLibrary::VoxelToWorld(WorldContextObject, ChunkX, ChunkY, ChunkZ, Position)` | The centre of a cell in your level. | The player must be signed in to the app. Fetching needs no permission key: any player of the app can read its chunks. ## How far a fetch reaches **Range** counts chunks on every axis from the chunk you name, so 1 fetches a cube of 3 chunks on a side (27 chunks) and 2 fetches 5 on a side (125). It runs from 1 to 8, the platform's range; a value outside is clamped. **Fetch Chunks Around** leaves out a chunk the platform does not store, so an empty area answers **On Fetched** with no chunks. **Fetch Chunk** always answers its one chunk: one the platform does not store comes back empty, with **Stored** false. :::caution Only a chunk write (`updateChunk`, for example from a world generator or a chunk write-back) stores a chunk. Blocks placed only by single-voxel writes, such as a mod's or a hub's `set_voxels`, `updateVoxel` or a realtime voxel update, in a chunk nobody has stored do not come back from either of these two nodes: they return neither the chunk nor its edits until the chunk is stored. The live world and [Fetch Chunks In Box](#fetching-a-box) read those edits, so a chunk that has only edits loads with them. ::: ## What a chunk holds The platform keeps two things for a chunk: a grid of 4,096 one-byte types, and a log of edits made to single voxels (a player's edit, a mod's writes, a Server Object's). An edit has a position and a type, each any signed 16-bit value, and up to 1,024 bytes of state your game gives meaning to. Each **Crowdy Voxel Chunk** in an answer has both, already combined: | Field | Is | |---|---| | **X**, **Y**, **Z** | The chunk's coordinates, 64-bit. | | **Grid** | 4,096 block types, one byte each, at index x + 16 * y + 256 * z with each of x, y and z from 0 to 15, with every edit applied that fits a cell and a byte. 0 is empty. | | **Edits** | The chunk's per-voxel entries: the states stored with it and every recorded edit, one per position, sorted by position (z, then y, then x). Where the platform lists a position twice, the later entry is kept. This includes the voxels the grid cannot hold: a position outside 0 to 15, or a type outside 0 to 255. | | **Stored** | True when a chunk write has stored this chunk (see the caution above). False on a chunk that the live world or Fetch Chunks In Box returned for its edits alone, over an empty grid. | | **Edits Truncated** | True when the platform cut the edits it sent, so the chunk is incomplete. The platform applies at most 65,536 edits for **Fetch Chunk**, and 262,144 across one request of **Fetch Chunks Around**, so a heavily edited neighbourhood is cut sooner than one chunk alone would be. The SDK has no node yet for reading the rest of a chunk's edit log. | You never apply edits yourself. Use **Get Voxel** for one position and **Get Filled Voxels** for all of them: both take an edit over the grid, return the edit's state, and include the voxels the grid cannot hold. A grid cell whose edit has a type wider than a byte reads 0 in **Grid**, so read it through the helpers, not the grid alone. Each **Crowdy Voxel** has a **Position** (in the chunk's own X, Y and Z), a **Type** and its **State** bytes, empty when it has none. In Blueprint, **State** is a byte array; decode anything structured in C++. Types mean whatever your game decides. Keep one table from type to look that you use everywhere; a game on 16 by 16 by 16 chunks with up to 255 block types never needs anything outside the grid. ## Where a cell is in your level Chunk (x, y, z) is the chunk the SDK puts an actor in when it stands at that spot, so voxels and players agree on where they are. A voxel's position is Unreal X, Y and Z, z up, with no axis swapped. Its centre is: **Get Chunk Origin** + (position + 0.5) * **Get Voxel Size** which is what **Voxel To World** returns. At the default chunk size of 1600 units a cell is 100 units, and cell (1, 2, 3) of chunk (0, 0, 0) is centred at (150, 250, 350). **World To Voxel** goes the other way, from a location to its chunk and cell. :::note Content built where y is up, such as the web Construct's starter mods, has its height along Unreal +Y here. The data is the same; draw it as it is, or author for z up. ::: ## Fetching and drawing `ShowBlocksAround` fetches the chunks within two of the lantern's chunk. `AddChunkBlocks` adds one cube instance per filled voxel of a chunk to an Instanced Static Mesh component, all in one call. ```cpp // LanternPlayer.h #include "Components/InstancedStaticMeshComponent.h" #include "Subsystem/CrowdyVoxels.h" // The engine cube, one instance per filled cell around the lantern. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Lantern") TObjectPtr Blocks; UFUNCTION(BlueprintCallable, Category = "Lantern") void ShowBlocksAround(); // One cube per filled cell of Chunk, added in one call. UFUNCTION(BlueprintCallable, Category = "Lantern") void AddChunkBlocks(const FCrowdyVoxelChunk& Chunk); // LanternPlayer.cpp #include "Engine/StaticMesh.h" #include "Subsystem/CrowdyVoxelLibrary.h" #include "UObject/ConstructorHelpers.h" // The blocks keep a world transform of their own, so they stay where they are while the lantern walks. static ConstructorHelpers::FObjectFinder Cube(TEXT("/Engine/BasicShapes/Cube.Cube")); Blocks = CreateDefaultSubobject(TEXT("Blocks")); Blocks->SetupAttachment(RootComponent); Blocks->SetUsingAbsoluteLocation(true); Blocks->SetUsingAbsoluteRotation(true); Blocks->SetUsingAbsoluteScale(true); Blocks->SetCollisionEnabled(ECollisionEnabled::NoCollision); Blocks->SetStaticMesh(Cube.Object); void ALanternPlayer::ShowBlocksAround() { int64 ChunkX = 0, ChunkY = 0, ChunkZ = 0; FIntVector Cell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), ChunkX, ChunkY, ChunkZ, Cell); TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->FetchChunksAround(ChunkX, ChunkY, ChunkZ, 2, [WeakThis](const FCrowdyChunkFetch& Fetch) { ALanternPlayer* Self = WeakThis.Get(); if (!Self || Fetch.Result != ECrowdyVoxelResult::Ok) { return; } Self->Blocks->ClearInstances(); for (const FCrowdyVoxelChunk& Chunk : Fetch.Chunks) { Self->AddChunkBlocks(Chunk); } }); } void ALanternPlayer::AddChunkBlocks(const FCrowdyVoxelChunk& Chunk) { // The engine cube is 100 units, one cell at the default chunk size. const double Size = UCrowdyVoxelLibrary::GetVoxelSize(this); const FVector Origin = UCrowdyVoxelLibrary::GetChunkOrigin(this, Chunk.X, Chunk.Y, Chunk.Z); TArray Cubes; for (const FCrowdyVoxel& Voxel : UCrowdyVoxelLibrary::GetFilledVoxels(Chunk)) { Cubes.Emplace(FQuat::Identity, Origin + (FVector(Voxel.Position) + 0.5) * Size, FVector(Size / 100.0)); } Blocks->AddInstances(Cubes, false, true); } ``` A custom event, **ShowBlocksAround**, finds the lantern's chunk with **World To Voxel** and calls **Fetch Chunks Around** with **Range** 2. **On Fetched** clears the cubes drawn last time with **Clear Instances**, then loops over the chunks and hands each to **Add Chunk Blocks**, the C++ function above. [Blueprint snippet: voxel-chunks-read, see /bp/unreal-sdk/voxel-chunks-read.txt] :::caution Do not loop over every cell in Blueprint. A For Each Loop evaluates the pure node that feeds its Array, such as **Get Filled Voxels**, again on every pass, so a solid chunk costs thousands of scans and can trip the engine's runaway-loop limit. Do the per-cell work in one C++ function, as **Add Chunk Blocks** does. ::: ## Fetching a box **Fetch Chunks Around** reads a cube. For any other shape, such as one layer of chunks or a long strip, ask for the box itself with `UCrowdyVoxels::FetchChunksInBox(Corner, OppositeCorner, OnDone, Cancelled)`. It is C++ only; there is no Blueprint node. - Both corners are included, in either order, and the box holds at most 4,913 chunks (17 on a side). A larger box answers **Failed**. - A chunk the platform never stored but holds edits for comes back with **Stored** false and those edits over an empty grid. A chunk with neither is left out. - `Cancelled` is an optional shared bool. Once it is true nothing more is asked for and `OnDone` never runs, so a read for an area the player has left costs no more requests. `ShowBlocksInSlab` fetches one layer of 9 by 9 chunks around the lantern and draws it as above. Each call cancels the read before it through `SlabRead`, and so does `EndPlay`, so a slab the lantern has left never redraws. ```cpp // LanternPlayer.h #include "Subsystem/CrowdyVoxels.h" void ShowBlocksInSlab(); virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; // Set to true to stop the slab read in flight: a newer read or the lantern leaving play replaces it. TSharedPtr SlabRead; // LanternPlayer.cpp #include "Subsystem/CrowdyVoxelLibrary.h" void ALanternPlayer::ShowBlocksInSlab() { int64 ChunkX = 0, ChunkY = 0, ChunkZ = 0; FIntVector Cell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), ChunkX, ChunkY, ChunkZ, Cell); // A read still running is for a slab the lantern has left: stop it, so its answer never redraws. if (SlabRead) { *SlabRead = true; } SlabRead = MakeShared(false); // One layer of chunks, 9 by 9: a shape Fetch Chunks Around, which reads a cube, cannot ask for. TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->FetchChunksInBox( FInt64Vector(ChunkX - 4, ChunkY - 4, ChunkZ), FInt64Vector(ChunkX + 4, ChunkY + 4, ChunkZ), [WeakThis](const FCrowdyChunkFetch& Fetch) { ALanternPlayer* Self = WeakThis.Get(); if (!Self || Fetch.Result != ECrowdyVoxelResult::Ok) { return; } Self->Blocks->ClearInstances(); for (const FCrowdyVoxelChunk& Chunk : Fetch.Chunks) { Self->AddChunkBlocks(Chunk); } }, SlabRead); } void ALanternPlayer::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (SlabRead) { *SlabRead = true; } Super::EndPlay(EndPlayReason); } ``` ## Keeping a live world The **Crowdy Voxel World** (`UCrowdyVoxelWorld`) is a World subsystem: one per level, under **Crowdy SDK > Voxels**. Tell it which actors to follow and it keeps the chunks around them loaded, applies other players' edits as they arrive, and shows your player's own edits at once while it sends them. | Blueprint | C++ | Does | |---|---|---| | **Follow** | `Follow(AActor* Actor, int32 Range)` | Keeps every chunk within Range (1 to 7) of the actor's chunk loaded and unloads what falls past Range + 1. Several followed actors load the union. Call it any time, even before sign-in. | | **Stop Following** | `StopFollowing(AActor* Actor)` | A destroyed actor stops being followed by itself. | | **Is Chunk Loaded**, **Is Chunk Live** | `IsChunkLoaded(X, Y, Z)`, `IsChunkLive(X, Y, Z)` | Live means loaded, within 8 chunks of your player's actor, and fetched again after the connection settled, so other players' edits there reach you as they happen. | | **Is Chunk In Reach** | `IsChunkInReach(X, Y, Z)` | True when the chunk is within 8 chunks of your player's own chunk on every axis, loaded or not, so an edit there reaches the players near it as it happens. False until your player's chunk is known. | | **Get Voxel** | `GetVoxel(X, Y, Z, Position)` | What your player sees at a cell: their own edit still waiting for its answer, else the confirmed voxel. | | **Find Chunk** | `FindChunk(X, Y, Z, Chunk)` | A copy of a loaded chunk as your player sees it. It copies the whole chunk, so read single cells with **Get Voxel**. | | **Set Voxel**, **Set Voxels** | `SetVoxel(const FCrowdyVoxelWrite&)`, `SetVoxels(...)` | Shows the edit at once, sends it, and returns its edit id (never 0). | | (C++ only) | `ForEachFilledVoxel(X, Y, Z, Visit)` | Calls Visit for every cell of a loaded chunk with a type of 1 to 255, in index order, with no copy. Use it to build or rebuild a chunk's cubes. | | (C++ only) | `ForEachLoadedChunk(Visit)` | Calls Visit for every chunk loaded now, so a renderer that starts after chunks have loaded can draw them; later loads arrive as **On Chunk Loaded**. | Its events, each on the game thread: | Event | Fires | |---|---| | **On Chunk Loaded**, **On Chunk Unloaded** (`OnChunkLoaded`, `OnChunkUnloaded`, each an `FOnCrowdyVoxelChunk` with `ChunkX`, `ChunkY`, `ChunkZ`) | Once per chunk as it comes and goes. A chunk's first contents arrive here, not through **On Chunk Changed**, so draw on both. | | **On Chunk Changed** (`OnChunkChanged`, an `FOnCrowdyVoxelChunkChanged`: X, Y, Z, Positions) | At most once a frame per chunk, naming every cell whose value as your player sees it changed, whoever changed it. Redraw that chunk, or only those cells. | | **On Edit Done** (`OnEditDone`, an `FOnCrowdyVoxelEditDone`: Edit Id, Write, Result, Message) | Exactly once per edit id, never inside the **Set Voxel** call. | When a hub or a mod writes a whole chunk, the platform tells the clients near it, and the world fetches the chunk again by itself, at most once a frame. **On Chunk Changed** then names the cells that differ and **On Chunk Loaded** does not fire a second time. ### An edit's life 1. **Set Voxel** checks the write. A chunk that is not loaded, a position or type wider than 16 bits, or state over 1,024 bytes ends it **Failed**; no realtime connection ends it **Not Signed In**. Either way nothing is shown or sent. 2. Otherwise the cell shows the new value at once and **On Chunk Changed** names it, even when the value is the same as before. 3. The edit is sent: at most 100 a second, so voice, movement and video keep room under the platform's 500 messages a second per player. A long **Set Voxels** queues the rest, already shown. 4. **On Edit Done** reports how it ended, always after the **On Chunk Changed** that showed it: | Result | Means | The cell then shows | |---|---|---| | **Ok** | The platform applied it and said so. | The edit, now confirmed. | | **Refused** | The platform refused it, usually because your player may not build there; the message names the code. | The newest value anyone else committed, never a value saved from before your edit. The chunk is fetched again to settle it. | | **No Answer** | Nothing came back within a second, or the connection dropped while it waited. The platform may have applied it or not. | Whatever a fresh fetch of the chunk says, which settles it either way. | | **Not Signed In** | The connection dropped before it was sent. | The value before it, unchanged. | Your player's edits to one cell are answered one by one, and the newest waiting one is what **Get Voxel** shows. An edit that is refused or unanswered is put back after its **On Edit Done**, so a listener sees the reason first and the cell change after. :::caution A live edit reaches only players within 8 chunks of the player who made it; everyone else sees it the next time they fetch that chunk. So a player may edit a chunk far away: **Set Voxel** sends it and **On Edit Done** says **Ok**, but players already near that chunk keep the old cell until they fetch it again. To allow only edits that nearby players see live, check **Is Chunk In Reach** before **Set Voxel**. A chunk loaded further than 8 chunks from your own player stays as it was fetched until it comes back within reach, when the world fetches it again. A player's first edit in a chunk the platform never stored survives a reload: the world reads the chunk's recorded edits along with it. ::: `BuildAround` binds the world's events and follows the lantern at range 1. A chunk's first contents arrive as **On Chunk Loaded**, not **On Chunk Changed**, so it binds that too, and **On Chunk Unloaded** redraws a chunk as empty. `RedrawChunk` rebuilds one chunk's cubes from `ForEachFilledVoxel`, each chunk in its own Instanced Static Mesh component so a change touches only its own chunk. `PlaceBlock` sets a cell of the lantern's chunk, and `HandleEditDone` logs why an edit did not land. ```cpp // LanternPlayer.h #include "Components/InstancedStaticMeshComponent.h" #include "Subsystem/CrowdyVoxelWorld.h" // One cube component per chunk the lantern draws, so redrawing one chunk leaves the others alone. UPROPERTY() TMap> ChunkBlocks; UFUNCTION(BlueprintCallable, Category = "Lantern") void BuildAround(); // Sets Cell of the lantern's chunk to Type; 0 clears it. UFUNCTION(BlueprintCallable, Category = "Lantern") void PlaceBlock(FIntVector Cell, int32 Type); UFUNCTION(BlueprintCallable, Category = "Lantern") void RedrawChunk(int64 ChunkX, int64 ChunkY, int64 ChunkZ); UFUNCTION() void HandleChunkChanged(int64 ChunkX, int64 ChunkY, int64 ChunkZ, const TArray& Positions); UFUNCTION() void HandleEditDone(int64 EditId, const FCrowdyVoxelWrite& Write, ECrowdyVoxelResult Result, const FString& Message); // LanternPlayer.cpp #include "Subsystem/CrowdyVoxelLibrary.h" void ALanternPlayer::BuildAround() { UCrowdyVoxelWorld* Voxels = GetWorld()->GetSubsystem(); if (!Voxels) { return; } // A chunk's first contents arrive as On Chunk Loaded, not On Chunk Changed; an unloaded chunk redraws as empty. Voxels->OnChunkLoaded.AddUniqueDynamic(this, &ALanternPlayer::RedrawChunk); Voxels->OnChunkUnloaded.AddUniqueDynamic(this, &ALanternPlayer::RedrawChunk); Voxels->OnChunkChanged.AddUniqueDynamic(this, &ALanternPlayer::HandleChunkChanged); Voxels->OnEditDone.AddUniqueDynamic(this, &ALanternPlayer::HandleEditDone); Voxels->Follow(this, 1); } void ALanternPlayer::PlaceBlock(FIntVector Cell, int32 Type) { UCrowdyVoxelWorld* Voxels = GetWorld()->GetSubsystem(); if (!Voxels) { return; } FCrowdyVoxelWrite Write; FIntVector LanternCell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), Write.ChunkX, Write.ChunkY, Write.ChunkZ, LanternCell); Write.Voxel.Position = Cell; Write.Voxel.Type = Type; Voxels->SetVoxel(Write); } void ALanternPlayer::RedrawChunk(int64 ChunkX, int64 ChunkY, int64 ChunkZ) { const UCrowdyVoxelWorld* Voxels = GetWorld()->GetSubsystem(); if (!Voxels) { return; } TObjectPtr& Cubes = ChunkBlocks.FindOrAdd(FInt64Vector(ChunkX, ChunkY, ChunkZ)); if (!Cubes) { Cubes = NewObject(this); Cubes->SetupAttachment(RootComponent); Cubes->SetUsingAbsoluteLocation(true); Cubes->SetUsingAbsoluteRotation(true); Cubes->SetUsingAbsoluteScale(true); Cubes->SetCollisionEnabled(ECollisionEnabled::NoCollision); // The same engine cube the Blocks component draws. Cubes->SetStaticMesh(Blocks->GetStaticMesh()); Cubes->RegisterComponent(); } const FVector Scale(UCrowdyVoxelLibrary::GetVoxelSize(this) / 100.0); TArray Transforms; Voxels->ForEachFilledVoxel(ChunkX, ChunkY, ChunkZ, [&](FIntVector Position, int32) { Transforms.Emplace(FQuat::Identity, UCrowdyVoxelLibrary::VoxelToWorld(this, ChunkX, ChunkY, ChunkZ, Position), Scale); }); Cubes->ClearInstances(); Cubes->AddInstances(Transforms, false, true); } void ALanternPlayer::HandleChunkChanged(int64 ChunkX, int64 ChunkY, int64 ChunkZ, const TArray& Positions) { // Positions names every changed cell; redrawing the whole chunk is the simplest correct answer. RedrawChunk(ChunkX, ChunkY, ChunkZ); } void ALanternPlayer::HandleEditDone(int64 EditId, const FCrowdyVoxelWrite& Write, ECrowdyVoxelResult Result, const FString& Message) { if (Result == ECrowdyVoxelResult::Ok) { return; } // The cell then settles to what the platform holds, and On Chunk Changed redraws it. UE_LOG(LogTemp, Warning, TEXT("The block was not placed: %s"), *Message); } ``` **BuildAround** gets the **Crowdy Voxel World**, binds **On Chunk Loaded** and **On Chunk Unloaded** to one event that calls **Redraw Chunk** (the C++ function above), binds **On Chunk Changed** the same way, and binds **On Edit Done** to print the message when **Result** is not **Ok**. Then it calls **Follow** with **Self** and **Range** 1. [Blueprint snippet: voxel-world-live, see /bp/unreal-sdk/voxel-world-live.txt] **PlaceBlock** finds the lantern's chunk with **World To Voxel**, makes a **Crowdy Voxel** with the cell and type, wraps it in a **Crowdy Voxel Write** with that chunk, and calls **Set Voxel**. [Blueprint snippet: voxel-world-place, see /bp/unreal-sdk/voxel-world-place.txt] ### What the live world costs - **Loading** reads each missing chunk once, as boxes of at most one page (32 chunks), several read side by side. Crossing into a new chunk reads only the new slab; a loaded chunk is read again only after a reconnect, when it comes back within reach, when the platform replaces it as a whole, or to settle an edit. - **Each live edit** is applied where it lands, in the chunk's grid and its sorted edits. **Get Voxel** is a lookup; with your own edits waiting it also checks those, which stay few at 100 a second. - **Memory** is a full chunk per loaded chunk: 4 KiB of grid plus its edits. Range 7 loads up to 3,375 chunks, about 14 MB before edits; follow the smallest range you draw. - **On Chunk Changed** builds one array per changed chunk per frame; bind it only where you redraw. ### Reloading a chunk A mod's and a hub's writes reach players near the chunk live: single-cell writes arrive as voxel updates, and a whole-chunk write as one notice, after which the world fetches the chunk again (see above). Live events can be lost, and a player farther away gets an edit only from the next fetch, so the world can still hold an older copy. **Reload Chunk** (`UCrowdyVoxelWorld::ReloadChunk(ChunkX, ChunkY, ChunkZ, OnDone)`, under **Crowdy SDK > Voxels**) fetches one loaded chunk again and merges it the way every fetch is merged, under your player's own waiting edits. Use it after you know a mod or a hub wrote the chunk, for example when a [mod](./mods.md#what-a-mod-is-for) that builds on its plot says so in a call's reply, or when a player asks for a refresh. It is latent: **On Done** or **On Failed** fires once, on a later frame, never inside the call. - **On Done** fires when a fetch that began after your call has merged. **On Chunk Changed** has already named every cell it changed, so a redraw bound to it has run by then. A chunk that did not change fires nothing there. - **On Failed** fires when the chunk is not loaded, the connection dropped, the fetch failed, or no fetch completed within 30 seconds. In C++ the callback gets a result other than **Ok** and a **Message**. A chunk that is not loaded is not loaded by this call: [Follow](#keeping-a-live-world) an actor near it first. - If the world ends first, neither pin fires and the callback is dropped without running. A mod that writes on a timer may write after your fetch has been read. Reload again when the mod tells you it wrote, rather than once at the start. `ReloadPlot` finds the workshop's chunk with **World To Voxel** and reloads it, so the plot shows every block written there even if the live world missed one. It logs the reason when a reload does not happen. ```cpp // LanternWorkshop.h #include "Subsystem/CrowdyVoxelWorld.h" UFUNCTION(BlueprintCallable, Category = "Lantern") void ReloadPlot(); // LanternWorkshop.cpp #include "Subsystem/CrowdyVoxelLibrary.h" void ALanternWorkshop::ReloadPlot() { UCrowdyVoxelWorld* Voxels = GetWorld()->GetSubsystem(); if (!Voxels) { return; } int64 ChunkX = 0, ChunkY = 0, ChunkZ = 0; FIntVector Cell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), ChunkX, ChunkY, ChunkZ, Cell); // Fetch the chunk again for anything the live world missed; On Chunk Changed names what changed. Voxels->ReloadChunk(ChunkX, ChunkY, ChunkZ, [](ECrowdyVoxelResult Result, const FString& Message) { if (Result != ECrowdyVoxelResult::Ok) { UE_LOG(LogTemp, Warning, TEXT("The plot did not reload: %s"), *Message); } }); } ``` **ReloadPlot** finds the workshop's chunk with **World To Voxel** and calls **Reload Chunk**. **On Failed** prints **Message**. **On Chunk Changed**, bound in **BuildAround** above, redraws what changed. [Blueprint snippet: reload-chunk, see /bp/unreal-sdk/reload-chunk.txt] It costs one chunk fetch, the same as one chunk of a **Fetch Chunk**. ## When a fetch fails **On Failed** gives the result and a message. Nothing from a failed fetch is returned. | Result | Means | |---|---| | **Not Signed In** | The player has no app token yet. Fetch after sign-in completes. | | **Refused** | The platform answered with an error; the message starts with its code. | | **Failed** | The request did not complete: no connection, a timeout, the app changed while it was in flight, or a box of more than 4,913 chunks. | | **Bad Reply** | The answer held something the platform never sends: a malformed chunk or state, an answer nested too deeply for the SDK's JSON guard, a position or type wider than 16 bits, state over 1,024 bytes, more chunks than were asked for, or a different chunk than **Fetch Chunk** asked for. None of it is returned. | A fetch that cannot start (no token, no API client) answers before the call returns. A chunk that appears on two pages of a fetch is kept once. A chunk first stored while a fetch runs may still be missing from its answer; fetch again for it. ## What it costs - **One request per 32 chunks.** A fetch of range 2 is up to four requests, one after another, and answers once with all of them. Range 8 can be over a hundred; fetch the smallest range that covers what you draw. **Fetch Chunk** is one request. - **Each answer is handled on the game thread** when it arrives: parsed, checked, and decoded into chunks without building an Unreal JSON tree. Measured on a desktop CPU with made-up data, a whole fetch of 125 dense chunks took about 2 ms with no edits, about 26 ms with 256 recorded edits per chunk (2.7 MB of answer), and about 87 ms when each of those edits also carried 64 bytes of state (5.4 MB). One chunk at the platform's limit of 65,536 edits took about 110 ms, and the worst single page, 32 chunks carrying 262,144 edits between them (16.7 MB), about 0.45 seconds. Decoding grows in step with the number of edits, between 0.1 and 0.4 microseconds each; most of the rest is parsing the answer. - **Edits cost the most,** and state more than type alone: each edit with state keeps its own copy of its bytes. - **Fetch Chunk downloads its chunk's LOD data and chunk state,** which it does not return, so a chunk with LODs costs far more bandwidth than its voxels. **Fetch Chunks Around**, Fetch Chunks In Box and the live world select only each chunk's coordinates, voxels and states. - **Get Voxel** searches the sorted edits, so it is cheap at any count. **Get Filled Voxels** allocates one array per chunk; for a large area, read **Grid** directly in C++ and skip the 0 bytes, then add the voxels in **Edits** the grid cannot hold. - **The Blueprint nodes copy their chunks** into their output pins. C++ callers get them by reference. ## From C++ `FetchChunksAround`, `FetchChunksInBox` and `FetchChunk` run `OnDone` once on the game thread, unless the game instance ends first, and before they return when the fetch cannot start. `UCrowdyVoxels::PageSize` (32) is the chunks one request asks for. The types behind the nodes: | Type | Is | |---|---| | `FCrowdyVoxelChunk` | `X`, `Y`, `Z` (`int64`), `Grid` (`TArray`, 4,096), `Edits` (`TArray`, sorted by position; the helpers rely on that order and on `Grid` agreeing with it, so treat a fetched chunk as a read-only snapshot and fetch again for a fresh one), `bStored` and `bEditsTruncated` (`bool`). | | `FCrowdyVoxel` | `Position` (`FIntVector`, each axis a 16-bit value), `Type` (`int32`, a 16-bit value) and `State` (`TArray`, up to 1,024 bytes). Writable from Blueprint, so a write can be made there. | | `FCrowdyVoxelWrite` | `ChunkX`, `ChunkY`, `ChunkZ` (`int64`) and `Voxel` (`FCrowdyVoxel`): one edit for **Set Voxel**. | | `FCrowdyChunkFetch` | `Result`, `Chunks` (in the platform's order; exactly one from `FetchChunk`) and `Message`. | | `ECrowdyVoxelResult` | `Ok`, `NotSignedIn`, `Refused`, `Failed`, `BadReply`, `NoAnswer` (an edit only). | | `UCrowdyVoxelWorld` | The live world. `EditsPerSecond` (100), `AnswerTimeoutSeconds` (1), `SettleSeconds` (5) and `LiveReach` (8) are its fixed numbers. | | `UCrowdyFetchChunksAround`, `UCrowdyFetchChunk` | The two nodes. C++ calls the subsystem instead. | | `UCrowdyReloadChunk` | The **Reload Chunk** node; C++ calls `UCrowdyVoxelWorld::ReloadChunk`. Its pins use `FCrowdyVoxelReloadAsyncResult` (`Result`, `Message`). | | `FCrowdyChunksFetchedAsyncResult`, `FCrowdyChunkFetchedAsyncResult` | The delegate types of the nodes' pins: `Chunks` or `Chunk`, `Result` and `Message`. | # Chunk Claims Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/chunk-claims # Chunk Claims A player can claim one chunk of the voxel world at a time, as often as you let them. A claimed chunk is theirs: only they can build in it, and it stays theirs until they give it back. **Claim Chunk**, **Release Claim** and **Find Claims** do this from Unreal, and **Can Edit Chunk** and **Get Grid Permissions** tell you whether a player may build in a chunk. ## When you touch this When your game gives players land: a plot to build on, a base, a stall. The claim is the platform's own record, so other players' edits in a claimed chunk are refused whatever their client does. Pair it with the [Crowdy Voxel World](./voxel-chunks.md#keeping-a-live-world) to let the owner build there. ## The nodes They live on the **Crowdy Claims** subsystem (`UCrowdyClaims`, a Game Instance subsystem), under **Crowdy SDK > Claims**. Your module needs `CrowdyServices` in its Build.cs. Each is latent: **On Done** or **On Failed** fires once, never inside the call. | Blueprint | C++ | Does | |---|---|---| | **Claim Chunk** | `UCrowdyClaims::ClaimChunk(int64 ChunkX, int64 ChunkY, int64 ChunkZ, TFunction OnDone)` | Claims one chunk for the signed-in player. **On Done** gives the new claim's **Grid Id**. | | **Release Claim** | `UCrowdyClaims::ReleaseClaim(int64 GridId, TFunction OnDone)` | Gives one of the player's claims back. The chunk's voxels stay; the chunk is claimable again. | | **Find Claims** | `UCrowdyClaims::FindClaims(int64 LowX, int64 LowY, int64 LowZ, int64 HighX, int64 HighY, int64 HighZ, TFunction OnDone)` | Every claim inside a box of chunks, corners included, in grid id order: its chunk, its owner's user id, and whether the signed-in player owns it. | | **Can Edit Chunk** | `UCrowdyClaims::CanEditChunk(int64 ChunkX, int64 ChunkY, int64 ChunkZ, TFunction OnDone)` | Whether the signed-in player may edit voxels in one chunk, and the grid that decides. | | **Get Grid Permissions** | `UCrowdyClaims::GetGridPermissions(int64 ChunkX, int64 ChunkY, int64 ChunkZ, TFunction OnDone)` | Every grid covering one chunk, with the player's own permission keys on each. | The Blueprint nodes are the async actions `UCrowdyClaimChunk`, `UCrowdyReleaseClaim`, `UCrowdyFindClaims`, `UCrowdyCanEditChunk` and `UCrowdyGetGridPermissions`; C++ calls the subsystem instead. Each node's **On Done** and **On Failed** pins share one delegate: `FCrowdyClaimAsyncResult` (**Claim Chunk** and **Release Claim**: `GridId`, `Result`, `Message`), `FCrowdyClaimSearchAsyncResult` (**Find Claims**: `Claims`, `Result`, `Message`), `FCrowdyChunkEditAsyncResult` (**Can Edit Chunk**: `bCanEdit`, `GridId`, `Result`, `Message`) and `FCrowdyGridPermissionsAsyncResult` (**Get Grid Permissions**: `Grids`, `Result`, `Message`). Two structs carry the lists. `FCrowdyChunkClaimInfo` is one claim in a **Find Claims** answer: `GridId`, `ChunkX`, `ChunkY`, `ChunkZ`, `OwnerUserId` (all `int64`) and `bOwnedByMe`. `FCrowdyGridPermissionRow` is one grid in a **Get Grid Permissions** answer: `GridId`, its chunk box as `LowChunkX`, `LowChunkY`, `LowChunkZ`, `HighChunkX`, `HighChunkY`, `HighChunkZ` (all `int64`), `PermissionKeys` (the player's own) and `bDecidesEdits`. **List Grid Channels** (`UCrowdyClaims::ListGridChannels(int64 GridId, TFunction OnDone)`) answers the channels a grid owns, oldest first, in **Channels**; the list is empty when the grid has none. A **Grid Id** of 0 or less is **Refused** without sending, and a row that is not one of the grid's own fails the whole list as **Bad Reply**. Its node is `UCrowdyListGridChannels` with `FCrowdyGridChannelsAsyncResult` (`Channels`, `Result`, `Message`). It takes a grid id you already hold, such as a claim's. Chunk coordinates are the ones the SDK places actors in; **World To Voxel** on the [Voxel Chunks](./voxel-chunks.md#the-nodes) page turns a location into its chunk. The player must be signed in to the app. ## What a claim is - A claim covers exactly one chunk and belongs to the player who made it. Nothing else names a claim: it is a grid on the platform, and **Grid Id** is its id. - Only wilderness can be claimed: a chunk no grid covers but the app's world grid. A chunk inside a plot, a zone or someone's claim is refused. - The app's claim policy must be **Self Claim**, the default. You set it in Crowdy Studio. - The owner may build in the chunk, talk on voice there and teleport into it; the code and video keys come with a claim only where the player's tier already has them. Everyone else is refused building there, however open the land around it is. - The platform names no limit on claims per player. If your game wants one, keep your own count, for example in a Server Object. ## What each result means | Result | Means | |---|---| | **Success** | Done. **Claim Chunk** answers the new **Grid Id**; **Find Claims** answers its list, empty when the box holds no claim. | | **Not Signed In** | The player has no app token yet. Nothing was sent. | | **Not Claimable** | The chunk is inside another grid: a plot, a zone, or someone's claim. | | **Already Claimed** | The chunk is already claimed. The platform answers this or **Not Claimable** for a claimed chunk, so treat the two the same. | | **Refused** | Any other refusal, such as a claim policy other than Self Claim, two players claiming at once, or a release of a grid that is not the player's. **Message** names the platform's code. | | **Failed** | The request did not complete, or the box was too large. | | **Bad Reply** | The answer was malformed, so nothing from it is used. | ## Finding claims **Find Claims** reads the grids over the box once, then the owner of each grid that covers a single chunk, one request each, and keeps those whose owner claimed them. The world grid, plots and grids with no owner are not claims and are left out. If any read fails, the whole search answers that failure, never part of a list. The box holds at most 4,096 chunks (16 on each side, or any other shape that size). Search once for the whole area your level shows, not once per chunk: a level of 20 claim pads is one search, not 20. Nothing pushes a claim to other players. Search again when your player arrives somewhere or when it matters, for example when they step onto a plot. ## Checking whether a player can build An edit in a chunk is allowed when the player holds `update_voxel_data` on the grid that decides that chunk. **Can Edit Chunk** answers whether they do, so a build tool can switch itself off before the platform refuses an edit. **Get Grid Permissions** answers with the detail: every grid over the chunk and the player's own permission keys on each. Both need Application API v2.67.0, which every tier has. - The deciding grid is the smallest grid covering the chunk, the lower grid id when two are the same size. **Grid Id** names it, and **Can Edit** is true when the player holds `update_voxel_data` there. - A chunk no grid covers answers **Success** with **Can Edit** false and **Grid Id** 0: the platform refuses every edit there. - The answer is advice. It cannot see the player's access tier, which must also grant `update_voxel_data`, or a closed wilderness, which refuses a chunk that only the world grid covers. The platform still decides each edit, so keep handling a refused edit. - **Get Grid Permissions** lists the deciding grid first, then the rest by smallest box and lowest id. Each grid has its chunk box, the player's own unexpired permission keys, and **Decides Edits**, true on the deciding grid. Nobody else's keys are returned. `CheckPlot` asks about the workshop's chunk and lights the bench when the keeper may build there. It does nothing when the platform did not answer. ```cpp // LanternWorkshop.h #include "Subsystem/CrowdyClaims.h" UFUNCTION(BlueprintCallable, Category = "Lantern") void CheckPlot(); // LanternWorkshop.cpp #include "Subsystem/CrowdyVoxelLibrary.h" void ALanternWorkshop::CheckPlot() { int64 ChunkX = 0, ChunkY = 0, ChunkZ = 0; FIntVector Cell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), ChunkX, ChunkY, ChunkZ, Cell); TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->CanEditChunk(ChunkX, ChunkY, ChunkZ, [WeakThis](const FCrowdyChunkEditCheck& Check) { ALanternWorkshop* Self = WeakThis.Get(); if (!Self || Check.Result != ECrowdyClaimResult::Success) { return; } // Advice for the build tool: the platform still decides each edit. Self->Bench->SetVisibility(Check.bCanEdit); }); } ``` **CheckPlot** finds the workshop's chunk with **World To Voxel** and calls **Can Edit Chunk**. From **On Done**, **Set Visibility** on the **Bench** light takes **Can Edit**. Handle **On Failed** to learn why nothing was answered. [Blueprint snippet: claims-can-edit, see /bp/unreal-sdk/claims-can-edit.txt] ```cpp #include "Subsystem/CrowdyClaims.h" void AMyPlot::TryClaim() { UCrowdyClaims* Claims = GetGameInstance()->GetSubsystem(); TWeakObjectPtr WeakThis(this); Claims->ClaimChunk(ChunkX, ChunkY, ChunkZ, [WeakThis](const FCrowdyChunkClaim& Claim) { AMyPlot* Self = WeakThis.Get(); if (!Self) { return; } if (Claim.Result == ECrowdyClaimResult::Success) { Self->ShowOwned(Claim.GridId); return; } Self->ShowReason(Claim.Result, Claim.Message); }); } ``` Call **Claim Chunk** with the plot's chunk. From **On Done**, keep **Grid Id** and show the plot as the player's own. From **On Failed**, switch on **Result**: **Already Claimed** and **Not Claimable** both mean someone else holds it. ## What it costs - **Claim Chunk**, **Release Claim**, **Can Edit Chunk** and **Get Grid Permissions** are one request each. - **Find Claims** is one request for the box plus one per single-chunk grid in it. Nothing is cached, so each call asks again. # Mods Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/mods # Mods A mod is a player's own server code on a grid they own. It is a Rust crate that the platform builds from source and runs for that one grid. The platform's [mods page](/exec/mods) says how to write one. This page is the Unreal side: **Get Starter**, **Build Mod**, **Deploy Mod**, **Set Mod Enabled**, **List Mods**, **List My Mods**, **Call Mod**, **Get Mod Logs** and **Delete Mod** do each step from your game. ## What a mod is for A mod is the server rules a player puts on their own land. It keeps its own state across restarts, and any player can call it. So players can add mechanics to their plots without your game shipping new code: your game gives the owner a way to install a mod, and gives visitors a way to call it. Some mechanics a mod can carry: - **A guestbook or a visitor counter.** The mod counts who called it and remembers the last visitor, and the count survives restarts. This page builds one below. - **A plot that rebuilds or animates its own blocks**, such as a windmill that turns or a garden that grows. The mod writes its grid's blocks, for example on a timer. Its writes reach nearby players live, single cells as voxel updates and a whole chunk as one notice; a player who missed one sees it when the chunk is fetched or [reloaded](./voxel-chunks.md#reloading-a-chunk). - **A sign or a shop counter that answers from the plot's own data**: what is built there, who is standing there now, or a notice its owner keeps in the mod's state. - **A puzzle whose solution the server checks.** A visitor sends an attempt with **Call Mod**, the mod compares it with the answer it keeps, and only the mod opens the door by writing the blocks. The answer stays on the platform, so a modified client cannot fake a solve. A mod reads only its own grid's chunks, voxels and actors, and writes only that grid's blocks. It hears the grid's world events, such as actors moving and voxels changing. It cannot call your app's own server code or other mods, and only players call it. It runs as its owner, so it is not trusted game state like a [Server Object](../exec/overview.md): keep HP, inventory and anything a cheat would want in your game's own Server Objects. A player's land can be a chunk they own through a [chunk claim](./chunk-claims.md). ## What a player needs Every call is the signed-in player's own, made with their app token. Building needs the `write_server_code` permission in the app. Deploying and deleting need the grid and `write_server_code` on both the player's access tier and the grid. Switching a mod on or off needs the grid and `run_server_code` on both. Switching on also needs the app's code admission. The default access tier does not grant any of these: your app's developers do. The platform's [mods page](/exec/mods#who-may-do-what) has the full table. A call the player is not allowed to make answers **Denied**, and **Message** names the missing permission. ## The nodes They live on the **Crowdy Mods** subsystem (`UCrowdyMods`, a Game Instance subsystem), under **Crowdy SDK > Mods**. Your module needs `CrowdyServices` in its Build.cs. Each call is latent: **On Done** or **On Failed** fires once, on the game thread, never inside the call. Nothing is cached, so each call asks the platform again. | Blueprint | C++ | Does | |---|---|---| | **Get Starter** | `UCrowdyMods::GetStarter(TFunction OnDone)` | The platform's own starter crate: a **Name** and the **Files** to hand to **Build Mod**. | | **Build Mod** | `UCrowdyMods::BuildMod(const FString& CrateName, const TArray& Files, OnProgress, OnDone)` | Builds one crate and waits for it. **On Progress** fires on each status change, **On Done** once at the end. | | **Deploy Mod** | `UCrowdyMods::DeployMod(int64 GridId, const FString& Name, const FString& BuildId, OnDone)` | Puts a successful build on one of the player's grids under a name. A new mod starts switched off. | | **Set Mod Enabled** | `UCrowdyMods::SetModEnabled(int64 GridId, const FString& Name, bool bEnabled, OnDone)` | Switches a mod on or off. | | **List Mods** | `UCrowdyMods::ListMods(int64 GridId, OnDone)` | Every mod on one grid. | | **List My Mods** | `UCrowdyMods::ListMyMods(OnDone)` | The signed-in player's mods on every grid of the app. | | **Call Mod** | `UCrowdyMods::CallMod(int64 GridId, const FString& Name, const FString& Method, const FString& ParamsJson, OnDone)` | Calls one method of a mod with JSON parameters and answers its reply as JSON. | | **Get Mod Logs** | `UCrowdyMods::GetModLogs(int64 GridId, const FString& Name, int32 Limit, OnDone)` | A mod's latest log lines, oldest first, from the last 24 hours. **Limit** is 1 to 500, or 0 for 100. | | **Delete Mod** | `UCrowdyMods::DeleteMod(int64 GridId, const FString& Name, OnDone)` | Stops a mod and removes it, with its state and its versions. | | **Build Client Mod**, **Deploy Client Mod** | `UCrowdyMods::BuildClientMod(...)`, `UCrowdyMods::DeployClientMod(...)` | The same two steps for a mod's CLIENT half. No run lock, no pinned revision and no Allow Live Modding check. | | **Run Project**, **Get Project Status** | `UCrowdyMods::RunProject(...)`, `UCrowdyMods::GetProjectStatus(...)` | Build and deploy one revision of a Studio project, and read where each half is. See [Studio Dock](./studio-dock.md#run-a-project). | The player must be signed in to the app. Grid ids are 64-bit: keep them as Integer64 in Blueprint and `int64` in C++. Every build, deploy and read (**Build Mod**, **Deploy Mod**, **Set Mod Enabled**, **List Mods**, **List My Mods** and the Studio calls) needs Application API v2.73.0; an older one refuses it with `GRAPHQL_VALIDATION_FAILED`. ## Example: a guestbook on a plot The guestbook (`ALanternGuestbook`) stands on a plot its owner claimed. **Plot Grid Id** is the claimed chunk's grid, **Mod Name** is the mod's name on it, a sphere **Trigger** notices who walks in, and a Text Render component named **Sign** shows what the guestbook says. In Blueprint, give your actor an Integer64 variable named **PlotGridId** and a Text Render component named **Sign**. The platform's starter crate is a greeter, which makes it a ready guestbook. Its name is `grid-mod`, and it has two methods: - `visit` counts one visit, remembers the caller, and answers a JSON string: `"welcome to grid 7, visitor 3"`. - `state` answers a JSON object: `grid`, `visits`, `last_visitor` (that player's user id), counts of the world events it heard, and the chunk of the last one. The starter writes no blocks, so nothing here reloads a chunk. The owner installs the guestbook once and can switch it off. Visitors sign it, and anyone can read it. ### Install the guestbook Install from the owner's own menu or button, once. Never build on an overlap: a build takes about half a minute. **Get Starter** answers the starter's **Name**, which becomes the mod's name, and its **Files**. A crate is a list of files, each a **Path** and its **Content**: `Cargo.toml`, `README.md` and `.rs` files under `src/`, at most 64 files and 2 MB of source. Anything else answers **Refused** before a request is sent. **Build Mod** sends the crate and then reads its status every 2 seconds. It gives up after 11 minutes with **Failed**. A player has one build at a time. **On Progress** gives the status as it changes: **Queued**, **Building**, then **Succeeded** or **Failed**. :::caution A crate that does not compile is not an error. **Build Mod** ends with **Result** **Success** and **Status** **Failed**, and **Log** holds the compiler's output, at most 64 KB with the end kept. Check **Status** before you deploy. ::: **Deploy Mod** takes the **Build Id** from a successful build. The mod's name is 1 to 48 lowercase letters, digits, `-` or `_`; a grid holds at most 8 mods and a player at most 64. Deploying a new version of a running mod restarts it. **Set Mod Enabled** with **Enabled** true switches it on. Since Application API v2.66.0 a switched-on mod starts when a player is in its grid, so nothing needs to start it. A call starts it too, which covers the couple of minutes after a platform update in which a player's arrival may not. `InstallGuestbook` asks for the platform's starter and hands it to `BuildGuestbook`. `bBusy` lets one install, open or close run at a time, so a second press, or a close during a build, cannot be undone by a late answer. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Lantern") int64 PlotGridId = 0; // Visitors' games never run the install, so they call the mod by the name set on the placed actor. UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Lantern") FString ModName = TEXT("grid-mod"); UFUNCTION(BlueprintCallable, Category = "Lantern") void InstallGuestbook(); // The owner's install, open and close run one at a time, so a late answer never undoes a newer choice. bool bBusy = false; // LanternGuestbook.cpp void ALanternGuestbook::InstallGuestbook() { if (bBusy) { return; } bBusy = true; TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->GetStarter([WeakThis](const FCrowdyModStarter& Starter) { ALanternGuestbook* Self = WeakThis.Get(); if (!Self) { return; } if (Starter.Result != ECrowdyModResult::Success) { Self->EndStep(Starter.Message); return; } Self->BuildGuestbook(Starter); }); } ``` `BuildGuestbook` remembers the starter's name, builds its files, and shows each status on the sign. A build that did not succeed shows its compiler output, or the message when the call itself failed, and stops there. `EndStep` ends every step the same way: it frees the buttons and shows the outcome. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" // A mod's reply is its owner's text, so the sign shows at most this much of it. static constexpr int32 MaxSignChars = 200; void BuildGuestbook(const FCrowdyModStarter& Starter); // Ends the owner's step: frees the buttons and shows Text on the sign. void EndStep(const FString& Text); // LanternGuestbook.cpp void ALanternGuestbook::BuildGuestbook(const FCrowdyModStarter& Starter) { ModName = Starter.Name; TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->BuildMod(Starter.Name, Starter.Files, [WeakThis](const FCrowdyModBuild& Build) { ALanternGuestbook* Self = WeakThis.Get(); if (Self) { Self->Sign->SetText(FText::Format(INVTEXT("Building: {0}"), UEnum::GetDisplayValueAsText(Build.Status))); } }, [WeakThis](const FCrowdyModBuild& Build) { ALanternGuestbook* Self = WeakThis.Get(); if (!Self) { return; } // A crate that does not compile is a successful call with Status Failed, and its log says why. if (Build.Result != ECrowdyModResult::Success || Build.Status != ECrowdyModBuildStatus::Succeeded) { Self->EndStep(Build.Log.IsEmpty() ? Build.Message : Build.Log); return; } Self->DeployGuestbook(Build.BuildId); }); } void ALanternGuestbook::EndStep(const FString& Text) { bBusy = false; Sign->SetText(FText::FromString(Text.Left(MaxSignChars))); } ``` A successful build is deployed on the plot's grid, then switched on, and the sign invites visitors in. A refused deploy or switch shows the platform's reason, for example a grid the player cannot write server code to. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" void DeployGuestbook(const FString& BuildId); void SetGuestbookOpen(bool bOpen); // LanternGuestbook.cpp void ALanternGuestbook::DeployGuestbook(const FString& BuildId) { TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->DeployMod(PlotGridId, ModName, BuildId, [WeakThis](const FCrowdyModInfo& Info) { ALanternGuestbook* Self = WeakThis.Get(); if (!Self) { return; } if (Info.Result != ECrowdyModResult::Success) { Self->EndStep(Info.Message); return; } Self->SetGuestbookOpen(true); }); } void ALanternGuestbook::SetGuestbookOpen(bool bOpen) { TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->SetModEnabled(PlotGridId, ModName, bOpen, [WeakThis, bOpen](const FCrowdyModInfo& Info) { ALanternGuestbook* Self = WeakThis.Get(); if (!Self) { return; } if (Info.Result != ECrowdyModResult::Success) { Self->EndStep(Info.Message); return; } Self->EndStep(bOpen ? TEXT("Open: walk in to sign") : TEXT("Closed")); }); } ``` **InstallGuestbook** calls **Get Starter**, and **On Done** feeds **Name** and **Files** to **Build Mod**. From **On Done** of the build, a **Switch on ECrowdyModBuildStatus** sends only **Succeeded** on to **Deploy Mod**, which takes **PlotGridId**, the starter's **Name** and the build's **Build Id**. **On Done** of the deploy calls **Set Mod Enabled** with **Enabled** true. Wire **On Progress** of the build to the sign's **Set Text** to show the status, and **Failed** on the switch to show **Log**. Handle **On Failed** on each node, and keep a Boolean, as the C++ keeps `bBusy`, so a second press does nothing while an install runs. [Blueprint snippet: mods-install, see /bp/unreal-sdk/mods-install.txt] ### Sign it when a visitor walks in A visitor's game calls the mod. It never ran the install, so it knows the grid and the name from the placed guestbook: **Plot Grid Id**, and **Mod Name**, which is `grid-mod` for the starter. **Call Mod** names the grid, the mod and a method, and sends **Params Json** as the method's argument; an empty **Params Json** sends `{}`. **Reply Json** holds whatever the method returns, as JSON. A string comes back with its quotes, so read it with a JSON reader before you show it. A switched-off mod answers **Denied**, and a deleted one answers **Not Found**. A mod the app has not admitted stays not running even when it is switched on: [list it](#list-mods-and-read-their-logs) to see whether it runs. The overlap signs only for this player's own pawn: in a standalone game an AI controller counts as local too, so it also asks **Is Player Controlled**. `bSigned` makes it sign once, so each visitor is counted once, by their own game; a failed call clears it, so the next visit tries again. ```cpp // LanternGuestbook.h virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; // LanternGuestbook.cpp #include "GameFramework/Pawn.h" void ALanternGuestbook::NotifyActorBeginOverlap(AActor* OtherActor) { Super::NotifyActorBeginOverlap(OtherActor); // In a standalone game an AI controller is local too, so ask for this player's own pawn. const APawn* Pawn = Cast(OtherActor); if (!Pawn || !Pawn->IsLocallyControlled() || !Pawn->IsPlayerControlled()) { return; } SignGuestbook(); } ``` `SignGuestbook` calls `visit` and puts the welcome on the sign. The reply is the plot owner's text, so the sign shows at most `MaxSignChars` of it. Unreal's JSON reader wants an object or an array at the root, so the string reply is read inside an array. A **Denied** answer means the guestbook is switched off, by its owner or by billing. Reading JSON needs `Json` in your module's Build.cs. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" // A mod's reply is its owner's text, so the sign shows at most this much of it. static constexpr int32 MaxSignChars = 200; UFUNCTION(BlueprintCallable, Category = "Lantern") void SignGuestbook(); // Set once this player has signed, so a visitor is counted once however often they walk in. bool bSigned = false; // LanternGuestbook.cpp #include "Serialization/JsonSerializer.h" void ALanternGuestbook::SignGuestbook() { if (bSigned) { return; } bSigned = true; TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->CallMod(PlotGridId, ModName, TEXT("visit"), TEXT("{}"), [WeakThis](const FCrowdyModCall& Call) { ALanternGuestbook* Self = WeakThis.Get(); if (!Self) { return; } if (Call.Result != ECrowdyModResult::Success) { // Not counted, so the next visit tries again. Self->bSigned = false; Self->Sign->SetText(Call.Result == ECrowdyModResult::Denied ? INVTEXT("Closed") : FText::FromString(Call.Message.Left(MaxSignChars))); return; } // The reply is a JSON string; Unreal's reader needs an array or object at the root, so wrap it in one. TArray> Reply; FString Welcome; if (FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(TEXT("[") + Call.ReplyJson + TEXT("]")), Reply) && Reply.Num() == 1 && Reply[0]->TryGetString(Welcome)) { Self->Sign->SetText(FText::FromString(Welcome.Left(MaxSignChars))); } }); } ``` **SignGuestbook** calls **Call Mod** with **PlotGridId**, **Name** `grid-mod`, **Method** `visit` and **Params Json** `{}`, and **On Done** sets the sign's text to the first 200 characters of **Reply Json**, through **Left**. Call it from **Event ActorBeginOverlap** after a **Cast To Pawn**, **Is Locally Controlled** and **Is Player Controlled**, as the C++ does. The SDK has no Blueprint node that reads JSON, so the sign shows the reply as the mod sent it, quotes included: `"welcome to grid 7, visitor 3"`. Read it in C++ to drop them. **On Failed** with **Result** **Denied** means the guestbook is closed. [Blueprint snippet: mods-visit, see /bp/unreal-sdk/mods-visit.txt] ### Show the owner who came `state` answers the guestbook's whole state, and anyone may call it. `ShowGuestbook` reads `visits` and `last_visitor` from the object and shows them on the sign. A user id is 64-bit, so the reply is read with its numbers kept as written; read as a double, a large id would lose its last digits. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" UFUNCTION(BlueprintCallable, Category = "Lantern") void ShowGuestbook(); // LanternGuestbook.cpp #include "Serialization/JsonSerializer.h" void ALanternGuestbook::ShowGuestbook() { TWeakObjectPtr WeakThis(this); GetGameInstance()->GetSubsystem()->CallMod(PlotGridId, ModName, TEXT("state"), TEXT("{}"), [WeakThis](const FCrowdyModCall& Call) { ALanternGuestbook* Self = WeakThis.Get(); TSharedPtr State; // Numbers are kept as written, so a 64-bit user id reads back exactly. if (!Self || Call.Result != ECrowdyModResult::Success || !FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Call.ReplyJson), State, FJsonSerializer::EFlags::StoreNumbersAsStrings)) { return; } int64 Visits = 0; int64 LastVisitor = 0; State->TryGetNumberField(TEXT("visits"), Visits); State->TryGetNumberField(TEXT("last_visitor"), LastVisitor); Self->Sign->SetText(FText::FromString(FString::Printf(TEXT("%lld visits; last visitor %lld"), Visits, LastVisitor))); }); } ``` In Blueprint, **Call Mod** with **Method** `state` answers the same object as text in **Reply Json**. Show it as it is, or read it in C++. ### Close the guestbook **Set Mod Enabled** with **Enabled** false switches the mod off. While it is off, a visitor's **Call Mod** answers **Denied**, and `SignGuestbook` above shows the guestbook closed. `OpenGuestbook` switches it on again. Both wait for an install still running. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyMods.h" UFUNCTION(BlueprintCallable, Category = "Lantern") void CloseGuestbook(); UFUNCTION(BlueprintCallable, Category = "Lantern") void OpenGuestbook(); // LanternGuestbook.cpp void ALanternGuestbook::CloseGuestbook() { if (bBusy) { return; } bBusy = true; SetGuestbookOpen(false); } void ALanternGuestbook::OpenGuestbook() { if (bBusy) { return; } bBusy = true; SetGuestbookOpen(true); } ``` In Blueprint, it is one **Set Mod Enabled** node with **PlotGridId**, the mod's name and **Enabled** false. ## List mods and read their logs **List Mods** and **List My Mods** answer **Mods**, an array of **Crowdy Mod**. Each has: | Field | Is | |---|---| | **Mod Id**, **Name**, **Grid Id**, **Owner User Id** | Which mod it is and whose. | | **Version**, **Digest** | The deployed version, and the SHA-256 of its module in hex. | | **Enabled** | Its owner switched it on. It runs only while this holds and it is not blocked. | | **Running** | An instance of it runs now. A switched-on mod that is not running starts on a player's arrival in its grid or on a call. | | **Blocked**, **Blocked Reason** | A switch such as billing's has stopped it, whatever **Enabled** says. The reason says which. | | **Updated At Ms** | Unix time in milliseconds. | | **Studio Project Id**, **Studio Revision** | The [Studio project](./studio-dock.md#studio-projects) and revision this version was built from. Empty when its build named none, as an install's does. | **Get Mod Logs** answers **Lines**: each has **At Ms**, a **Level** (0 error, 1 warning, 2 info, 3 debug) and the **Text**. When a call fails or a mod does not do what you expect, read its logs first. ## What each result means | Result | Means | |---|---| | **Success** | Done. For **Build Mod** it means the build ran to an end; read **Status**. | | **Not Signed In** | The player has no app token yet. Nothing was sent. | | **Denied** | A missing permission, a grid that is not the player's, or a billing switch such as an empty wallet or a spend cap. **Message** names which. A switched-off mod answers **Denied** to a call. | | **Not Found** | No such mod, build or grid. A deleted mod answers this to a call. | | **Refused** | Any other refusal: a name that is not allowed, a limit reached, or a crate this SDK rejects before sending. | | **Failed** | The request did not complete, or a build did not finish in 11 minutes. | | **Bad Reply** | The answer was malformed, so nothing from it is returned. | | **Busy** | Another run for this app is still going, or the platform is already building one for this player: a build the platform refuses for that reason answers **Busy**. Try again once it ends. | | **Revision Changed** | A Studio project's saved revision or module names are not the ones **Run Project** was asked for, so nothing was built. | | **Not Built** | This SDK version does not carry the call yet, so nothing was sent. | In Blueprint the nodes report a result other than **Success** on **On Failed**, with **Result** and **Message**. ## What a mod costs A mod bills its owner's player wallet once their monthly trial is used up, not your app, and an empty wallet or a spend cap switches the owner's mods off, which shows as **Blocked** (see [Who pays for a mod](/exec/mods#who-pays-for-a-mod)). Each call is one request, except **Build Mod**, which is one request to send the crate and one every 2 seconds to read its status. ## From C++ Every callback runs once on the game thread, unless the game instance ends first. `UCrowdyMods` has fixed limits as constants: `MaxFiles` (64), `MaxSourceBytes` (2 MB), `BuildPollSeconds` (2), `BuildLimitSeconds` (11 minutes), `MaxLogLines` (500) and `DefaultLogLines` (100). The types behind the nodes: | Type | Is | |---|---| | `ECrowdyModResult` | `Success`, `NotSignedIn`, `Denied`, `NotFound`, `Refused`, `Failed`, `BadReply`, `Busy`, `RevisionChanged`, `NotBuilt`. Values are only added at the end. | | `ECrowdyModBuildStatus` | `Queued`, `Building`, `Succeeded`, `Failed`. | | `FCrowdyModFile` | `Path` and `Content` of one source file. | | `FCrowdyModStarter` | `Result`, `Name`, `Files` and `Message`, and `bNotServed` (C++ only) when the platform serves no such starter. `GetClientStarter(OnDone)`, C++ only, answers the platform's client half starter the same way. | | `FCrowdyModBuild` | `Result`, `BuildId`, `Status`, `Log`, `SdkVersion` (the version it compiled against, once it started) and `Message`. | | `FCrowdyMod` | One mod: `ModId`, `GridId`, `OwnerUserId`, `Name`, `Version`, `Digest`, `bEnabled`, `bRunning`, `bBlocked`, `BlockedReason`, `UpdatedAtMs`, `StudioProjectId` and `StudioRevision`. | | `FCrowdyModInfo` | `Result`, `Mod` and `Message`: the answer to deploying and switching. | | `FCrowdyModList` | `Result`, `Mods` and `Message`. | | `FCrowdyModLogs`, `FCrowdyModLogLine` | `Result`, `Lines` and `Message`; a line is `AtMs`, `Level` and `Text`. | | `FCrowdyModDelete` | `Result`, `bDeleted` and `Message`. | | `FCrowdyModCall` | `Result`, `ReplyJson` and `Message`. `ReplyJson` is the mod's answer as JSON text, empty unless `Result` is `Success`. | | `UCrowdyGetModStarter`, `UCrowdyBuildMod`, `UCrowdyDeployMod`, `UCrowdySetModEnabled`, `UCrowdyListMods`, `UCrowdyListMyMods`, `UCrowdyGetModLogs`, `UCrowdyDeleteMod`, `UCrowdyCallMod` | The nodes. C++ calls the subsystem instead. | | `FCrowdyModBuildAsyncResult`, `FCrowdyModStarterAsyncResult`, `FCrowdyModInfoAsyncResult`, `FCrowdyModListAsyncResult`, `FCrowdyModLogsAsyncResult`, `FCrowdyModDeleteAsyncResult`, `FCrowdyModCallAsyncResult` | The delegate types of the nodes' pins. | # Mod Scripts Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/mod-scripts # Mod Scripts A [mod](./mods.md) runs on the platform's servers. A Mod Script is the other half of the same mod: Rust that the platform builds to WebAssembly, and that a player standing in the mod's grid runs on their own machine, inside your game, once they agree. The platform's [client halves page](/exec/client-halves) says how to write one. This page is the Unreal side: **Enter Grid**, **Leave Grid**, **Set Host**, **On Mod Script Prompt** and **Answer Prompt** wire it into your game. ## Plan what a plot's script shows A Mod Script is how a plot's owner shows something to the visitors of the plot. The script can: - Show text on a mod HUD. - Draw shapes that only this player sees. - Read the player's mouse clicks. - Read the grid's chunks and the players in it. - Write a voxel as this player. - Keep and read the player's own app state. - Send events to other scripts on this machine. - Send spatial client events from inside the grid, up to 8 chunks. - Post to the grid's own channels. A script reads and writes only inside its grid, and it never acts as anyone but the player who runs it. It runs only on Win64: **Is Available** is false on every other platform. The SDK runs it on background threads with a fuel limit, a watchdog, 32 MiB of memory and per-second call caps. A script whose start, tick or event fails five times in a row, for example by running out of fuel, or that makes more than 1,000 host calls in one second, is stopped and tried again 60 seconds later. A Mod Script is code from another player, running on your player's machine. The player is asked before it runs, and your game answers each call that touches the world or the screen, so your game decides what a script may do there. ## Wire Mod Scripts into your game Your game does two things. It tells the SDK where the player is and asks the player, through the **Crowdy Mod Scripts** subsystem (`UCrowdyModScripts`, a world subsystem, under **Crowdy SDK > Mod Scripts**). And it answers the calls only it can, by setting an object that implements **Crowdy Mod Script Host** (`ICrowdyModScriptHost`). Your module needs `CrowdyServices` in its Build.cs. | Blueprint | C++ | Does | |---|---|---| | **Is Available** | `UCrowdyModScripts::IsAvailable()` | Whether this build can run scripts: Win64 only. | | **Enter Grid** | `EnterGrid(int64 ChunkX, int64 ChunkY, int64 ChunkZ)` | The local player stands in this chunk. The SDK asks the platform which grid decides it and what box it covers. Does nothing when **Is Available** is false. | | **Leave Grid** | `LeaveGrid()` | The player left the grid. Every script of it stops. | | **Get Grid** | `GetGrid()` | The grid the scripts run in, with its box in chunks. Empty outside a grid. | | **Set Host** | `SetHost(TScriptInterface)` | Sets the object that answers the host calls. | | **Clear Host** | `ClearHost(Host)` | Clears the host, only if it is the one set. | | **Answer Prompt** | `AnswerPrompt(int32 PromptId, bool bRun)` | Answers a prompt: run the author's scripts or not. | | **Get Running** | `GetRunning()` | The scripts running now. | | **Revoke** | `Revoke(const FString& ModId)` | Stops one script and takes back the player's agreement to it, and the player's trust in its author on the grid. The author's scripts running now keep running; the rest wait for a new yes. | | **Forget Author** | `ForgetAuthor(int64 AuthorId)` | Stops all of the author's scripts on this grid and takes back the player's trust in the author. Does nothing outside a grid. | | **Get Script Status** | `GetScriptStatus(int64 GridId, OnDone)` | Where each of the grid's scripts is. See [Read a script's status and log](#read-a-scripts-status-and-log). | | **Get Script Log** | `GetScriptLog(int64 GridId, const FString& ModId, OnDone)` | A script's last log lines, oldest first, from memory. | The SDK takes the grid from the platform, never from your call: you pass only the chunk the player stands in. Leaving the grid, signing out, travelling and the world ending stop every script. ## Host the scripts The host answers the calls a script makes that only your game can answer. The SDK calls each event on the game thread, with values it has already checked against the grid, the player's agreement and the call's limits. It never passes the script's JSON. A Blueprint shows each one as **Event ShowHud**, **Event DrawOverlay** and so on. | Event | Does | |---|---| | **Show Hud** `(Script, Text)` | Shows the script's text. At most 8 lines and 500 characters; empty text clears it. | | **Draw Overlay** `(Script, Shapes)` | Replaces the shapes the script draws for this player: at most 64. Positions are in voxel units from the world origin, inside the grid. An empty array clears them. | | **Read Chunk** `(ChunkX, ChunkY, ChunkZ, Chunk)` | Fills `Chunk` with the 4,096 voxel types (index x + 16y + 256z) and returns true, or returns false when the chunk is not loaded. | | **List Players** `(Box, Players)` | Fills `Players` with the players in the box, you included. At most 64, and names past 64 characters are cut. | | **Drain Clicks** `(Clicks)` | Fills `Clicks` with the clicks since the last call. The SDK calls it once a frame while a host is set, and keeps the newest 64 for each script. | | **Set Voxel** `(Script, Write, Refusal)` | Returns true when the write went into the voxel world's queue. Otherwise returns false and sets `Refusal`. | | **Clear Script** `(Script)` | Removes what that script showed. Also called for every running script when the host is replaced. | Each one answers from what your game already holds, never by waiting on the network. Hand back a plain copy of what the voxel world holds: the SDK cannot stop one slow answer in the middle of a frame. With no host set, the world and input calls are refused, and **Show Hud** and **Draw Overlay** answer that nothing was delivered. **Set Voxel** needs no rate limit of your own: the SDK already holds scripts to 100 writes a second and answers busy at 64 unsent edits. The guestbook (`ALanternGuestbook`) is an actor on a plot that has a mod with a Mod Script. It implements the host interface, shows the script's text on its sign, and in `BeginPlay` sets itself as the host and binds the prompt. A world has one host and **Leave Grid** stops every script, so the guestbook assumes it is the only one in the level; a game with several plots sets the host once, from its player controller for example, and leaves the grid when the player's chunk is outside **Get Grid**'s box. `ALanternGuestbook` inherits `ICrowdyModScriptHost`. Its `BeginPlay` sets it as the host of the world's `UCrowdyModScripts` and binds `OnModScriptPrompt`. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyModScripts.h" #include "Subsystem/CrowdyModScriptHost.h" class ALanternGuestbook : public AActor, public ICrowdyModScriptHost { virtual void BeginPlay() override; // LanternGuestbook.cpp void ALanternGuestbook::BeginPlay() { Super::BeginPlay(); UCrowdyModScripts* Scripts = GetWorld()->GetSubsystem(); Scripts->SetHost(TScriptInterface(this)); Scripts->OnModScriptPrompt.AddDynamic(this, &ALanternGuestbook::AnswerPlotPrompt); OnActorBeginOverlap.AddDynamic(this, &ALanternGuestbook::EnterPlot); OnActorEndOverlap.AddDynamic(this, &ALanternGuestbook::LeavePlot); } ``` Open the guestbook Blueprint's **Class Settings** and, under **Interfaces**, use **Implemented Interfaces > Add** to add **Crowdy Mod Script Host**. ![A Blueprint's Class Settings: Implemented Interfaces, under Interfaces, is where Crowdy Mod Script Host is added](/img/unreal-sdk/modscripts-interface.png) In **Event BeginPlay**, a **Crowdy Mod Scripts** getter feeds **Set Host** with **Self**, then **Bind Event to On Mod Script Prompt** to a custom event `OnModScriptPrompt`. The interface's events appear under **Interfaces** in **My Blueprint**: the rest of this page fills in the ones the guestbook needs. [Blueprint snippet: modscripts-host, see /bp/unreal-sdk/modscripts-host.txt] ## Enter and leave a grid **Enter Grid** takes the chunk the local player stands in. Call it when the player walks onto the plot, and **Leave Grid** when they walk off. The SDK looks the chunk up once: naming the same chunk every frame asks once. A failed lookup, for example before sign-in, is asked again only when **Enter Grid** names that chunk 2 seconds or more later, so keep calling it as the player moves rather than once per walk-in. While the player stands in the grid the SDK lists its scripts again every 10 seconds, so a script the owner adds shows up without a second **Enter Grid**. The guestbook's trigger does this. It reacts only to the local player's own pawn, so another player walking in does nothing here. The overlap checks that the pawn is the local player's, and that it is player controlled, then enters the grid of the chunk the guestbook stands in. The end of the overlap leaves it. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyModScripts.h" UFUNCTION() void EnterPlot(AActor* PlotActor, AActor* OtherActor); UFUNCTION() void LeavePlot(AActor* PlotActor, AActor* OtherActor); // LanternGuestbook.cpp #include "Subsystem/CrowdyVoxelLibrary.h" static bool IsLocalPlayerPawn(const AActor* Actor) { const APawn* Pawn = Cast(Actor); return Pawn && Pawn->IsLocallyControlled() && Pawn->IsPlayerControlled(); } void ALanternGuestbook::EnterPlot(AActor* PlotActor, AActor* OtherActor) { if (!IsLocalPlayerPawn(OtherActor)) { return; } int64 ChunkX = 0, ChunkY = 0, ChunkZ = 0; FIntVector Cell; UCrowdyVoxelLibrary::WorldToVoxel(this, GetActorLocation(), ChunkX, ChunkY, ChunkZ, Cell); GetWorld()->GetSubsystem()->EnterGrid(ChunkX, ChunkY, ChunkZ); } void ALanternGuestbook::LeavePlot(AActor* PlotActor, AActor* OtherActor) { if (!IsLocalPlayerPawn(OtherActor)) { return; } GetWorld()->GetSubsystem()->LeaveGrid(); } ``` **Event ActorBeginOverlap** turns the guestbook's location into a chunk with **World to Voxel** and calls **Enter Grid** on the **Crowdy Mod Scripts** getter. **Event ActorEndOverlap** calls **Leave Grid**. These graphs leave out the check that the pawn is the local player's: put a **Cast To Pawn**, **Is Locally Controlled** and **Is Player Controlled** in front, as the C++ tab does, when other players or AI walk past too. [Blueprint snippet: modscripts-enter, see /bp/unreal-sdk/modscripts-enter.txt] [Blueprint snippet: modscripts-leave, see /bp/unreal-sdk/modscripts-leave.txt] ## Ask the player A player's scripts do not run until the player says yes. **On Mod Script Prompt** fires for each author whose scripts the player has not agreed to, each time the player enters the grid and again when the calls those scripts make change. The prompt holds: | Field | Is | |---|---| | **Prompt Id** | The id to hand to **Answer Prompt**. | | **Grid Id**, **Author Id** | The grid, and its owner, who wrote the scripts. | | **Scripts** | The names of the scripts a yes runs. | | **Calls** | Every call those scripts make. | | **Groups** | The calls in groups for a short question: State, World Read, World Write, Meta, Egress, Present and Input. | | **Not Offered** | The calls the scripts ask for that your game refuses. With no host set when the prompt fires, the world and input calls are listed here too: set the host first. | Show the player who is asking and what for, then call **Answer Prompt** with **Run**. **Run** true trusts the author on this grid for those calls. **Run** false declines for as long as the player stays in the grid: they are asked again the next time they enter it, or sooner if the scripts' calls change. If the prompt goes stale, for example because the player left, **On Mod Script Prompt Withdrawn** fires with its id: close your question. A prompt is your game's own user interface. The guestbook skips the dialog: a **Run Plot Scripts** setting on it decides the answer. In C++ its sign also says what was asked. The handler writes the question on the sign, how many scripts the plot's owner asks to run, and answers it from the guestbook's **Run Plot Scripts** setting. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyModScripts.h" // Whether to say yes when the plot's scripts ask to run; a real game shows the player the question. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Lantern") bool bRunPlotScripts = true; UFUNCTION() void AnswerPlotPrompt(const FCrowdyModScriptPrompt& Prompt); // LanternGuestbook.cpp void ALanternGuestbook::AnswerPlotPrompt(const FCrowdyModScriptPrompt& Prompt) { Sign->SetText(FText::Format(INVTEXT("Run {0} scripts by this plot's owner?"), Prompt.Scripts.Num())); GetWorld()->GetSubsystem()->AnswerPrompt(Prompt.PromptId, bRunPlotScripts); } ``` The custom event `OnModScriptPrompt` has a **Prompt** pin. **Break Crowdy Mod Script Prompt** gives its **Prompt Id**, and **Answer Prompt** takes it with the guestbook's **Run Plot Scripts**. The same break gives **Author Id**, **Scripts** and **Calls** for the question your game shows. [Blueprint snippet: modscripts-prompt, see /bp/unreal-sdk/modscripts-prompt.txt] A yes is kept: the next time the player enters this author's grid, the scripts start with no question. Take it back with **Revoke** for one script, or **Forget Author** for all of the author's scripts on the grid. A refusal from the platform, such as a revoke it would not take, arrives on **On Mod Script Error** with a **Mod Id**, a **Code** and a **Message**, and the script it was for stops as **Unconsented** until the player enters the grid again. ## Show what a script says **On Mod Script Started** fires when a script starts, and **On Mod Script Stopped** when it stops, each with the script: its **Mod Id**, **Name**, **Author Id**, **Grid Id**, **Version**, the **Calls** it may make, and its **Digest**, the SHA-256 of the module it runs (64 lowercase hex digits; the SDK runs no bytes that hash to anything else), so your game can show which build is running. **On Mod Script Stopped** also carries why it stopped, in the table below. A script that fails to start fires **On Mod Script Stopped** with **Failed** and no **On Mod Script Started** before it. The guestbook's script writes who signed lately. **Show Hud** puts that text on the sign, and **Clear Script** takes it down when the script stops. The guestbook's `ShowHud` puts the text on the sign. Its `ClearScript` clears it, so a stopped script leaves no text behind. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyModScriptHost.h" // What the guestbook says to whoever stands at the plot. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Lantern") TObjectPtr Sign; // A mod's reply is its owner's text, so the sign shows at most this much of it. static constexpr int32 MaxSignChars = 200; virtual void ShowHud_Implementation(const FCrowdyModScript& Script, const FString& Text) override; virtual void ClearScript_Implementation(const FCrowdyModScript& Script) override; // LanternGuestbook.cpp void ALanternGuestbook::ShowHud_Implementation(const FCrowdyModScript& Script, const FString& Text) { Sign->SetText(FText::FromString(Text.Left(MaxSignChars))); } void ALanternGuestbook::ClearScript_Implementation(const FCrowdyModScript& Script) { Sign->SetText(FText::GetEmpty()); } ``` A C++ host overrides the events it answers; one it leaves alone answers nothing. The guestbook spells the other five out anyway: no clicks, no chunk, no players, no voxel write and no shapes. ```cpp // LanternGuestbook.h #include "Subsystem/CrowdyModScriptHost.h" virtual void DrainClicks_Implementation(FCrowdyModScriptClicks& Clicks) override {} virtual bool ReadChunk_Implementation(int64 ChunkX, int64 ChunkY, int64 ChunkZ, FCrowdyModScriptChunk& Chunk) override { return false; } virtual void ListPlayers_Implementation(const FCrowdyModScriptGrid& Box, TArray& Players) override {} virtual bool SetVoxel_Implementation(const FCrowdyModScript& Script, const FCrowdyVoxelWrite& Write, FString& Refusal) override { Refusal = TEXT("The guestbook does not edit voxels"); return false; } virtual void DrawOverlay_Implementation(const FCrowdyModScript& Script, const TArray& Shapes) override {} ``` Add **Event ShowHud** from the interface: it sets the sign's text to the first 200 characters of **Text**. Add **Event ClearScript**: it sets the sign's text to an empty text. [Blueprint snippet: modscripts-hud, see /bp/unreal-sdk/modscripts-hud.txt] [Blueprint snippet: modscripts-clear, see /bp/unreal-sdk/modscripts-clear.txt] A script that is stopped and that comes back, for example after a change of code, runs under a new **Generation**. A host that keeps what each script showed keys it by **Mod Id**, and stops showing it on **Clear Script**. ## Check which calls your game answers A script names each call it makes, and the SDK answers it or refuses it: | Call | Answered by | |---|---| | `grid_info`, `clock`, `emit_event`, `grid_permission_check` | The SDK alone. | | `user_state_get`, `user_state_set`, `emit_spatial`, `emit_channel` | The SDK, through the platform, as the player. | | `pointer_clicks`, `chunk_get`, `voxels_list`, `actors_list`, `actors_list_radius`, `voxel_set`, `hud_set`, `overlay_draw` | Your host. | `emit_spatial` sends only the `client_event` and `server_event` kinds: an actor or text send is refused. `emit_channel` posts only to the grid's own channels, at most 1,024 bytes. `grid_permission_check` answers the four code permissions, for the local player only. Any other call, such as `avatar_state_get` or `emit_event_to`, a script makes is refused as not offered, and a script that asks for one shows it in **Not Offered** on the prompt. ## Read a script's status and log A dock or a debug panel can ask where the grid's scripts are. Both calls answer once on the game thread, never inside the call, and answer **Not In Grid** unless the grid id is the one the player stands in. They answer **Failed** when the Mod Script runtime is not running. In C++ the callback runs even after the world ends, so capture weakly. **Get Script Status** answers **Scripts**, every script the grid lists, agreed to or not. Each has the **Script**, a **State** (**Running**, **Stopped**, **Erred** or **Circuit Open**), a **Stop Reason** that means something only when **State** is **Stopped** (the table below), and a **Message**. **Get Script Log** takes a grid id and a **Mod Id** and answers the script's last 200 log lines, oldest first: each has **At Ms**, a **Level** (0 error, 1 warning, 2 info, 3 debug) and the **Text**. The lines are kept in memory only, never saved, and they outlive each run of the script, so a crash's last lines stay readable. **Dropped Lines** counts the lines lost before the read: those the script logged too fast to keep and those that fell out of the 200. The answer also names the script (**Name**) and its author (**Author Id**). :::caution[A script's log lines are its author's text.] A reader that passes them on, such as to a model, should read only the logs of authors it trusts. ::: Reading the log through this call does not put the lines in the game's log: that is what `crowdy.modscripts.trace 1` does, as described below. ## Read why a script stopped | Reason | Means | |---|---| | **Removed** | The grid no longer serves the script, or listing the grid's scripts was refused or failed three times in a row. | | **Changed** | Its code, permissions or tick changed. It is asked about again only when its calls changed; otherwise it restarts. | | **Unconsented** | The player took their agreement back somewhere else, or the platform refused an agreement call. | | **Revoked** | The player took it back here, through **Revoke** or **Forget Author**. | | **Left Grid** | The player left its grid. | | **Stopped** | Sign-out, a change of player, travel or the world ending. | | **Circuit Open** | Its start, tick or event failed five times in a row, for example out of fuel, or it made more than 1,000 host calls in one second. It starts again after 60 seconds. | | **Failed** | Fetching, checking or starting it failed. It is tried again later while the player stays in the grid. | A script's own log lines are its author's text, so they stay out of the game's log. To read them while you test a plot, run `crowdy.modscripts.trace 1` in the console: each kept line (up to 20 a second per script, cut at 1,000 characters) then appears under `LogCrowdyModScripts` with the script's name, along with a count of the lines dropped over that limit. :::warning[Install the host before the player enters a grid.] A script that starts with no host set cannot read the world or show anything: its world and input calls are refused and its HUD and overlay calls answer delivered false. Set the host in `BeginPlay`, before the first **Enter Grid**. ::: :::caution[Answer a host call from state you already hold.] A host event runs on the game thread inside the frame. Read the chunk you already loaded, copy it, and return. A call that waits on the network or a disk freezes the game. ::: :::caution[Ship the Wasmtime notices with every Win64 game.] The runtime that runs scripts is Wasmtime, under Apache-2.0 with the LLVM exception. Every Win64 build of the plugin links it, whether or not your game uses Mod Scripts, so ship its licence and notices in your game's notices: `Plugins/CrowdySDK/Source/CrowdyModScriptRuntime/ThirdParty/Wasmtime/LICENSE` and `THIRD-PARTY-NOTICES.txt`. ::: ## Use the types from C++ Every event and delegate fires on the game thread. `UCrowdyModScripts::ListSeconds` (10) is how often the grid's scripts are listed again. The types behind the nodes: | Type | Is | |---|---| | `UCrowdyModScripts` | The world subsystem. | | `ICrowdyModScriptHost`, `UCrowdyModScriptHost` | The host interface, and its `UInterface`. Its methods `ShowHud`, `DrawOverlay`, `ReadChunk`, `ListPlayers`, `DrainClicks`, `SetVoxel` and `ClearScript` are each a `BlueprintNativeEvent`: a C++ host overrides `ShowHud_Implementation` and the rest, and the SDK calls them through `Execute_ShowHud` and so on. | | `FCrowdyModScriptGrid` | `GridId` and the box in chunks: `LowChunkX`, `LowChunkY`, `LowChunkZ`, `HighChunkX`, `HighChunkY`, `HighChunkZ`. | | `FCrowdyModScript` | A running script: `ModId`, `Name`, `AuthorId`, `GridId`, `Version`, `Generation`, `Calls` and `Digest`. | | `UCrowdyGetScriptStatus`, `UCrowdyGetScriptLog`, `FCrowdyModScriptStatusAsyncResult`, `FCrowdyModScriptLogAsyncResult` | The two read nodes and the delegate types of their pins. | | `FCrowdyModScriptStatusList`, `FCrowdyModScriptStatus`, `FCrowdyModScriptLog`, `FCrowdyModScriptLogLine` | The answers to the two reads. `FCrowdyModScriptStatusList` has `Result`, `GridId`, `Scripts` and `Message`; a status is `Script`, `State`, `StopReason` and `Message`. A log has `Result`, `ModId`, `Name`, `AuthorId`, `Lines`, `DroppedLines` and `Message`; a line is `AtMs`, `Level` and `Text`. | | `ECrowdyModScriptReadResult`, `ECrowdyModScriptState` | `Success`, `NotInGrid`, `Failed`, `NotBuilt`; and `Running`, `Stopped`, `Erred`, `CircuitOpen`. | | `FCrowdyModScriptPrompt` | `PromptId`, `GridId`, `AuthorId`, `Scripts`, `Calls`, `Groups` and `NotOffered`. | | `FCrowdyModScriptError` | `ModId`, `Code` and `Message`. | | `ECrowdyModScriptGroup` | `State`, `WorldRead`, `WorldWrite`, `Meta`, `Egress`, `Present`, `Input`. | | `ECrowdyModScriptStop` | `Removed`, `Changed`, `Unconsented`, `Revoked`, `LeftGrid`, `Stopped`, `CircuitOpen`, `Failed`. | | `FCrowdyModScriptClicks`, `FCrowdyModScriptClick` | The clicks since the last drain. `Buttons`, the buttons held now as a mask (1 left, 2 right, 4 middle), and the held times. Each click has `bDown`, `Button` (0 left, 1 middle, 2 right: not the mask's values), `AtMs` in Unix milliseconds, `HeldMs` on a release only, and `X`, `Y`, which run from -1 to 1 across the game viewport, +Y up. | | `FCrowdyModScriptChunk`, `FCrowdyModScriptCellState` | `Types` (4,096) and `States`: a cell's `X`, `Y`, `Z` and its state in base64. | | `FCrowdyModScriptPlayer` | `ActorId` (32 hex digits), `bSelf`, `Name`, `Location` in voxels, `Yaw`, `Pitch` in degrees and `Program`. | | `FCrowdyModScriptShape`, `ECrowdyModScriptShapeKind` | `Id` (at most 32 characters, unique in its script), `Kind` (`Box`, `Sphere`, `Cylinder`, `Capsule`, `Plane`), `Location`, `Rotation`, `Size` (0.04 to 8 voxels on each axis), `Color`, `Opacity`, `bVisible` and `bUnlit`. | | `FOnCrowdyModScriptPrompt`, `FOnCrowdyModScriptPromptWithdrawn`, `FOnCrowdyModScriptStarted`, `FOnCrowdyModScriptStopped`, `FOnCrowdyModScriptError` | The delegate types of the subsystem's events. | # Studio Dock Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/studio-dock # Studio Dock A Studio dock is a panel in your game where a player works on their own [mods](./mods.md) and [Mod Scripts](./mod-scripts.md) with the Studio agent: they pick a project, the agent edits it, and the player runs it on their grid. This page is the platform side of such a dock. Your game draws the panel and hosts the agent's page. The SDK makes the calls, and each one answers or refuses plainly. Every call is the signed-in player's own, made with their app token, and nothing is cached. Each is latent: **On Done** or **On Failed** fires once, on the game thread, never inside the call. Your module needs `CrowdyServices` in its Build.cs. Grid ids are 64-bit: keep them as Integer64 in Blueprint and `int64` in C++. ## Boot the agent The **Crowdy Studio Agent** subsystem (`UCrowdyStudioAgent`, a Game Instance subsystem) lives under **Crowdy SDK > Studio**. | Blueprint | C++ | Does | |---|---|---| | **Get Agent Boot** | `GetAgentBoot(OnDone)` | What the page hosting the agent needs: **App Id**, **Graph QL Url**, **Model Base Url**, **Connect Origins**, **Studio Origin**, **Wallet Url** and **Models**, the models the app allows, with their prices. It holds no token. It answers **No Model** when no model is available to the app. | | none | `GetAgentToken()` | The app token to hand to the agent. Empty while signed out. | | none | `OnAgentTokenChanged` | Fires with the user id and the new token after a token rotation and after each sign-in, and with an empty token on sign-out. | | **On Agent Boot Changed** | `OnAgentBootChanged` | The SDK's API origin moved, so the boot material is stale. It is noticed when the app token changes and when the boot material is read. | **Connect Origins** lists every origin the agent may connect to. Put nothing else in the page's connect-src. The token hand-off is C++ only, so no Blueprint graph can read it, and it is never the session token. **Studio Origin** and **Wallet Url** come from the platform. If its links are missing or not https, they come from the Studio the API address implies: `ck.` gives `studio.`, and a local API's Studio is on port 3001. Only https links are handed out (http to this machine works outside a Shipping build). With no Studio address at all, the boot answers **Refused**. **Wallet Url** is where the player adds funds, so open it in their own browser. ## Consent, model use and live modding | Blueprint | C++ | Does | |---|---|---| | **Get Consent Notice** | `GetConsentNotice()` | The SDK's notice text: what reaches the model provider, who pays, and where sessions stay. Show it before asking. | | **Get Provider Consent** | `GetProviderConsent(OnDone)` | Whether the player consented to provider data use for this app: **Consented** and **Consented At Ms**. | | **Record Provider Consent** | `RecordProviderConsent(OnDone, bConsented)` | Records the consent after the player saw the notice. **Consented** false takes it back. | | **Get Model Usage** | `GetModelUsage(OnDone)` | Who pays (**Unknown**, **Player**, **App** or **Platform**), today's requests, today's charge and the day's limit, in millionths of a US dollar. | | **Authorize Live Modding** | `AuthorizeLiveModding(Action, OnDone)` | Asks the app's Allow Live Modding switch whether a **Draft Test** or a **Live** run may go ahead. **Allowed** is false unless **Result** is **Success**. | :::warning[Call Authorize Live Modding before every run.] Only **Authorize Live Modding** checks the app's Allow Live Modding switch. **Run Project**, **Build Client Mod**, **Deploy Client Mod** and the platform's build and deploy calls do not. A **Draft Test** is a real deploy on the player's grid, not a dry run. ::: A Studio call ends with one of these results; in Blueprint a result other than **Success** arrives on **On Failed**. | Result | Means | |---|---| | **Success** | Done. | | **Not Signed In** | The player has no app token yet. | | **Denied** | A missing permission such as `use_studio_agent`, or the app's agent policy. **Message** names which. | | **Not Found** | No such project or model. | | **Refused** | Any other refusal, the platform's or the SDK's before sending. | | **Failed** | The request did not complete, or the platform could not confirm the model provider's policy. Try again. | | **Bad Reply** | The answer was malformed, so nothing from it is returned. | | **Not Built** | This SDK version does not carry the call yet, so nothing was sent. | | **No Model** | **Get Agent Boot** only: no model is available to the app, from its agent policy and the platform's together, so the agent cannot start. The app's operator or the platform fixes it, not the player. | ## Studio projects The **Crowdy Studio Projects** subsystem (`UCrowdyStudioProjects`, a Game Instance subsystem) reads and creates the player's Studio projects in this app. | Blueprint | C++ | Does | |---|---|---| | **List Studio Projects** | `ListProjects(OnDone)` | The player's projects, newest first, up to 50 a call, archived ones left out. **More** is true when the platform holds others. | | **Get Studio Project** | `GetProject(ProjectId, OnDone)` | One project read fresh, with its **Files** ordered by target and path. | | **Create Studio Project** | `CreateProject(Name, Kind, OnDone)` | A new project of that **Kind**, filled from the platform's starters. | A project has a **Project Id**, **Name**, **Source** (**Studio**, or **GitHub** when a bound repository is the working tree), **Kind**, **Server Module**, **Client Module**, **Grid Id** (0 when none) and **Revision**. The revision is an opaque token that changes whenever the source does: hand it back as it is. For a GitHub project it is the revision joined to the commit as `revision@sha`. A file has a **Target**, a **Path** (`Cargo.toml`, `README.md` or a Rust file under `src/`), its **Content** and its own **Revision**. **Kind** says which halves the project has: **Server** (a server mod only), **Client** (a Mod Script only, riding the platform's starter mod), **Paired** (both, which run only together) or **Independent** (both, either of which may run alone). **Create Studio Project** names the modules from **Name**: the server module is its lowercase slug, and the client module is the slug plus `-client`, so a client module never shares a name with a server mod. A name with no ASCII letters or digits is refused. In C++ an overload takes the module names too: 1 to 48 lowercase letters, digits, `-` and `_`, different from each other. Every half the kind has needs a name, and a name for a half it does not have is refused. The server half starts from the platform's starter, and the client half from its client starter, with the package named for the client module. If the platform does not serve the client starter, the SDK uses its own copy of the same crate. If the platform refuses a starter, or it does not arrive, the create fails with the platform's reason. ## Run a project **Run Project** builds one revision of a project and puts it on one of the player's grids. Pass the revision your panel showed the player as **Expected Revision**. It, **Get Project Status** and the two pieces below need Application API v2.73.0; an older one refuses them with `GRAPHQL_VALIDATION_FAILED`. | Blueprint | C++ | Does | |---|---|---| | **Run Project** | `RunProject(GridId, ProjectId, ExpectedRevision, Mode, OnDone)` | Builds and deploys exactly that revision on the grid. | | none | `RunProject(GridId, ProjectId, ExpectedRevision, Mode, ExpectedServerModule, ExpectedClientModule, OnDone)` | The same, and answers **Revision Changed** before building when the project's server or client module name is not the one given, since those names pick the mods the run overwrites. An empty name is not checked. | | **Get Project Status** | `GetProjectStatus(GridId, ProjectId, OnDone)` | Where each half of the project is on the grid. | A run goes in this order: 1. The client half is built first, so a build that fails publishes nothing. 2. The server half is built, deployed and switched on. 3. The client half is attached to its mod, and consented to as its author. A client-only project rides a mod named for its client module. That mod is deployed from the platform's starter when the grid has none, and the run is refused when it exists and is switched off. The run is pinned. An empty **Expected Revision**, a grid id below 1 and a signed-out player are refused before anything is sent. If the saved revision, or in the C++ overload a module name, is not the one you passed, the answer is **Revision Changed** and nothing was built. A GitHub project's revision includes its commit. Each build a run sends names the project and revision, so the mod and its client half read back with that **Studio Project Id** and **Studio Revision**. One run per app runs at a time: a second answers **Busy**. A run keeps to its grid and to the player and app it started for. If either changes, it answers **Failed** and sends nothing more, though a step it already sent may still complete on the grid. **Result** is **Success** when the run went to its end. A crate that does not compile is still **Success**, with that half's **Phase** at **Build Failed**, so read the phases. The answer holds: | Field | Is | |---|---| | **Mode**, **Grid Id**, **Project Id** | What the run was for. | | **Revision** | The revision built, always the one asked for. | | **Targets** | Each half the project has, server first: **Target**, **Phase**, **Module**, **Mod Id**, **Digest**, **Version**, **Running Revision**, **Saved Revision** and **Message**. | | **Build Log** | The compiler's output for every half built, at most 64 KB each with the end kept. | | **Diagnostics** | Messages about project files, such as compiler errors: **Target**, **Source** (**rustc**, **Local** or **Runtime**), **Path**, **Line**, **Column**, **End Line**, **End Column** (0 when there is no end), **Severity**, **Message** and **Code**. Lines and columns count from 1. | A half's **Phase** is **Not Started**, **Building**, **Build Failed**, **Deploying**, **Deploy Failed**, **Deployed** or **Running**. **Deployed** means it is deployed but not running now, and **Message** says why. **Get Project Status** reads the platform back every time, so it needs no earlier run. It answers **Run In Flight** (a run of this project is still going), and the same targets. **Saved Revision** is the project's saved revision when it was read. **Running Revision** differs by half: - Server: the revision the platform says its mod was built from. It is empty when the mod was built from another project or from none. - Client: the revision a run deployed since this game started. It shows only while the platform still serves that run's digest, since the platform names no revision for a client half. A GitHub project's older revision reads as the platform's number alone, without its commit. ### The pieces of a run **Build Client Mod** builds one client crate and waits for it, as **Build Mod** does, with the same limits. **Deploy Client Mod** attaches a successful client build as a mod's client half on one of the player's grids; the mod must exist. Both are building blocks with no run lock, no pinned revision and no Allow Live Modding check. A dock uses **Run Project** instead. ### Run results [Mods](./mods.md#what-each-result-means) lists the mod results. Two more come with a run: | Result | Means | |---|---| | **Busy** | Another run for this app is still going, or the platform is already building one for this player. Try again once it ends. | | **Revision Changed** | The project's saved revision or module names are not the ones asked for, so nothing was built. | ## Grid channels and script logs **List Grid Channels** (`UCrowdyClaims::ListGridChannels(GridId, OnDone)`, under **Crowdy SDK > Claims**) answers the channels a grid owns, oldest first. A grid id of 0 or less is refused without sending. A row that is not one of the grid's own fails the whole list as **Bad Reply**. It answers with the [Chunk Claims](./chunk-claims.md#what-each-result-means) results. **Get Script Status** and **Get Script Log** read the [Mod Scripts](./mod-scripts.md#read-a-scripts-status-and-log) running for the player. Both answer **Not In Grid** unless the grid is the one the player stands in. ## From C++ Each C++ callback runs once on the game thread. If the game instance ends first it does not run, and a step a run already sent may still complete. The types behind the calls: | Type | Is | |---|---| | `FCrowdyStudioAgentBoot`, `FCrowdyStudioConsent`, `FCrowdyStudioModelUsage`, `FCrowdyStudioLiveModding` | The agent's answers. Each holds a `Result` (`ECrowdyStudioResult`) and a `Message`. | | `FCrowdyStudioModel` | One model the agent may use: `ModelId`, `Name`, `ContextWindow` (tokens, 0 when not given), `InputModalities`, and its prices in millionths of a US dollar per million tokens: `InputMicroUsdPerMillion`, `OutputMicroUsdPerMillion`, `ReasoningMicroUsdPerMillion` and `CachedInputMicroUsdPerMillion` (0 when not given). | | `FCrowdyStudioProject` | One project: `ProjectId`, `Name`, `Source`, `Revision`, `Kind`, `ServerModule`, `ClientModule`, `UpdatedAtMs`, `GitHubSha`, `GitHubRef` and `GridId`. | | `FCrowdyStudioProjectFile` | One file: `Target`, `Path`, `Content` and `Revision`. | | `FCrowdyStudioProjectList`, `FCrowdyStudioProjectInfo` | The answers to list, and to get and create. | | `ECrowdyStudioRunMode`, `ECrowdyStudioTarget` | `DraftTest` or `Live`; `Server` or `Client`. | | `ECrowdyStudioPayer`, `ECrowdyStudioProjectKind`, `ECrowdyStudioProjectSource` | The enums described above. | | `FCrowdyModRun`, `FCrowdyModProjectStatus` | The answers to a run and a status read, each with an `ECrowdyModResult`. | | `FCrowdyModRunTarget`, `ECrowdyModRunPhase` | One half of a run, and its phase: `NotStarted`, `Building`, `BuildFailed`, `Deploying`, `DeployFailed`, `Deployed`, `Running`. | | `FCrowdyModDiagnostic`, `ECrowdyModDiagnosticSeverity`, `ECrowdyModDiagnosticSource` | One message about a project file; the severity is `Error`, `Warning`, `Info` or `Hint`, and the source is `Rustc`, `Local` or `Runtime`. | | `FCrowdyModClient`, `FCrowdyModClientInfo` | A mod's client half on a grid, and the answer to **Deploy Client Mod**. A client half has `ModId`, `GridId`, `Name`, `OwnerUserId`, `ClientVersion`, `Digest`, `SizeBytes`, `CapabilitySummaryJson`, `CapabilityHash`, `TickIntervalMs`, `UpdatedAtMs`, and the `StudioProjectId` and `StudioRevision` it was built from (empty when its build named none). | | `UCrowdyGetAgentBoot`, `UCrowdyGetProviderConsent`, `UCrowdyRecordProviderConsent`, `UCrowdyGetModelUsage`, `UCrowdyAuthorizeLiveModding`, `UCrowdyListStudioProjects`, `UCrowdyGetStudioProject`, `UCrowdyCreateStudioProject`, `UCrowdyBuildClientMod`, `UCrowdyDeployClientMod`, `UCrowdyRunProject`, `UCrowdyGetProjectStatus` | The nodes. C++ calls the subsystems instead. | | `FCrowdyStudioBootAsyncResult`, `FCrowdyStudioConsentAsyncResult`, `FCrowdyStudioUsageAsyncResult`, `FCrowdyStudioLiveModdingAsyncResult`, `FCrowdyStudioProjectAsyncResult`, `FCrowdyStudioProjectListAsyncResult`, `FCrowdyModClientInfoAsyncResult`, `FCrowdyModRunAsyncResult`, `FCrowdyModProjectStatusAsyncResult` | The delegate types of the nodes' pins. | | `FOnCrowdyAgentTokenChanged`, `FOnCrowdyAgentBootChanged` | The delegate types of `OnAgentTokenChanged` (C++ only) and `OnAgentBootChanged`. | # Video Frames Source: https://docs.crowdedkingdoms.com/unreal-sdk/runtime/video-frames # Video Frames Video here means encoded still images sent as a stream. `UCrowdyVideoSender` sends one frame you give it to the players near your pawn. `UCrowdyVideoFrameReceiver` turns the video fragments the server fans out into whole frames and hands each one to you once, as an encoded image. The SDK does not capture a camera, does not encode, does not decode, does not know a frame's dimensions, and has not checked that received bytes are a valid image. Capturing and encoding a frame, and turning a received one into a texture, is your code. Other clients on the same app, such as a browser on the JavaScript SDK ([Webcam video](/crowdyjs/webcam-video)), send and receive the same frames. Unreal players can show JPEG only: the receiver delivers WebP frames, but this SDK does not decode WebP. Send WebP only to clients that can show it. ## When you need it A picture-in-picture of a nearby player, a video wall in the village square, any feature that shows another client's camera, or a camera the player shares with the people around them. If the game never shows video it pays for none of this: nothing is sent unless you call the sender, and with no listener bound a received fragment is dropped the moment it reaches the receiver, with no copy and no partial frame held. ## Send a frame `UCrowdyVideoSender` is a game instance subsystem. You capture the image and encode it as JPEG; the SDK splits it into datagrams, sends it from the local player's actor at the chunk the pawn stands in, and every receiver reassembles it. It reaches every player within `Distance` chunks who holds `use_video_chat` in the app and whose Video Receive setting and blocks admit you, CrowdyJS and CrowdyCPP players included, and your own client does not get it back. A receiver who does not qualify gets nothing, and the sender is not told. | Blueprint | C++ | Does | |---|---|---| | **Send Video Frame** | `SendVideoFrame(Frame, Codec, Distance)` | Sends one whole encoded image. **Codec** defaults to **Jpeg** and **Distance** to 1. Returns an `FCrowdyVideoFrameSend`. | | **Describe Video Send Result** | `DescribeVideoSendResult(Result)` | The result in words, for a log or a screen. | | **On Video Send Refused** | `OnVideoSendRefused` (`FOnCrowdyVideoSendRefused`) | Fires with an `FCrowdySendRefusal` when the server refuses one of your frames. | `FCrowdyVideoFrameSend` holds `Result` (an `ECrowdyVideoSendResult`), `FrameId`, `Fragments` and `Message`. `FrameId` and `Fragments` mean something only when `Result` is **Sent**; `Message` says why a frame was not sent and is empty when it was. The lantern village's player character sends a frame with `SendVideoFrameNearby`, which takes a JPEG your code produced, turns the torch white when the result is **Sent** and red when it is anything else, and turns it red again if the server later refuses a frame. ```cpp // LanternPlayer.h #include "Subsystem/CrowdyVideoSender.h" void WatchVideoSendRefusals(); void SendVideoFrameNearby(const TArray& Jpeg); UFUNCTION() void HandleVideoSendRefused(const FCrowdySendRefusal& Refusal); // LanternPlayer.cpp void ALanternPlayer::WatchVideoSendRefusals() { // Called once from BeginPlay. UCrowdyVideoSender* Video = GetGameInstance()->GetSubsystem(); Video->OnVideoSendRefused.AddDynamic(this, &ALanternPlayer::HandleVideoSendRefused); } void ALanternPlayer::SendVideoFrameNearby(const TArray& Jpeg) { // Jpeg is a whole encoded image the game already has. Sent means the frame was queued on this client, not that anyone got it. UCrowdyVideoSender* Video = GetGameInstance()->GetSubsystem(); const FCrowdyVideoFrameSend Sent = Video->SendVideoFrame(Jpeg, ECrowdyVideoCodec::Jpeg, 1); Torch->SetLightColor(Sent.Result == ECrowdyVideoSendResult::Sent ? FLinearColor::White : FLinearColor::Red); } void ALanternPlayer::HandleVideoSendRefused(const FCrowdySendRefusal& Refusal) { // The server refused a frame some time ago, for example because the player's access tier lacks use_video_chat. Torch->SetLightColor(FLinearColor::Red); } ``` A custom event `SendVideoFrameNearby` with a `Jpeg` byte array calls **Send Video Frame** on a **Crowdy Video Sender** getter node, breaks the returned struct with **Break Crowdy Video Frame Send**, and branches on whether `Result` is **Sent** to set the torch white or red. [Blueprint snippet: video-send, see /bp/unreal-sdk/video-send.txt] Once, at **Event BeginPlay**, bind **On Video Send Refused** to a custom event `OnVideoRefused`, which turns the torch red. [Blueprint snippet: video-send-refused, see /bp/unreal-sdk/video-send-refused.txt] | Result | Means | |---|---| | **Sent** | The frame left this client. There is no delivery receipt; a refusal arrives later on **On Video Send Refused**. | | **Not Connected** | No realtime connection yet, or it has closed. | | **No Local Player** | The player has no actor id yet, or no local pawn to place the frame at. | | **Empty** | The byte array has nothing in it. | | **Too Large** | The frame is larger than 17,872 bytes (16 fragments of 1,117 bytes). | | **Queue Full** | The outbound queue had no room for every fragment, or the connection refused the frame. | | **Codec Not Sent** | Only JPEG and WebP frames can be sent. | `Distance` is clamped to 0 through 8 chunks. Each sender counts its own frame ids, which wrap at 65535 and start from a value taken from the clock, so a client that restarts does not reuse ids the receivers just saw. An id is spent once the frame reaches the connection, even if the connection then refuses it. The earlier checks spend none. **Keep it small.** The server fans a frame out to every player in range, so cost grows with the crowd. Keep `Distance` at 0 or 1, send no more than 10 frames a second, and keep each frame under about 8 KB (a small image at a JPEG quality near 0.5). The figures behind this are in [Webcam video](/crowdyjs/webcam-video). :::warning[The player's access tier and Video Send setting must allow video.] A frame is refused by the server when the player's access tier lacks `use_video_chat`, for the app or for the grid covering the chunk, or when the player's Video Send setting is Off, which is the default for a minor without a parent's consent. The call still answers **Sent**, because that result means only that the frame was queued. The refusal arrives later on **On Video Send Refused**, at most once a second for the same refusal, and on a busy connection it may name a different send: show it to the player, do not act on it. Check **Video Send** in [Player safety](../services/player-safety.md) before you offer a camera. ::: **Success signal.** With another client in range that holds `use_video_chat` and whose Video Receive setting and blocks admit you, **Send Video Frame** answers **Sent** with `Fragments` above zero, and that client's receiver delivers the frame. ## Receive a frame The receiver is a world subsystem, created for Play in Editor and game worlds only. Bind `OnVideoFrameAssembled` (an `FOnCrowdyVideoFrameAssembled`) and it fires on the game thread once per completed frame with an `FCrowdyVideoFrame`. C++ code may bind `OnVideoFrameReady` instead, a plain multicast delegate (`FOnCrowdyVideoFrameReady`) at the same firing point with no dynamic-delegate overhead. The lantern village's player character binds at `BeginPlay`, and its `HandleVideoFrame` sets the torch's intensity to the byte count of each frame: a visible stand-in for the decode the example deliberately leaves out, because decoding is not the SDK's, as the page says below. ```cpp // LanternPlayer.h #include "Replication/Subsystems/CrowdyVideoFrameReceiver.h" UFUNCTION() void HandleVideoFrame(const FCrowdyVideoFrame& Frame); // LanternPlayer.cpp void ALanternPlayer::BeginPlay() { Super::BeginPlay(); if (UCrowdyVideoFrameReceiver* Video = GetWorld()->GetSubsystem()) { Video->OnVideoFrameAssembled.AddDynamic(this, &ALanternPlayer::HandleVideoFrame); } } void ALanternPlayer::HandleVideoFrame(const FCrowdyVideoFrame& Frame) { // The bytes are an encoded image the SDK never decodes; a consumer turns them into a texture. Torch->SetIntensity(static_cast(Frame.Bytes.Num())); } ``` In Blueprint the receiver is reached like any world subsystem: a **Crowdy Video Frame Receiver** getter node, **Bind Event to On Video Frame Assembled** off it, and a custom event with a `Frame` pin; **Break Crowdy Video Frame** opens the struct. The twin below, in the player character's Blueprint, binds at **Event BeginPlay**: a **Crowdy Video Frame Receiver** getter feeds **Bind Event to On Video Frame Assembled**, whose custom event `OnVideoFrame` calls **Set Visibility** on `Torch` (a Point Light component you add). Break the `Frame` pin to reach `Bytes`, `Sender Id`, and `Codec`. [Blueprint snippet: video-receive, see /bp/unreal-sdk/video-receive.txt] :::caution[Binding late costs you the frame already in flight, and nothing else.] Reassembly is turned on by the first bind. The one frame that was assembling when you bound may be missed; every frame after it is delivered. Nothing before the bind was kept. ::: **Success signal.** With another client in range sending video into the same app (this SDK or another), the torch's intensity jumps with every completed frame, and `GetPendingSenderCount()` reads above zero while a frame is half arrived. ## Choose whose video you receive These two are on the **Crowdy SDK Subsystem** (category **Crowdy SDK > Video**). The server sends no video that is left out, so it costs no data. | Blueprint | C++ | Does | |---|---|---| | **Set Video Speakers** (Speaker Uuids) | `SetVideoSpeakers(const TArray& SpeakerUuids)` | Has the server send you video only from these players' actor ids, at most 32, and none when the list is empty. Returns false, logs a warning and changes nothing for a longer list or an id that is not 32 characters. | | **See All Video Speakers** | `SeeAllVideoSpeakers()` | Goes back to every player in range. | The app can set a lower limit, `maxVideoSpeakers` (see [game setup](/management-api/game-setup#c5-cap-the-speakers-each-player-receives)), and the server refuses a longer list. Calling it again with the same players, in any order, sends nothing. Which players to name is your game's choice, such as the `SenderId` of the cameras on screen. The list holds across map changes and reconnects until **See All Video Speakers** or sign-out. Voice has its own pair; see [Voice Chat](../services/voice-chat.md#choose-whose-voice-you-receive). ## The frame `FCrowdyVideoFrame`, all fields read-only: | Field | What it is | |---|---| | `SenderId` (`FString`) | The sender's 32 wire octets as text. Exact and unambiguous; empty for an unset id. | | `SenderUUID` (`FGuid`) | The key derived from those octets, the id the rest of the SDK addresses an actor by. Lossy: the derivation reads the octets as hexadecimal, so two senders whose ids differ only outside that alphabet derive the same key. `USerializationFunctionLibrary::ToGuid` (Blueprint: **To Guid**) derives the same key from a `SenderId` string, and returns an invalid guid for text that is not an actor id. | | `Codec` (`ECrowdyVideoCodec`) | `Jpeg` or `WebP`. `Unknown` is what a byte this build has no entry for maps to; a fragment carrying one is dropped before it reaches you. | | `FrameId` (`int32`) | The sender's own counter. It wraps, orders that sender's frames, and means nothing across two senders. | | `Bytes` (`TArray`) | The encoded image, JPEG or WebP according to `Codec`. | | `ChunkX`, `ChunkY`, `ChunkZ` (`int64`) | The chunk the last fragment was broadcast over. | | `ServerTimestamp` (`int64`) | When the server stamped that last fragment, in milliseconds since the epoch. | :::warning[Use SenderId, not SenderUUID, to tell two senders apart for certain.] `SenderUUID` is the convenient key for matching a frame to an entity you already track by `FGuid`. It can name more than one sender. When correctness depends on which camera this is, compare `SenderId`. ::: :::danger[There is no decode anywhere in the SDK.] `Bytes` is a JPEG or WebP file in memory. Turning it into a `UTexture2D` is your own code, with the engine's image wrapper module or a decoder of your choice, and validating it as an image is part of that job: the bytes came off the network from another client. ::: ## Housekeeping | Call | What it answers or does | |---|---| | `GetPendingSenderCount()` | Senders with a frame half arrived. Zero while nothing is listening, since nothing is ingested. | | `GetDroppedFragmentCount()` | Fragments dropped for a malformed header, or for a frame their sender had already moved past. | | `GetAbandonedFrameCount()` | Frames abandoned incomplete: superseded by a newer frame, timed out, or the sender left. | | `ForgetSender(SenderGuid)` | Drops whatever is half assembled for one sender and forgets its frame counter. Exposed because a sender the server never announced as gone is otherwise never released, and a sender that rejoins and restarts at frame zero has every fragment dropped as a straggler until its counter climbs back past the old value. One key can name more than one sender, and every sender it names is forgotten. | The receiver releases a sender itself when the server announces its departure or the tracker times it out, using the same lossy key. ## What is not delivered - A client's own fragments. The server sends them back only while **Toggle Owner Echo** is on, and a frame of your own camera is one you already have, so they are discarded, never reassembled. - A frame that never completes. A fragment for a frame the sender has moved past is dropped; the incomplete frame is abandoned and counted. Video fragments share the per-frame receive budget with every other message the connection receives; see [Connection and reconnect](./connection-and-reconnect.md#the-receive-budget). ## Gotchas - The sender is a game instance subsystem. The receiver is a world subsystem: there is none in an editor world, and a new world has a new receiver with nothing bound. - Nothing is reassembled until something is bound. A diagnostic that reads the counters with no listener sees zeros. - `FrameId` is per sender. Do not use it to order frames from two cameras. - `SenderUUID` is the SDK's actor key and is lossy by construction; `SenderId` is exact. ## Related - [Connection and reconnect](./connection-and-reconnect.md): the receive budget these fragments share. - [Player safety](../services/player-safety.md): the video permission, and finding out who a frame came from. - [Voice chat](../services/voice-chat.md): the sibling communication feature. - [Entities and spawning](./entities-and-spawning.md): the actor tracker whose departures release a sender.