-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEntityManager.h
More file actions
468 lines (387 loc) · 16.7 KB
/
EntityManager.h
File metadata and controls
468 lines (387 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#pragma once
#include "_Plugin.h"
#include <Urho3D/Core/NonCopyable.h>
#include <Urho3D/Core/Signal.h>
#include <Urho3D/Core/TypeTrait.h>
#include <Urho3D/Scene/LogicComponent.h>
#include <Urho3D/Scene/TrackedComponent.h>
#include <entt/entt.hpp>
#include <EASTL/unique_ptr.h>
// Support formatting for entt::entity.
template <> struct fmt::formatter<entt::entity>
{
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator
{
// TODO: Support formatting specifiers
return ctx.begin();
}
auto format(const entt::entity& value, format_context& ctx) const -> format_context::iterator
{
return fmt::format_to(
ctx.out(), "{}:{}", static_cast<unsigned>(entt::to_entity(value)), entt::to_version(value));
}
};
namespace Urho3D
{
class EntityReference;
/// Component that is used to tag currently materialized entities.
/// EntityReference is expected to be valid.
struct EntityMaterialized
{
WeakPtr<EntityReference> entityReference_;
};
/// Component that is used to tag entities with updated transforms.
/// It is up to the user to clear this component when it's not needed anymore.
struct EntityTransformDirty
{
static constexpr unsigned Version = 1;
void SerializeInBlock(Archive& archive, unsigned version) {}
bool RenderInspector() { return false; }
};
/// Interface to manage EnTT components.
class PLUGIN_CORE_ENTITYMANAGER_API EntityComponentFactory
{
public:
EntityComponentFactory(const ea::string& name);
virtual ~EntityComponentFactory() = default;
const ea::string& GetName() const { return name_; }
virtual bool IsEmpty() const = 0;
virtual unsigned GetVersion() const = 0;
virtual bool HasComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void CreateComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void DestroyComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void CopyComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities) = 0;
virtual void MoveComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities) = 0;
virtual void SerializeComponent(
Archive& archive, entt::registry& registry, entt::entity entity, unsigned version) = 0;
virtual void SerializeComponents(Archive& archive, entt::registry& registry, unsigned version) = 0;
virtual bool RenderUI(entt::registry& registry, entt::entity entity) = 0;
virtual void CommitActions(entt::registry& registry) = 0;
private:
ea::string name_;
};
/// Type-erased manager of component types for registry.
class PLUGIN_CORE_ENTITYMANAGER_API ComponentTypeManager : public MovableNonCopyable
{
public:
using EntityComponentFactoryVector = ea::vector<ea::unique_ptr<EntityComponentFactory>>;
/// Register new EnTT component type.
/// It should be done as soon as possible, preferably in the constructor of derived class.
void AddComponentType(ea::unique_ptr<EntityComponentFactory> factory);
template <class T> void AddComponentType(const ea::string& name);
template <class T> void AddComponentType();
EntityComponentFactory* FindComponentType(ea::string_view name) const;
const EntityComponentFactoryVector& GetComponentTypes() const { return componentFactories_; }
const EntityComponentFactoryVector& GetComponentTypesSorted();
/// Ensure order of factories for consistent output.
void EnsureComponentTypesSorted();
/// Serialize entire registry contents. All existing entities are overwritten.
void SerializeRegistry(Archive& archive, entt::registry& registry) const;
/// Serialize components of specific entity. Entity must exist. All existing components are overwritten.
void SerializeStandaloneEntity(Archive& archive, entt::registry& registry, entt::entity entity) const;
/// Move entities from registry to registry.
void MoveEntities(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, ea::vector<entt::entity>& toEntities) const;
/// Utilities.
/// @{
static unsigned GetEntityVersion(entt::entity entity);
static unsigned GetEntityIndex(entt::entity entity);
template <class T>
static void SerializeComponents(Archive& archive, const char* name, entt::registry& registry, unsigned version);
/// @}
private:
void SerializeEntities(Archive& archive, entt::registry& registry) const;
void SerializeUserComponents(Archive& archive, entt::registry& registry) const;
/// Comparator to sort entities by their index.
struct EntityIndexComparator
{
bool operator()(entt::entity lhs, entt::entity rhs) const
{
return ComponentTypeManager::GetEntityIndex(lhs) < ComponentTypeManager::GetEntityIndex(rhs);
}
};
private:
EntityComponentFactoryVector componentFactories_;
bool componentTypesSorted_{};
};
/// Subsystem that stores and manages EnTT entities.
/// Don't remove this component from the scene if you have any entities!
class PLUGIN_CORE_ENTITYMANAGER_API EntityManager
: public TrackedComponentRegistryBase
, public ComponentTypeManager
{
URHO3D_OBJECT(EntityManager, TrackedComponentRegistryBase);
public:
Signal<void(entt::registry& registry, entt::entity entity, EntityReference* reference)> OnEntityMaterialized;
Signal<void(entt::registry& registry, entt::entity entity, EntityReference* reference)> OnEntityDematerialized;
Signal<void(entt::registry& registry)> OnPostUpdateSynchronized;
EntityManager(Context* context);
static void RegisterObject(Context* context);
void ApplyAttributes() override;
bool HasAuxiliaryData() const override { return true; }
void SerializeAuxiliaryData(Archive& archive) override;
/// Support inspector UI.
/// @{
bool RenderManagerInspector();
bool RenderEntityInspector(entt::entity entity);
void CommitActions();
/// @}
/// Synchronize pending EntityReference additions with the registry.
void Synchronize();
bool IsEntityValid(entt::entity entity) const;
EntityReference* EntityToReference(entt::entity entity) const;
Node* EntityToNode(entt::entity entity) const;
entt::entity NodeToEntity(Node* node) const;
static Variant EntityToVariant(entt::entity entity);
static entt::entity VariantToEntity(const Variant& variant);
bool IsEntityMaterialized(entt::entity entity) const;
EntityReference* MaterializeEntity(entt::entity entity);
void DematerializeEntity(entt::entity entity);
/// Per-entity serialization. Use with caution.
/// @{
ByteVector EncodeEntity(entt::registry& registry, entt::entity entity);
void DecodeEntity(entt::registry& registry, entt::entity entity, const ByteVector& data);
ea::vector<entt::entity> GetEntities() const;
ByteVector EncodeEntity(entt::entity entity);
void DecodeEntity(entt::entity entity, const ByteVector& data);
void QueueDecodeEntity(EntityReference* entityReference, const ByteVector& data);
/// @}
/// Getters.
/// @{
entt::registry& Registry() { return registry_; }
/// @}
/// Attributes.
/// @{
void SetDataAttr(const ByteVector& data);
ByteVector GetDataAttr() const;
bool GetPlaceholderAttr() const { return false; }
void SetPlaceholderAttr(bool placeholder);
/// @}
protected:
/// Implement TrackedComponentRegistryBase.
/// @{
void OnComponentAdded(TrackedComponentBase* baseComponent) override;
void OnComponentRemoved(TrackedComponentBase* baseComponent) override;
void OnAddedToScene(Scene* scene) override;
void OnRemovedFromScene() override;
/// @}
/// Return display label for the entity.
virtual ea::string GetEntityLabel(entt::entity entity) const;
/// Post-update synchronization. Executed even if the Scene is paused.
virtual void ForcedPostUpdate();
entt::registry registry_;
private:
void EnsureEntitiesMaterialized();
void RenderEntityHeader(entt::entity entity);
EntityComponentFactory* RenderCreateComponent(entt::entity entity);
bool RenderExistingComponents(entt::entity entity);
ea::string entitiesContainerName_;
WeakPtr<Node> entitiesContainer_;
bool registryDirty_{};
ea::unordered_set<WeakPtr<EntityReference>> pendingEntitiesAdded_;
ea::vector<ea::pair<WeakPtr<EntityReference>, ByteVector>> pendingEntityDecodes_;
bool synchronizationInProgress_{};
bool suppressComponentEvents_{};
struct EditorUI
{
ea::vector<ea::pair<entt::entity, bool>> pendingMaterializations_;
ea::vector<ea::pair<entt::entity, EntityComponentFactory*>> pendingCreateComponents_;
ea::vector<ea::pair<entt::entity, EntityComponentFactory*>> pendingDestroyComponents_;
ea::vector<EntityComponentFactory*> pendingEditComponents_;
} ui_;
};
/// Check whether component has "RenderInspector" member function.
URHO3D_TYPE_TRAIT(HasRenderInspector, !!std::declval<T&>().RenderInspector());
/// Default implementation of EntityComponentFactory.
/// T is expected to have certain functions and static members.
template <class T> class DefaultEntityComponentFactory : public EntityComponentFactory
{
public:
using EntityComponentFactory::EntityComponentFactory;
/// Implement EntityComponentFactory.
/// @{
bool IsEmpty() const override { return std::is_empty_v<T>; }
unsigned GetVersion() const override { return T::Version; }
bool HasComponent(entt::registry& registry, entt::entity entity) override;
void CreateComponent(entt::registry& registry, entt::entity entity) override;
void DestroyComponent(entt::registry& registry, entt::entity entity) override;
void CopyComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities) override;
void MoveComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities) override;
void SerializeComponent(Archive& archive, entt::registry& registry, entt::entity entity, unsigned version) override;
void SerializeComponents(Archive& archive, entt::registry& registry, unsigned version) override;
bool RenderUI(entt::registry& registry, entt::entity entity) override;
void CommitActions(entt::registry& registry) override;
/// @}
private:
template <bool IsMove>
void CopyOrMoveComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities);
private:
ea::string name_;
struct PendingEditAction
{
entt::entity entity_;
T newValue_;
};
ea::vector<PendingEditAction> pendingEditActions_;
};
} // namespace Urho3D
namespace Urho3D
{
template <class T> void ComponentTypeManager::AddComponentType(const ea::string& name)
{
AddComponentType(ea::make_unique<DefaultEntityComponentFactory<T>>(name));
}
template <class T> void ComponentTypeManager::AddComponentType()
{
AddComponentType<T>(T::TypeName);
}
template <class T>
void ComponentTypeManager::SerializeComponents(
Archive& archive, const char* name, entt::registry& registry, unsigned version)
{
auto& storage = registry.storage<T>();
const auto numComponents = static_cast<unsigned>(storage.size());
const auto block = archive.OpenArrayBlock(name, numComponents);
if (archive.IsInput())
{
for (unsigned i = 0; i < block.GetSizeHint(); ++i)
{
const auto elementBlock = archive.OpenUnorderedBlock("component");
unsigned entityData = 0;
archive.Serialize("_entity", entityData);
const auto entity = static_cast<entt::entity>(entityData);
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.emplace_or_replace<T>(entity);
component.SerializeInBlock(archive, version);
}
else
{
registry.emplace_or_replace<T>(entity);
}
}
}
else
{
static thread_local ea::vector<entt::entity> entitiesBuffer;
auto& entities = entitiesBuffer;
const auto view = registry.view<T>();
entities.assign(view.begin(), view.end());
ea::sort(entities.begin(), entities.end(), EntityIndexComparator{});
for (const entt::entity entity : entities)
{
const auto elementBlock = archive.OpenUnorderedBlock("component");
auto entityData = static_cast<unsigned>(entity);
archive.Serialize("_entity", entityData);
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.get<T>(entity);
component.SerializeInBlock(archive, version);
}
};
}
}
template <class T> bool DefaultEntityComponentFactory<T>::HasComponent(entt::registry& registry, entt::entity entity)
{
const auto& storage = registry.storage<T>();
return storage.contains(entity);
}
template <class T> void DefaultEntityComponentFactory<T>::CreateComponent(entt::registry& registry, entt::entity entity)
{
(void)registry.emplace<T>(entity);
}
template <class T>
void DefaultEntityComponentFactory<T>::DestroyComponent(entt::registry& registry, entt::entity entity)
{
registry.remove<T>(entity);
}
template <class T>
void DefaultEntityComponentFactory<T>::SerializeComponent(
Archive& archive, entt::registry& registry, entt::entity entity, unsigned version)
{
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.get<T>(entity);
component.SerializeInBlock(archive, version);
}
}
template <class T>
void DefaultEntityComponentFactory<T>::SerializeComponents(Archive& archive, entt::registry& registry, unsigned version)
{
EntityManager::SerializeComponents<T>(archive, "components", registry, version);
}
template <class T> bool DefaultEntityComponentFactory<T>::RenderUI(entt::registry& registry, entt::entity entity)
{
if constexpr (!std::is_empty_v<T> && HasRenderInspector<T>::value)
{
T& component = registry.get<T>(entity);
const T backup = component;
if (component.RenderInspector())
{
PendingEditAction action;
action.entity_ = entity;
action.newValue_ = component;
component = backup;
pendingEditActions_.push_back(action);
return true;
}
}
return false;
}
template <class T> void DefaultEntityComponentFactory<T>::CommitActions(entt::registry& registry)
{
for (const PendingEditAction& action : pendingEditActions_)
{
if (!registry.valid(action.entity_))
{
URHO3D_LOGERROR("Cannot edit component '{}' in entity {}", GetName(), action.entity_);
continue;
}
registry.replace<T>(action.entity_, action.newValue_);
}
pendingEditActions_.clear();
}
template <class T>
void DefaultEntityComponentFactory<T>::CopyComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities)
{
CopyOrMoveComponents<false>(fromRegistry, toRegistry, fromEntities, toEntities);
}
template <class T>
void DefaultEntityComponentFactory<T>::MoveComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities)
{
CopyOrMoveComponents<true>(fromRegistry, toRegistry, fromEntities, toEntities);
}
template <class T>
template <bool IsMove>
void DefaultEntityComponentFactory<T>::CopyOrMoveComponents(entt::registry& fromRegistry, entt::registry& toRegistry,
const ea::vector<entt::entity>& fromEntities, const ea::vector<entt::entity>& toEntities)
{
URHO3D_ASSERT(fromEntities.size() == toEntities.size());
for (unsigned i = 0; i < fromEntities.size(); ++i)
{
const entt::entity fromEntity = fromEntities[i];
const entt::entity toEntity = toEntities[i];
auto& storage = fromRegistry.storage<T>();
if (!storage.contains(fromEntity))
continue;
if constexpr (!std::is_empty_v<T>)
{
if constexpr (IsMove)
toRegistry.emplace_or_replace<T>(toEntity, ea::move(fromRegistry.get<T>(fromEntity)));
else
toRegistry.emplace_or_replace<T>(toEntity, fromRegistry.get<T>(fromEntity));
}
else
{
toRegistry.emplace_or_replace<T>(toEntity);
}
}
}
} // namespace Urho3D