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/fourcc.h"
22
23namespace MemDb { class Database; }
24namespace Util { class Blob; }
25
26namespace Game
27{
28
29class PackedLevel;
30
32template <typename COMPONENT_TYPE>
33ComponentId RegisterType(ComponentRegisterInfo<COMPONENT_TYPE> info = {});
34
35//------------------------------------------------------------------------------
39{
41 TemplateId templateId = TemplateId::Invalid();
43 bool immediate = false;
44};
45
46//------------------------------------------------------------------------------
49class World
50{
51public:
52 // Generally, only the game server should create worlds
54 ~World();
55
56 WorldHash GetWorldHash() const;
57 WorldId GetWorldId() const;
58
60 Entity CreateEntity(bool immediate = true);
64 void DeleteEntity(Entity entity);
66 bool IsValid(Entity entity);
68 bool HasInstance(Entity entity);
72 bool HasComponent(Entity entity, ComponentId component);
74 template <typename TYPE>
75 bool HasComponent(Entity entity);
79 template <typename TYPE>
80 void RemoveComponent(Entity entity);
82 void RemoveComponent(Entity entity, ComponentId component);
84 template <typename TYPE>
85 void SetComponent(Entity entity, TYPE const& value);
87 template <typename TYPE>
88 TYPE GetComponent(Entity entity);
90 template <typename TYPE>
91 TYPE* AddComponent(Entity entity);
93 void* AddComponent(Entity entity, ComponentId component);
96
98 void SetComponentValue(Entity entity, ComponentId component, void* value, uint64_t size);
99
101 void ReinitializeComponent(Entity entity, ComponentId component, void* value, uint64_t size);
102
104 Dataset Query(Filter filter);
108
113
116
118 void MarkAsModified(Game::Entity entity);
119
123 void UnloadLevel(PackedLevel* level);
124
126 void ExportLevel(Util::String const& path);
127
128 // -- Internal methods -- Use with caution! --
129
131 static void Override(World* src, World* dst);
135 void DeallocateEntityId(Entity entity);
137 MemDb::RowId AllocateInstance(Entity entity, MemDb::TableId table, Util::Blob const* const data = nullptr);
141 MemDb::RowId AllocateInstance(Entity entity, TemplateId templateId, bool performInitialize);
142 void FinalizeAllocate(Entity entity);
144 void DeallocateInstance(MemDb::TableId table, MemDb::RowId instance);
146 void DeallocateInstance(Entity entity);
148 void Defragment(MemDb::TableId tableId);
150 void* GetInstanceBuffer(MemDb::TableId const tableId, uint16_t partitionId, ComponentId const component);
152 void* GetColumnData(MemDb::TableId const tableId, uint16_t partitionId, MemDb::ColumnIndex const column);
157
158 void RenderDebug();
159
160private:
161 friend class GameServer;
162 friend class BlueprintManager;
163 friend class PackedLevel;
164
186
187 // These functions are called from game server
188 void Start();
189 void BeginFrame();
190 void SimFrame();
191 void EndFrame();
192 void OnLoad();
193 void OnSave();
194 void ManageEntities();
195 void Reset();
196 void PrefilterProcessors();
198 bool Prefiltered() const;
200 void ClearDecayBuffers();
201
203
206
209
210 MemDb::RowId Migrate(Entity entity, MemDb::TableId newTable);
211 void Migrate(
212 Util::Array<Entity> const& entities,
213 MemDb::TableId fromTable,
214 MemDb::TableId newTable,
216 );
217
218 void DecayComponent(ComponentId component, MemDb::TableId tableId, MemDb::ColumnIndex column, MemDb::RowId instance);
219
221
224
247
250
252 bool cacheValid = false;
253
256
258};
259
260//------------------------------------------------------------------------------
263inline WorldHash
265{
266 return this->hash;
267}
268
269//------------------------------------------------------------------------------
272inline WorldId
274{
275 return this->worldId;
276}
277
278//------------------------------------------------------------------------------
281template <typename COMPONENT_TYPE>
284{
285 uint32_t componentFlags = 0;
286 componentFlags |= (uint32_t)COMPONENTFLAG_DECAY * (uint32_t)info.decay;
287
288 ComponentInterface* cInterface = new ComponentInterface(
289 COMPONENT_TYPE::Traits::name,
290 COMPONENT_TYPE(),
291 componentFlags
292 );
293 cInterface->Init = reinterpret_cast<ComponentInterface::ComponentInitFunc>(info.OnInit);
297 return cid;
298}
299
300//------------------------------------------------------------------------------
303template <typename TYPE>
304inline void
305World::SetComponent(Entity entity, TYPE const& value)
306{
307#if NEBULA_DEBUG
308 n_assert2(
309 !this->pipeline.IsRunningAsync(),
310 "Settings components in arbitrary entities while executing an async processor is currently not supported!"
311 );
312#endif
313
314#if NEBULA_DEBUG
315 n_assert2(
317 "SetComponent: Provided value's type is not the correct size for the given ComponentId."
318 );
319#endif
320 EntityMapping mapping = this->GetEntityMapping(entity);
321 TYPE* ptr = (TYPE*)this->GetInstanceBuffer(mapping.table, mapping.instance.partition, GetComponentId<TYPE>());
322 *(ptr + mapping.instance.index) = value;
323}
324
325//------------------------------------------------------------------------------
328template <typename TYPE>
329inline TYPE
331{
332#if NEBULA_DEBUG
333 n_assert2(
334 !this->pipeline.IsRunningAsync(), "Getting components from entities while executing an async processor is currently not supported!"
335 );
336#endif
337
338#if NEBULA_DEBUG
339 n_assert2(
341 "GetComponent: Provided value's type is not the correct size for the given ComponentId."
342 );
343#endif
344 EntityMapping mapping = this->GetEntityMapping(entity);
345 TYPE* ptr = (TYPE*)this->GetInstanceBuffer(mapping.table, mapping.instance.partition, GetComponentId<TYPE>());
346 return *(ptr + mapping.instance.index);
347}
348
349//------------------------------------------------------------------------------
352template <typename TYPE>
353inline void
355{
356#if NEBULA_DEBUG
357 n_assert2(
358 !this->pipeline.IsRunningAsync(),
359 "Removing components from entities while executing an async processor is currently not supported!"
360 );
361#endif
363 .entity = entity,
364 .componentId = Game::GetComponentId<TYPE>(),
365 };
366 this->removeComponentQueue.Append(cmd);
367}
368
369//------------------------------------------------------------------------------
372template <typename TYPE>
373inline bool
375{
376 return this->HasComponent(entity, Game::GetComponentId<TYPE>());
377}
378
379//------------------------------------------------------------------------------
382template <typename TYPE>
383inline TYPE*
385{
386 /*
387 We could possibly support this by either having thread local allocators and
388 staged queues and gathering after the processors have finished (must clear
389 allocators by issuing a separate job for this at the end of the frame), or by
390 just introducing a simple mutex.
391 */
392#if NEBULA_DEBUG
393 n_assert2(!this->pipeline.IsRunningAsync(), "Adding component to entities while in an async processor is currently not supported!");
394#endif
396#if NEBULA_DEBUG
397 n_assert(MemDb::AttributeRegistry::TypeSize(id) == sizeof(TYPE));
398 //n_assert(!this->HasComponent<TYPE>(entity));
399#endif
400 TYPE* data = this->componentStageAllocator.Alloc<TYPE>();
401 const void* defaultValue = MemDb::AttributeRegistry::DefaultValue(id);
402 Memory::Copy(defaultValue, data, sizeof(TYPE));
403
405 .entity = entity,
406 .componentId = id,
407 .dataSize = sizeof(TYPE),
408 .data = data,
409 };
410 this->addStagedQueue.Append(cmd);
411
413 ComponentInterface* cInterface;
414 cInterface = static_cast<ComponentInterface*>(attr);
415
416 if (cInterface->Init != nullptr)
417 {
418 // run initialization function if it exists.
419 cInterface->Init(this, entity, data);
420 }
421
422 return data;
423}
424
428
429template<> void World::SetComponent(Entity entity, Game::Position const&);
430template<> void World::SetComponent(Entity entity, Game::Orientation const&);
431template<> void World::SetComponent(Entity entity, Game::Scale const&);
432
433
434} // namespace Game
Loads the 'data:tables/blueprint.json' file and subsequently sets up categories based on the blueprin...
Definition blueprintmanager.h:31
static void Register(ComponentId component, DrawFunc)
Definition componentinspection.cc:55
These are registered to the attribute registry so that we can add more functionality to attributes.
Definition component.h:75
void(*)(Game::World *, Game::Entity, void *) ComponentInitFunc
Definition component.h:90
ComponentInitFunc Init
Definition component.h:91
static void Register(ComponentId component)
Definition componentserialization.h:70
Generation pool.
Definition entitypool.h:22
Definition frameevent.h:108
bool IsRunningAsync()
check if the pipeline is currently executing an async frame event batch
Definition frameevent.cc:472
The game server setups and runs the game world.
Definition gameserver.h:45
Definition level.h:23
Definition world.h:50
PackedLevel * PreloadLevel(Util::String const &path)
preload a level that can be instantiated
Definition world.cc:82
void MoveInstance(MemDb::Table::Partition *partition, MemDb::RowId from, MemDb::RowId to)
Definition world.cc:1350
Dataset Query(Filter filter)
Query the entity database using specified filter set. This does NOT wait for resources to be availabl...
Definition world.cc:1715
void AddStagedComponentsToEntity(Entity entity, AddStagedComponentCommand *cmds, SizeT numCmds)
Definition world.cc:882
Entity AllocateEntityId()
Allocate an entity id. Use this with caution!
Definition world.cc:394
bool componentInitializationEnabled
Disable if initialization of components is not required (ex. when running as editor db)
Definition world.h:156
EntityPool pool
used to allocate entity ids for this world
Definition world.h:226
Util::Array< RemoveComponentCommand > removeComponentQueue
Definition world.h:246
MemDb::RowId AllocateInstance(Entity entity, MemDb::TableId table, Util::Blob const *const data=nullptr)
Allocate an entity instance in a table. Use this with caution!
Definition world.cc:1105
ComponentDecayBuffer const GetDecayBuffer(ComponentId component)
Get a decay buffer for the given component.
Definition world.cc:740
Ptr< MemDb::Database > db
contains all entity instances
Definition world.h:232
Util::HashTable< BlueprintId, MemDb::TableId > blueprintToTableMap
maps from blueprint to a table that has the same signature
Definition world.h:238
void InitializeAllComponents(Entity entity, MemDb::TableId tableId, MemDb::RowId row)
Run OnInit on all components. Use with caution, since they can only be initialized once and the funct...
Definition world.cc:1147
WorldId GetWorldId() const
Definition world.h:273
bool HasInstance(Entity entity)
Check if an entity has an instance. It might be valid, but not have received an instance just after i...
Definition world.cc:774
TYPE GetComponent(Entity entity)
Get an entitys component.
Definition world.h:330
void PrefilterProcessors()
Definition world.cc:487
void ClearDecayBuffers()
Clears all decay buffers. This is called by the game server automatically.
Definition world.cc:752
void ExecuteAddComponentCommands()
dispatches all staged components to be added to entities
Definition world.cc:815
Entity CreateEntity(bool immediate=true)
Create a new empty entity.
Definition world.cc:566
void RenderDebug()
Definition world.cc:1461
bool cacheValid
set to true if the caches for the frame pipeline is valid
Definition world.h:252
Util::Queue< AllocateInstanceCommand > allocQueue
Definition world.h:240
bool HasComponent(Entity entity, ComponentId component)
Check if entity has a specific component. (SLOW!)
Definition world.cc:796
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:1404
void Reset()
Definition world.cc:547
void SimFrame()
Definition world.cc:443
void DeleteEntity(Entity entity)
Delete entity.
Definition world.cc:621
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:1422
void UnloadLevel(PackedLevel *level)
unload a preloaded level
Definition world.cc:207
~World()
Definition world.cc:73
FramePipeline pipeline
the frame pipeline for this world
Definition world.h:255
bool IsValid(Entity entity)
Check if an entity ID is still valid.
Definition world.cc:765
World(WorldHash hash, WorldId id)
Definition world.cc:41
void FinalizeAllocate(Entity entity)
Definition world.cc:1241
SizeT GetNumInstances(MemDb::TableId tid)
Get total number of instances in an entity table.
Definition world.cc:806
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:1027
MemDb::TableId CreateEntityTable(EntityTableCreateInfo const &info)
Create a table in the entity database that has a specific set of components.
Definition world.cc:1046
void DecayComponent(ComponentId component, MemDb::TableId tableId, MemDb::ColumnIndex column, MemDb::RowId instance)
Definition world.cc:643
void ExportLevel(Util::String const &path)
Export the world as a level.
Definition world.cc:216
EntityMapping GetEntityMapping(Entity entity)
Returns the entity mapping of an entity.
Definition world.cc:784
void RemoveComponentsFromEntity(Entity entity, RemoveComponentCommand *cmds, SizeT numCmds)
Definition world.cc:951
void RemoveComponent(Entity entity)
Remove a component from an entity.
Definition world.h:354
void ExecuteRemoveComponentCommands()
Definition world.cc:849
void DeallocateEntityId(Entity entity)
Deallocate an entity id. Use this with caution!
Definition world.cc:410
Util::Array< EntityMapping > entityMap
maps entity index to table+row pair
Definition world.h:230
FramePipeline & GetFramePipeline()
Get the frame pipeline.
Definition world.cc:1690
void BeginFrame()
Definition world.cc:433
WorldId worldId
world id
Definition world.h:236
void Start()
Definition world.cc:421
void EndFrame()
Definition world.cc:453
Ptr< MemDb::Database > GetDatabase()
Get the entity database. Be careful when directly modifying the database, as some information is only...
Definition world.cc:557
WorldHash GetWorldHash() const
Definition world.h:264
void Defragment(MemDb::TableId tableId)
Defragment an entity table.
Definition world.cc:1380
void DeallocateInstance(MemDb::TableId table, MemDb::RowId instance)
Deallocate an entity instance. Use this with caution!
Definition world.cc:1251
MemDb::RowId Migrate(Entity entity, MemDb::TableId newTable)
Definition world.cc:1289
static void Override(World *src, World *dst)
copies and overrides dst with src. This is extremely destructive - make sure you understand the impli...
Definition world.cc:1648
MemDb::RowId GetInstance(Entity entity)
Get instance of entity.
Definition world.cc:1037
void ManageEntities()
Definition world.cc:506
TYPE * AddComponent(Entity entity)
Create a component. This queues the component in a command buffer to be added later.
Definition world.h:384
bool Prefiltered() const
Check if the database is fully prefiltered.
Definition world.cc:497
Util::Queue< DeallocInstanceCommand > deallocQueue
Definition world.h:242
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:1009
void OnSave()
Definition world.cc:478
Util::Array< AddStagedComponentCommand > addStagedQueue
Definition world.h:244
Memory::ArenaAllocator< 4096_KB > componentStageAllocator
allocator for staged components
Definition world.h:249
void OnLoad()
Definition world.cc:469
SizeT numEntities
Number of entities alive.
Definition world.h:228
MemDb::TableId defaultTableId
Definition world.h:257
void MarkAsModified(Game::Entity entity)
Mark an entity as modified in its table.
Definition world.cc:1699
void SetComponent(Entity entity, TYPE const &value)
Set the value of an entitys component.
Definition world.h:305
WorldHash hash
world hash
Definition world.h:234
Definition attribute.h:29
static AttributeId Register(Util::StringAtom name, TYPE defaultValue, uint32_t flags=0)
register a type (templated)
Definition attributeregistry.h:99
static void const *const DefaultValue(AttributeId descriptor)
get attribute default value pointer
Definition attributeregistry.h:268
static SizeT TypeSize(AttributeId descriptor)
get type size by attribute id
Definition attributeregistry.h:246
static Attribute * GetAttribute(AttributeId descriptor)
get attribute description by id
Definition attributeregistry.h:228
Definition table.h:169
Allocates memory in chunks.
Definition arenaallocator.h:36
T * Alloc()
allocate new object, and calls constructor, but beware because this allocator does not run the destru...
Definition arenaallocator.h:186
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:60
The Util::Blob class encapsulates a chunk of raw memory into a C++ object which can be copied,...
Definition blob.h:22
Implements a fixed size one-dimensional array.
Definition fixedarray.h:20
Organizes key/value pairs by a hash code.
Definition hashtable.h:42
Nebula's queue class (a FIFO container).
Definition queue.h:28
#define n_assert2(exp, msg)
Definition debug.h:51
#define n_assert(exp)
Definition debug.h:50
Game::EditorState.
Definition orientation.h:7
ComponentId RegisterType(ComponentRegisterInfo< COMPONENT_TYPE > info={})
Register a component type.
Definition world.h:283
MemDb::AttributeId ComponentId
Definition componentid.h:15
@ COMPONENTFLAG_DECAY
Component will decay.
Definition component.h:38
uint32_t Filter
Opaque filter identifier.
Definition filter.h:26
void ComponentDrawFuncT(ComponentId component, void *data, bool *commit)
Definition componentinspection.h:72
ComponentId GetComponentId()
Returns a component id, based on template type.
Definition component.h:120
uint32_t WorldId
Definition entity.h:28
Attribute.
Definition attribute.h:26
void Copy(const void *from, void *to, size_t numBytes)
Copy a chunk of memory (note the argument order is different from memcpy()!!!)
Definition osxmemory.cc:213
A pinned array is an array which manages its own virtual memory.
Definition String.cs:6
Definition category.h:17
Contains data for components flagged with COMPONENTFLAG_DECAY, that has been deleted this frame.
Definition component.h:47
Used for registering component types to the game world.
Definition component.h:61
OnInitFunc OnInit
initialization function to run for the component, or nullptr if not needed.
Definition component.h:67
bool decay
Set to true if the component should end up in the decay buffer before being completely destroyed.
Definition component.h:65
A dataset that contains views into category tables.
Definition dataset.h:23
Definition world.h:39
TemplateId templateId
template to instantiate.
Definition world.h:41
bool immediate
set if the entity should be instantiated immediately or deferred until end of frame.
Definition world.h:43
An entity is essentially just an Id with some utility functions attached.
Definition entity.h:35
Maps an entity to a table and instance id.
Definition entity.h:87
MemDb::RowId instance
Definition entity.h:89
MemDb::TableId table
Definition entity.h:88
Definition category.h:21
Definition orientation.h:10
Definition position.h:10
Definition scale.h:10
Definition category.h:18
ComponentId componentId
Definition world.h:177
SizeT dataSize
Definition world.h:178
void * data
Definition world.h:179
Game::Entity entity
Definition world.h:176
Game::Entity entity
Definition world.h:167
TemplateId tid
Definition world.h:168
Game::Entity entity
Definition world.h:172
ComponentId componentId
Definition world.h:184
Entity entity
Definition world.h:183
Definition entity.h:29
Definition attributeid.h:19
column id
Definition tableid.h:38
row identifier
Definition tableid.h:18
uint16_t partition
Definition tableid.h:19
uint16_t index
Definition tableid.h:20
Table identifier.
Definition tableid.h:14
Nebula's universal string class.
Definition string.h:50
int SizeT
Definition types.h:49