Skip to main content

Chunk

A class in Root.Township, Alta.Chunks.

A piece of the world that loads, unloads and saves as a unit. Every entity sits in one chunk. The server loads a chunk while players are near it (or it is force loaded) and streams its entities to them. Look one up with ChunksByIdentifier or ChunksByIndex; LocationChunk is the subclass for places in the world.

Constructors​

MemberWhat it is
Chunk()Unity makes components itself; use AddComponent or spawn a prefab instead of new.

Fields​

MemberWhat it is
const int BitsToSerializeNumber of bits used to send a chunk index (13, so up to 8192 chunks).
const string OverworldChunkTagThe tag string Overworld Chunk.
12 private and internal fields
MemberWhat it is
private bool autoSyncsWhether the chunk syncs its entities to players without them being in it. Always true for global chunks; read through AutoSyncs.
private string chunkIdentifierBacking field for ChunkIdentifier; defaults to the object name in the editor.
private bool isForceLoadedBacking field for IsForceLoaded.
private bool isForceUnloadedWhen set, the chunk gets an empty content manager, so nothing in it is ever loaded or saved.
private bool isGlobalMarks a global chunk; backing field for IsGlobal.
private bool isLoadedBacking field for IsLoaded.
private static Logger loggerNLog logger for this class.
private GlobalLogicManager logicManagerBacking field for LogicManager, the global logic manager for this chunk.
private const int MaxChunksIndexNumber of chunk indices (8192, the 13 bits sent over the network).
private ChunkSaveVersion minimumSaveVersionLowest chunk save version the chunk accepts; older saves are logged as out of date when loaded.
private static uint nextIndexStatic counter for the next chunk index to try in FindIndex.
private MethodSync syncIndexMethod sync that sends the chunk's index to each player when they connect.

Properties​

MemberWhat it is
bool AutoSyncs { get; }Whether the server tells clients to load and unload this chunk as players come and go. Always true for global chunks.
string ChunkIdentifier { get; set; }The chunk's unique name, also used as its save key. Setting it recomputes Seed.
static Dictionary<string, Chunk> ChunksByIdentifier { get; }Static map from chunk identifier to chunk, filled in Awake.
static Dictionary<uint, Chunk> ChunksByIndex { get; }Static map from network index to chunk. Filled on the server at init and on clients when the index arrives.
ChunkContentManager ContentManager { get; private set; }Loads, unloads and saves the chunk's content. A server, client or empty manager depending on side and IsForceUnloaded.
ChunkEntityManager Entities { get; private set; }Server: the entities in this chunk.
uint Index { get; private set; }Small network id for the chunk, assigned by the server and sent to each client.
bool IsForceLoaded { get; set; }Whether the chunk stays loaded regardless of players. Setting it updates the loaded state.
bool IsForceUnloaded { get; }Set on the prefab. Such chunks use an empty content manager and never load content.
bool IsFullyLoaded { get; }Loaded and not in the middle of a content transition.
bool IsFullyUnloaded { get; }Not loaded and not in the middle of a content transition.
bool IsGlobal { get; }Set on the prefab for chunks that are not a place in the world. Global chunks always auto sync.
bool IsLoaded { get; private set; }Whether the chunk is meant to be loaded right now. Content may still be loading; see IsFullyLoaded.
virtual bool IsSkippingStaticContent { get; }When true the server content manager skips the chunk's static content. False here; subclasses override it.
bool IsStatic { get; set; }True for chunks that are part of the scene. Personal storage chunks set it false, so destroying them is not logged as an error.
static int LoadedCount { get; private set; }Static count of chunks currently loaded.
GlobalLogicManager LogicManager { get; }The chunk's GlobalLogicManager, if set on the prefab.
ChunkSaveVersion MinimumSaveVersion { get; }Saves older than this version are treated as invalid and not loaded.
ChunkPlayerManager Players { get; private set; }Server: the players currently in this chunk. The first joining and last leaving trigger a load or unload.
IProceduralGenerationStreamer ProceduralStreamer { get; private set; }The IProceduralGenerationStreamer on the chunk, if it generates content procedurally.
uint Seed { get; private set; }Hash of the chunk identifier, used as a stable random seed.
virtual SpawnData SpawnData { get; }Spawn data used for entities this chunk spawns. SpawnData.Default unless overridden.
List<Task> UnloadingGate { get; }Tasks to wait for before unloading. Cleared and refilled each time BeganUnloading fires.
protected PlayerEntitySyncServer Sync { get; private set; }Server: the sync that streams this chunk's entities to players.

Events​

MemberWhat it is
event Action<Chunk> BeganUnloadingRaised when the chunk starts unloading. Handlers can add tasks to UnloadingGate to delay the unload.
event Action<Chunk> FullyLoadedRaised when the chunk's content has finished loading.
event Action<Chunk> FullyUnloadedRaised when the chunk's content has finished unloading.

Methods​

MemberWhat it is
void ClearEntities()Server: removes every entity from the chunk's entity list. Refuses and logs an error if players are in it.
async Task ClearSave()Clears the chunk's saved content through its content manager.
async Task ForceLoad()Server: keeps the chunk loaded even with no players near, and waits for the load.
void ForceUnloadAndSave()Server: drops all players from the chunk, unloads it and saves it, blocking until done.
void HandleParentChange(IChunker chunker)Passes an entity's parent change to the chunk's player sync, unless the chunk is mid load or unload.
override void Initialize()Finds the procedural streamer, sets up the client content manager and registers the index sync.
override void InitializeAsServer(SpawnData spawnData)Server: sets up the content manager, entity and player lists, and picks a free index.
void InitializeContentManager()Creates the side-specific content manager and sync objects once, and hooks the load and unload events.
override void OnConnected(Player player)Server: sends the chunk's index to a client who just got the chunk.
async Task Save()Saves the chunk's content, logging any exception instead of throwing.
static void SerializeChunkAndPosition(Stream stream, ref Chunk chunk, ref Vector3 position, NetworkEntity entity = null)Writes or reads a chunk reference followed by a position encoded by that chunk.
static void SerializeEntityPosition(Stream stream, INetworkEntity entity, ref Vector3 position)Writes or reads an entity's position along with its chunk. The server uses the entity's position chunk; clients find the best containing chunk.
virtual void SerializePosition(Stream stream, ref Vector3 position, NetworkEntity entity = null)Writes or reads a position. The base class sends a full vector; LocationChunk overrides it to quantise within its bounds.
override string ToString()Returns the chunk identifier in brackets.
protected virtual void OnDestroy()Removes the chunk from the static lookups. Logs an error if a static chunk is destroyed outside a reload or quit.
protected virtual void OnValidate()Defaults the identifier to the GameObject name.
7 private and internal methods
MemberWhat it is
private void Awake()Registers the chunk in ChunksByIdentifier and sets Seed from the hash of its identifier.
private void ContentIsFullyLoaded(Chunk chunk)Handler on the content manager's Loaded event; raises FullyLoaded.
private void ContentIsFullyUnloaded(Chunk chunk)Handler on the content manager's Unloaded event; raises FullyUnloaded.
private uint FindIndex()Server: finds the next free chunk index below 8192, wrapping once. If none is free it logs a fatal error and shuts the server down.
private void SetIndex(uint index)Stores the chunk's network index and registers it in ChunksByIndex.
private void SyncIndex(IPlayer player, Stream stream)Sends the chunk's index to a player in 13 bits; the client calls SetIndex with it.
private async Task UpdateLoadedAsync()Server and client: works out whether the chunk should be loaded (force loaded, players syncing, or unload blocked) and loads or unloads its content.

Used in​

Members of other types that take, return or hold a Chunk:

CaveLayerManager.PrepareSpawn, CaveLayerChunk.GetNeighboursForLoading, CaveLayerChunk.OnFullyLoaded, CaveLayerStreamer.Unloaded, ChunkContentManager.Chunk, ChunkContentManager.ChunkContentManager, ChunkContentManager.Loaded, ChunkContentManager.Unloaded, ChunkEntityManager.Chunk, ChunkEntityManager.ChunkEntityManager, ChunkFileHelper.GetFile, ChunkPlayerManager.Chunk, ChunkPlayerManager.ChunkPlayerManager, ChunkPositionSurface.AddToChunk, ChunkPrefabPointer.Unuse, ChunkPrefabPointer.Use, ChunkPrefabPointer.UseOld, ChunkPrefabPointer.PointerInstance.Unuse, ChunkPrefabPointer.PointerInstance.Use, ChunkPrefabPointer.PointerInstance.Uses, ChunkReference.Chunk, ChunkReference.ChunkReference, ChunkSync.chunk, ClientChunkContentManager.ClientChunkContentManager, DynamicChunkContentManager.chunk, DynamicChunkContentManager.DynamicChunkContentManager, EmptyChunkContentManager.EmptyChunkContentManager, FastChunkLookup.AddChunksInGrid, FastChunkLookup.GetChunksToLoadWithinRadius, LocationChunk.GetNeighboursForLoading, LocationChunkHelper.GetChunksToLoad, LocationChunkHelper.GetChunksWithinRadius, OverworldChunk.GetNeighboursForLoading, PlayerEntitySync.chunk, PlayerEntitySync.PlayerEntitySync, PlayerEntitySyncServer.OnChunkLoaded, PlayerEntitySyncServer.OnChunkUnloaded, PlayerEntitySyncServer.PlayerEntitySyncServer, PrefabLoadManager.loadedPointerPrefabs, PrefabLoadManager.LoadPointer, PrefabLoadManager.UnloadPointer, ServerChunkContentManager.ServerChunkContentManager, StaticChunkContentManager.StaticChunkContentManager, WorldLandmark.LoadedChunks, WorldLandmark.sceneLoadedChunks, WorldLandmark.sceneStaticChunks, WorldLandmark.StaticChunks, WorldLandmarkManager.AttemptLoadLandmark, WorldLandmarkManager.AttemptLoadLandmarkFromStatic, WorldLandmarkManager.AttemptUnloadLandmark, WorldLandmarkManager.ForceUnloadLandmark, WorldLandmarkManager.toLoad, WorldLandmarkManager.toUnload, ChunkInfo.op_Implicit, ProfilingCommandModule.ChunkUnloaded, ProfilingCommandModule.loadedChunks, SpawnCommandModule.Spawn, UserInfoDetailed.Chunk, WackyCommandModule.DestroyBase, GenericCraftingPiece.ApplySaveData and 137 more.