Nebula
Loading...
Searching...
No Matches
world.h
Go to the documentation of this file.
1#pragma once
2//------------------------------------------------------------------------------
9//------------------------------------------------------------------------------
10#include "core/refcounted.h"
11#include "entity.h"
12#include "entitypool.h"
13#include "component.h"
15#include "util/queue.h"
16#include "category.h"
17#include "processorid.h"
18#include "processor.h"
20#include "frameevent.h"
21#include "util/delegate.h"
22#include "util/fourcc.h"
23#include "basegamefeature/components/basegamefeature.h"
24
25
26namespace MemDb
27{
28class Database;
29}
30namespace Util
31{
32class Blob;
33}
34
35namespace Game
36{
37
39class PackedLevel;
40
42World* GetWorld(WorldHash worldHash);
44World* GetWorld(WorldId worldId);
45
46// which mode a world is currently running in. A processor only runs if its phase
47// allows the mode the world is in.
48enum WorldMode : uint8_t
49{
50 EditorMode = 0, // world is not simulating
51 PlayMode = 1, // world is running gameplay
52};
53
54// returns the phase bit that corresponds to a world mode
55inline ProcessorPhase
57{
58 return mode == PlayMode ? PlayPhase : EditorPhase;
59}
60
63
64//------------------------------------------------------------------------------
91class World
92{
93public:
94 // Generally, only the game server should create worlds
96 ~World();
97
99 WorldHash GetWorldHash() const;
101 WorldId GetWorldId() const;
102
106
108 Entity CreateEntity(bool immediate = true);
110 void DeleteEntity(Entity entity);
111
113 bool IsValid(Entity entity) const;
115 bool HasInstance(Entity entity) const;
116
119
121 SizeT GetNumEntities() const;
122
126
129 void EnumerateEntities(EntityCreatedCallback const& callback);
130
132 template <typename TYPE>
133 TYPE* AddComponent(Entity entity);
136 template <typename TYPE>
137 void AddComponent(Entity entity, TYPE const& component);
139 void* AddComponent(Entity entity, ComponentId component);
141 void* AddComponent(Entity entity, ComponentId component, const void* value);
142
144 template <typename TYPE>
145 bool HasComponent(Entity entity) const;
147 bool HasComponent(Entity entity, ComponentId component) const;
148
151 byte* FindComponentData(Entity entity, ComponentId component) const;
152
155 template <typename TYPE>
156 void RemoveComponent(Entity entity);
158 void RemoveComponent(Entity entity, ComponentId component);
159
161 template <typename TYPE>
162 void SetComponent(Entity entity, TYPE const& value);
164 template <typename TYPE>
165 TYPE GetComponent(Entity entity);
166
169 void MarkAsModified(Game::Entity entity);
170
172 Dataset Query(Filter filter);
176
184 void DecayComponentValue(Entity entity, ComponentId component);
185
189 void UnloadLevel(PackedLevel* level);
191 bool ExportLevel(Util::String const& path);
192
195
198
199 // -- Internal methods -- Use with caution! --
200
202 MemDb::RowId GetInstance(Entity entity) const;
204 void SetComponentValue(Entity entity, ComponentId component, void* value, uint64_t size);
206 void ReinitializeComponent(Entity entity, ComponentId component, void* value, uint64_t size);
210 static void Override(World* src, World* dst);
214 void DeallocateEntityId(Entity entity);
218 MemDb::RowId AllocateInstance(Entity entity, MemDb::TableId table, Util::Blob const* const data = nullptr);
220 void InitializeInstance(Entity entity);
222 void InitializeInstance(Entity entity, MemDb::TableId tableId, MemDb::RowId row);
223 void FinalizeAllocate(Entity entity);
225 void DeallocateInstance(MemDb::TableId table, MemDb::RowId instance, Entity entity);
227 void DeallocateInstance(Entity entity);
229 void Defragment(MemDb::TableId tableId);
231 void* GetInstanceBuffer(MemDb::TableId const tableId, uint16_t partitionId, ComponentId const component);
233 void* GetColumnData(MemDb::TableId const tableId, uint16_t partitionId, MemDb::ColumnIndex const column);
240
243
244 void RenderDebug();
245
246private:
247 friend class GameServer;
248 friend class PackedLevel;
249
254
259
261 {
263 ComponentId componentId = ComponentId::Invalid();
265 void* data = nullptr;
268 IndexT next = InvalidIndex;
269 };
270
276
277 // These functions are called from game server
278 void Start();
279 void BeginFrame();
280 void SimFrame();
281 void EndFrame();
282 void OnLoad();
283 void OnSave();
284 void ManageEntities();
285 void Reset();
286 void PrefilterProcessors();
288 void ClearDecayBuffers();
289
292
294 MemDb::RowId Migrate(Entity entity, MemDb::TableId newTable);
296 void Migrate(
297 Util::Array<Entity> const& entities,
298 MemDb::TableId fromTable,
299 MemDb::TableId newTable,
301 );
302
305 void DecayComponent(ComponentId component, MemDb::TableId tableId, MemDb::ColumnIndex column, MemDb::RowId instance, Entity entity);
307 void AppendToDecayBuffer(ComponentId component, const void* value);
308
311
316
318 void* StageComponent(Entity entity, ComponentId component, const void* value, SizeT typeSize);
320 IndexT StagedHead(Entity entity) const;
322 void* FindStagedComponent(Entity entity, ComponentId component) const;
323
354 bool cacheValid = false;
361};
362
363//------------------------------------------------------------------------------
366inline WorldHash
368{
369 return this->hash;
370}
371
372//------------------------------------------------------------------------------
375inline WorldId
377{
378 return this->worldId;
379}
380
381//------------------------------------------------------------------------------
384template <typename TYPE>
385inline void
386World::SetComponent(Entity entity, TYPE const& value)
387{
388#if NEBULA_DEBUG
389 n_assert2(
390 !this->pipeline.IsRunningAsync(),
391 "Settings components in arbitrary entities while executing an async processor is currently not supported!"
392 );
393#endif
394
395#if NEBULA_DEBUG
396 n_assert2(
398 "SetComponent: Provided value's type is not the correct size for the given ComponentId."
399 );
400#endif
401
402 TYPE* ptr = reinterpret_cast<TYPE*>(FindComponentData(entity, GetComponentId<TYPE>()));
403#if NEBULA_DEBUG
404 n_assert2(ptr != nullptr, "SetComponent: Entity does not have the component, staged or in a table!");
405#endif
406 *ptr = value;
407}
408
409//------------------------------------------------------------------------------
412template <typename TYPE>
413inline TYPE
415{
416#if NEBULA_DEBUG
417 n_assert2(
418 !this->pipeline.IsRunningAsync(),
419 "Getting components from entities while executing an async processor is currently not supported!"
420 );
421#endif
422
423#if NEBULA_DEBUG
424 n_assert2(
426 "GetComponent: Provided value's type is not the correct size for the given ComponentId."
427 );
428#endif
430
431 byte* data = this->FindComponentData(entity, id);
432#if NEBULA_DEBUG
433 n_assert2(data != nullptr, "GetComponent: Entity does not have the component, staged or in a table!");
434#endif
435 return *(TYPE*)data;
436}
437
438//------------------------------------------------------------------------------
441template <typename TYPE>
442inline void
444{
445#if NEBULA_DEBUG
446 n_assert2(
447 !this->pipeline.IsRunningAsync(),
448 "Removing components from entities while executing an async processor is currently not supported!"
449 );
450#endif
452 .entity = entity,
453 .componentId = Game::GetComponentId<TYPE>(),
454 };
455 this->removeComponentQueue.Append(cmd);
456}
457
458//------------------------------------------------------------------------------
461template <typename TYPE>
462inline bool
464{
465 return this->HasComponent(entity, Game::GetComponentId<TYPE>());
466}
467
468//------------------------------------------------------------------------------
471template <typename TYPE>
472inline TYPE*
474{
475 /*
476 We could possibly support this by either having thread local allocators and
477 staged queues and gathering after the processors have finished (must clear
478 allocators by issuing a separate job for this at the end of the frame), or by
479 just introducing a simple mutex.
480 */
481#if NEBULA_DEBUG
482 n_assert2(
483 !this->pipeline.IsRunningAsync(), "Adding component to entities while in an async processor is currently not supported!"
484 );
485#endif
487#if NEBULA_DEBUG
488 n_assert(MemDb::AttributeRegistry::TypeSize(id) == sizeof(TYPE));
489 //n_assert(!this->HasComponent<TYPE>(entity));
490#endif
491 TYPE* data = (TYPE*)this->StageComponent(entity, id, nullptr, sizeof(TYPE));
492
494 ComponentInterface* cInterface;
495 cInterface = static_cast<ComponentInterface*>(attr);
496
497 if (this->componentInitializationEnabled && cInterface->Init != nullptr)
498 {
499 // run initialization function if it exists.
500 cInterface->Init(this, entity, data);
501 }
502
503 return data;
504}
505
506//------------------------------------------------------------------------------
509template <typename TYPE>
510inline void
511World::AddComponent(Entity entity, TYPE const& component)
512{
513#if NEBULA_DEBUG
514 n_assert2(
515 !this->pipeline.IsRunningAsync(), "Adding component to entities while in an async processor is currently not supported!"
516 );
517#endif
519#if NEBULA_DEBUG
520 n_assert(MemDb::AttributeRegistry::TypeSize(id) == sizeof(TYPE));
521 //n_assert(!this->HasComponent<TYPE>(entity));
522#endif
523 TYPE* data = (TYPE*)this->StageComponent(entity, id, &component, sizeof(TYPE));
524
526 ComponentInterface* cInterface;
527 cInterface = static_cast<ComponentInterface*>(attr);
528
529 if (this->componentInitializationEnabled && cInterface->Init != nullptr)
530 {
531 // run initialization function if it exists.
532 cInterface->Init(this, entity, data);
533 }
534}
535
536template <>
538template <>
540template <>
542
543template <>
545template <>
547template <>
549
552template <>
553void World::SetComponent(Entity entity, Game::HTransform const&);
554
555} // namespace Game
These are registered to the attribute registry so that we can add more functionality to attributes.
Definition component.h:86
ComponentInitFunc Init
Definition component.h:104
Generation pool.
Definition entitypool.h:22
Definition frameevent.h:156
bool IsRunningAsync()
check if the pipeline is currently executing an async frame event batch
Definition frameevent.cc:641
Represents a level that can be instantiated into a world.
Definition level.h:38
The parent, child and sibling links of the entities in one world's hierarchy.
Definition transformhierarchy.h:53
A container of entities, their components, and processors.
Definition world.h:92
void SetEntityCreatedCallback(EntityCreatedCallback const &callback)
Set the callback invoked for every entity instance allocated in this world.
Definition world.cc:1014
void DeallocateInstance(MemDb::TableId table, MemDb::RowId instance, Entity entity)
Deallocate an entity instance. Use this with caution!
Definition world.cc:1543
PackedLevel * PreloadLevel(Util::String const &path)
preload a level that can be instantiated
Definition world.cc:101
void MoveInstance(MemDb::Table::Partition *partition, MemDb::RowId from, MemDb::RowId to)
Move a instance/row within a partition.
Definition world.cc:1641
Dataset Query(Filter filter)
Query the entity database using specified filter set. This does NOT wait for resources to be availabl...
Definition world.cc:2083
void AddStagedComponentsToEntity(Entity entity, AddStagedComponentCommand *cmds, SizeT numCmds)
Adds all components in cmds to entity.
Definition world.cc:1182
Entity AllocateEntityId()
Allocate an entity id. Use this with caution!
Definition world.cc:513
bool componentInitializationEnabled
Disable if initialization of components is not required (ex. when running as editor db).
Definition world.h:239
EntityPool pool
used to allocate entity ids for this world
Definition world.h:325
Util::Array< RemoveComponentCommand > removeComponentQueue
Stores all deferred remove component commands.
Definition world.h:348
ComponentDecayBuffer const GetDecayBuffer(ComponentId component)
Get a decay buffer for the given component.
Definition world.cc:950
Ptr< MemDb::Database > db
contains all entity instances
Definition world.h:336
byte * FindComponentData(Entity entity, ComponentId component) const
The data of a component, read from the entity's table when it is there, otherwise from its chain of s...
Definition world.cc:913
void * FindStagedComponent(Entity entity, ComponentId component) const
A component on the entity's chain of staged commands, or nullptr.
Definition world.cc:890
WorldId GetWorldId() const
Returns the world ID for this world. This corresponds to Game::Entity::world.
Definition world.h:376
bool IsValid(Entity entity) const
Check if an entity ID is still valid.
Definition world.cc:975
Ptr< TransformHierarchy > hierarchy
The transform hierarchy of the entities in this world.
Definition world.h:352
EntityMapping GetEntityMapping(Entity entity) const
Returns the entity mapping of an entity.
Definition world.cc:994
TYPE GetComponent(Entity entity)
Get an entitys component.
Definition world.h:414
void PrefilterProcessors()
Definition world.cc:616
SizeT GetNumEntities() const
Number of entity ids currently allocated in this world.
Definition world.cc:1005
void ClearDecayBuffers()
Clears all decay buffers. This is called by the game server automatically.
Definition world.cc:962
bool HasComponent(Entity entity) const
Check if entity has a specific component.
Definition world.h:463
void ExecuteAddComponentCommands()
dispatches all staged components to be added to entities
Definition world.cc:1076
Entity CreateEntity(bool immediate=true)
Create a new empty entity.
Definition world.cc:691
void RenderDebug()
Definition world.cc:1787
bool cacheValid
Set to true if the caches for the frame pipeline are valid.
Definition world.h:354
Util::Queue< AllocateInstanceCommand > allocQueue
Stores all deferred allocation commands.
Definition world.h:342
void * StageComponent(Entity entity, ComponentId component, const void *value, SizeT typeSize)
Stage a component for an entity and put it on the entity's chain of staged commands.
Definition world.cc:849
void SetComponentValue(Entity entity, ComponentId component, void *value, uint64_t size)
Set the value of a component by providing a pointer and type size.
Definition world.cc:1696
void Reset()
Definition world.cc:671
void AppendToDecayBuffer(ComponentId component, const void *value)
Copies a component value to the component's decay buffer.
Definition world.cc:772
void SimFrame()
Definition world.cc:568
void DeleteEntity(Entity entity)
Delete entity.
Definition world.cc:714
void EnumerateEntities(EntityCreatedCallback const &callback)
Call callback for every entity in the world that has an instance in the database.
Definition world.cc:1023
void ReinitializeComponent(Entity entity, ComponentId component, void *value, uint64_t size)
Set the value of a component by providing a pointer and type size, then reinitialize the component.
Definition world.cc:1735
void UnloadLevel(PackedLevel *level)
unload a preloaded level
Definition world.cc:317
bool HasInstance(Entity entity) const
Check if an entity has an instance. It might be valid, but not have received an instance just after i...
Definition world.cc:984
MemDb::RowId AllocateInstance(Entity entity)
Allocate an entity instance in default (empty) table without initializing components....
Definition world.cc:1427
FramePipeline pipeline
The frame pipeline for this world.
Definition world.h:356
Ptr< TransformHierarchy > GetHierarchy() const
The transform hierarchy of this world.
Definition world.cc:53
World(WorldHash hash, WorldId id)
Definition world.cc:61
void FinalizeAllocate(Entity entity)
Definition world.cc:1530
SizeT GetNumInstances(MemDb::TableId tid)
Get total number of instances in an entity table.
Definition world.cc:1067
friend class PackedLevel
Definition world.h:248
void * GetColumnData(MemDb::TableId const tableId, uint16_t partitionId, MemDb::ColumnIndex const column)
Get a pointer to the first instance of a column in a partition of an entity table....
Definition world.cc:1350
Util::FixedArray< ComponentDecayBuffer > componentDecayTable
Contains all the component decay buffers. Lookup directly via ComponentId.
Definition world.h:360
MemDb::TableId CreateEntityTable(EntityTableCreateInfo const &info)
Create a table in the entity database that has a specific set of components.
Definition world.cc:1369
void RemoveComponentsFromEntity(Entity entity, RemoveComponentCommand *cmds, SizeT numCmds)
Removes all components in cmds from entity.
Definition world.cc:1273
void RemoveComponent(Entity entity)
Remove a component from an entity.
Definition world.h:443
void ExecuteRemoveComponentCommands()
dispatches all staged components to be removed from entities
Definition world.cc:1144
friend class GameServer
Definition world.h:247
void DeallocateEntityId(Entity entity)
Deallocate an entity id. Use this with caution!
Definition world.cc:530
IndexT StagedHead(Entity entity) const
The first command on the entity's chain of staged commands, or InvalidIndex.
Definition world.cc:876
WorldMode mode
the mode this world is currently running in, which decides which processors execute
Definition world.h:242
Util::Array< EntityMapping > entityMap
maps entity index to table+row pair
Definition world.h:331
FramePipeline & GetFramePipeline()
Get the frame pipeline.
Definition world.cc:2058
void DecayComponentValue(Entity entity, ComponentId component)
Put the value an entity's component holds into the component's decay buffer, the way removing it woul...
Definition world.cc:754
void BeginFrame()
Definition world.cc:556
Util::Array< IndexT > stagedHeads
the first staged command per entity index.
Definition world.h:334
MemDb::RowId GetInstance(Entity entity) const
Get instance of entity.
Definition world.cc:1360
void DecayComponent(ComponentId component, MemDb::TableId tableId, MemDb::ColumnIndex column, MemDb::RowId instance, Entity entity)
Copies the component to the decay table and runs its decay callback.
Definition world.cc:736
WorldId worldId
world id
Definition world.h:340
void Start()
Definition world.cc:545
void EndFrame()
Definition world.cc:580
Ptr< MemDb::Database > GetDatabase()
Get the entity database. Be careful when directly modifying the database, as some information is only...
Definition world.cc:682
WorldHash GetWorldHash() const
Returns the world hash for this world.
Definition world.h:367
void Defragment(MemDb::TableId tableId)
Defragment an entity table.
Definition world.cc:1671
MemDb::RowId Migrate(Entity entity, MemDb::TableId newTable)
Migrate an entity from it's current table to a different table.
Definition world.cc:1581
static void Override(World *src, World *dst)
Copy src over dst without initializing components. This is extremely destructive.
Definition world.cc:2026
void ManageEntities()
Definition world.cc:626
TYPE * AddComponent(Entity entity)
Create a component. This queues the component in a command buffer to be added later.
Definition world.h:473
Util::Queue< DeallocInstanceCommand > deallocQueue
Stores all deferred deallocation commands.
Definition world.h:344
void * GetInstanceBuffer(MemDb::TableId const tableId, uint16_t partitionId, ComponentId const component)
Get a pointer to the first instance of a component in a partition of an entity table....
Definition world.cc:1329
void OnSave()
Definition world.cc:607
EntityCreatedCallback entityCreatedCallback
Callback invoked for every entity instance allocated in this world.
Definition world.h:329
Util::Array< AddStagedComponentCommand > addStagedQueue
Stores all deferred add staged component commands.
Definition world.h:346
bool ExportLevel(Util::String const &path)
Export the world as a level.
Definition world.cc:326
Memory::ArenaAllocator< 4096_KB > componentStageAllocator
Allocator for staged components.
Definition world.h:350
void OnLoad()
Definition world.cc:598
SizeT numEntities
Number of entities alive.
Definition world.h:327
MemDb::TableId defaultTableId
The default table that empty entities are instantiated into.
Definition world.h:358
void MarkAsModified(Game::Entity entity)
Mark an entity as modified in its table.
Definition world.cc:2067
void SetComponent(Entity entity, TYPE const &value)
Set the value of an entitys component.
Definition world.h:386
WorldHash hash
world hash
Definition world.h:338
void InitializeInstance(Entity entity)
Initialize all components on an allocated entity instance.
Definition world.cc:1479
Definition attribute.h:29
static SizeT TypeSize(AttributeId descriptor)
get type size by attribute id
Definition attributeregistry.h:247
static Attribute * GetAttribute(AttributeId descriptor)
get attribute description by id
Definition attributeregistry.h:229
Definition database.h:28
Represents a partition within a Table in MemDb.
Definition table.h:205
Allocates memory in chunks.
Definition arenaallocator.h:36
Nebula's smart pointer class which manages the life time of RefCounted objects.
Definition ptr.h:38
Nebula's dynamic array class.
Definition array.h:61
The Util::Blob class encapsulates a chunk of raw memory into a C++ object which can be copied,...
Definition blob.h:22
Nebula delegate class, allows to store a function, method or lambda call into a C++ object for later ...
Definition delegate.h:39
Implements a fixed size one-dimensional array.
Definition fixedarray.h:20
Nebula's queue class (a FIFO container).
Definition queue.h:22
Nebula's universal string class.
Definition string.h:50
#define n_assert2(exp, msg)
Definition debug.h:59
#define n_assert(exp)
Definition debug.h:58
Game::EditorState.
Definition graphicsmanager.h:66
MemDb::AttributeId ComponentId
Definition componentid.h:15
uint32_t Filter
Opaque filter identifier.
Definition filter.h:26
Util::Delegate< void(World *, Entity)> EntityCreatedCallback
Called for every entity instance allocated in a world.
Definition world.h:62
ComponentId GetComponentId()
Returns a component id, based on template type.
Definition component.h:136
WorldMode
Definition world.h:49
@ EditorMode
Definition world.h:50
@ PlayMode
Definition world.h:51
uint32_t WorldId
Definition entity.h:28
World * GetWorld(WorldHash hash)
returns a world by hash
Definition world.cc:35
ComponentId GetComponentId(Util::StringAtom name)
Returns a component id.
Definition component.h:155
ProcessorPhase PhaseForMode(WorldMode mode)
Definition world.h:56
ProcessorPhase
which world mode a processor is allowed to run in
Definition processor.h:24
@ PlayPhase
Definition processor.h:26
@ EditorPhase
Definition processor.h:25
Attribute.
Definition attribute.h:26
A quad tree designed to return regions of free 2D space.
Definition Random.cs:5
Contains data for components flagged with COMPONENTFLAG_DECAY, that has been deleted this frame.
Definition component.h:50
A dataset that contains views into category tables.
Definition dataset.h:23
An entity is essentially just an Id with some utility functions attached.
Definition entity.h:35
static constexpr Entity Invalid()
Definition entity.h:139
Maps an entity to a table and instance id.
Definition entity.h:88
Definition category.h:18
A component that stores the orientation of an entity.
Definition orientation.h:18
A component that stores the position of an entity in world space coordinates.
Definition position.h:19
A component that stores the scale of an entity.
Definition scale.h:18
ComponentId componentId
Definition world.h:263
IndexT next
The next command staged for the same entity, or InvalidIndex.
Definition world.h:268
SizeT dataSize
Definition world.h:264
void * data
Definition world.h:265
Game::Entity entity
Definition world.h:262
Game::Entity entity
Definition world.h:252
Game::Entity entity
Definition world.h:257
ComponentId componentId
Definition world.h:274
Entity entity
Definition world.h:273
Definition entity.h:29
column id
Definition tableid.h:38
row identifier
Definition tableid.h:18
Table identifier.
Definition tableid.h:14
int SizeT
Definition types.h:50
int IndexT
Definition types.h:49