summaryrefslogtreecommitdiffstats
path: root/deps/include/entt/entity/snapshot.hpp
blob: 46ebd28beaf43b23bba9b7e22ade799c8cf251ea (plain)
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#ifndef ENTT_ENTITY_SNAPSHOT_HPP
#define ENTT_ENTITY_SNAPSHOT_HPP

#include <cstddef>
#include <iterator>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../container/dense_map.hpp"
#include "../core/type_traits.hpp"
#include "entity.hpp"
#include "fwd.hpp"
#include "view.hpp"

namespace entt {

/*! @cond TURN_OFF_DOXYGEN */
namespace internal {

template<typename Registry>
void orphans(Registry &registry) {
    auto &storage = registry.template storage<typename Registry::entity_type>();

    for(auto entt: storage) {
        if(registry.orphan(entt)) {
            storage.erase(entt);
        }
    }
}

} // namespace internal
/*! @endcond */

/**
 * @brief Utility class to create snapshots from a registry.
 *
 * A _snapshot_ can be either a dump of the entire registry or a narrower
 * selection of elements of interest.<br/>
 * This type can be used in both cases if provided with a correctly configured
 * output archive.
 *
 * @tparam Registry Basic registry type.
 */
template<typename Registry>
class basic_snapshot {
    static_assert(!std::is_const_v<Registry>, "Non-const registry type required");
    using traits_type = entt_traits<typename Registry::entity_type>;

public:
    /*! Basic registry type. */
    using registry_type = Registry;
    /*! @brief Underlying entity identifier. */
    using entity_type = typename registry_type::entity_type;

    /**
     * @brief Constructs an instance that is bound to a given registry.
     * @param source A valid reference to a registry.
     */
    basic_snapshot(const registry_type &source) noexcept
        : reg{&source} {}

    /*! @brief Default copy constructor, deleted on purpose. */
    basic_snapshot(const basic_snapshot &) = delete;

    /*! @brief Default move constructor. */
    basic_snapshot(basic_snapshot &&) noexcept = default;

    /*! @brief Default destructor. */
    ~basic_snapshot() noexcept = default;

    /**
     * @brief Default copy assignment operator, deleted on purpose.
     * @return This snapshot.
     */
    basic_snapshot &operator=(const basic_snapshot &) = delete;

    /**
     * @brief Default move assignment operator.
     * @return This snapshot.
     */
    basic_snapshot &operator=(basic_snapshot &&) noexcept = default;

    /**
     * @brief Serializes all elements of a type with associated identifiers.
     * @tparam Type Type of elements to serialize.
     * @tparam Archive Type of output archive.
     * @param archive A valid reference to an output archive.
     * @param id Optional name used to map the storage within the registry.
     * @return An object of this type to continue creating the snapshot.
     */
    template<typename Type, typename Archive>
    const basic_snapshot &get(Archive &archive, const id_type id = type_hash<Type>::value()) const {
        if(const auto *storage = reg->template storage<Type>(id); storage) {
            const typename registry_type::common_type &base = *storage;

            archive(static_cast<typename traits_type::entity_type>(storage->size()));

            if constexpr(std::is_same_v<Type, entity_type>) {
                archive(static_cast<typename traits_type::entity_type>(storage->free_list()));

                for(auto first = base.rbegin(), last = base.rend(); first != last; ++first) {
                    archive(*first);
                }
            } else if constexpr(registry_type::template storage_for_type<Type>::storage_policy == deletion_policy::in_place) {
                for(auto it = base.rbegin(), last = base.rend(); it != last; ++it) {
                    if(const auto entt = *it; entt == tombstone) {
                        archive(static_cast<entity_type>(null));
                    } else {
                        archive(entt);
                        std::apply([&archive](auto &&...args) { (archive(std::forward<decltype(args)>(args)), ...); }, storage->get_as_tuple(entt));
                    }
                }
            } else {
                for(auto elem: storage->reach()) {
                    std::apply([&archive](auto &&...args) { (archive(std::forward<decltype(args)>(args)), ...); }, elem);
                }
            }
        } else {
            archive(typename traits_type::entity_type{});
        }

        return *this;
    }

    /**
     * @brief Serializes all elements of a type with associated identifiers for
     * the entities in a range.
     * @tparam Type Type of elements to serialize.
     * @tparam Archive Type of output archive.
     * @tparam It Type of input iterator.
     * @param archive A valid reference to an output archive.
     * @param first An iterator to the first element of the range to serialize.
     * @param last An iterator past the last element of the range to serialize.
     * @param id Optional name used to map the storage within the registry.
     * @return An object of this type to continue creating the snapshot.
     */
    template<typename Type, typename Archive, typename It>
    const basic_snapshot &get(Archive &archive, It first, It last, const id_type id = type_hash<Type>::value()) const {
        static_assert(!std::is_same_v<Type, entity_type>, "Entity types not supported");

        if(const auto *storage = reg->template storage<Type>(id); storage && !storage->empty()) {
            archive(static_cast<typename traits_type::entity_type>(std::distance(first, last)));

            for(; first != last; ++first) {
                if(const auto entt = *first; storage->contains(entt)) {
                    archive(entt);
                    std::apply([&archive](auto &&...args) { (archive(std::forward<decltype(args)>(args)), ...); }, storage->get_as_tuple(entt));
                } else {
                    archive(static_cast<entity_type>(null));
                }
            }
        } else {
            archive(typename traits_type::entity_type{});
        }

        return *this;
    }

private:
    const registry_type *reg;
};

/**
 * @brief Utility class to restore a snapshot as a whole.
 *
 * A snapshot loader requires that the destination registry be empty and loads
 * all the data at once while keeping intact the identifiers that the entities
 * originally had.<br/>
 * An example of use is the implementation of a save/restore utility.
 *
 * @tparam Registry Basic registry type.
 */
template<typename Registry>
class basic_snapshot_loader {
    static_assert(!std::is_const_v<Registry>, "Non-const registry type required");
    using traits_type = entt_traits<typename Registry::entity_type>;

public:
    /*! Basic registry type. */
    using registry_type = Registry;
    /*! @brief Underlying entity identifier. */
    using entity_type = typename registry_type::entity_type;

    /**
     * @brief Constructs an instance that is bound to a given registry.
     * @param source A valid reference to a registry.
     */
    basic_snapshot_loader(registry_type &source) noexcept
        : reg{&source} {
        // restoring a snapshot as a whole requires a clean registry
        ENTT_ASSERT(reg->template storage<entity_type>().free_list() == 0u, "Registry must be empty");
    }

    /*! @brief Default copy constructor, deleted on purpose. */
    basic_snapshot_loader(const basic_snapshot_loader &) = delete;

    /*! @brief Default move constructor. */
    basic_snapshot_loader(basic_snapshot_loader &&) noexcept = default;

    /*! @brief Default destructor. */
    ~basic_snapshot_loader() noexcept = default;

    /**
     * @brief Default copy assignment operator, deleted on purpose.
     * @return This loader.
     */
    basic_snapshot_loader &operator=(const basic_snapshot_loader &) = delete;

    /**
     * @brief Default move assignment operator.
     * @return This loader.
     */
    basic_snapshot_loader &operator=(basic_snapshot_loader &&) noexcept = default;

    /**
     * @brief Restores all elements of a type with associated identifiers.
     * @tparam Type Type of elements to restore.
     * @tparam Archive Type of input archive.
     * @param archive A valid reference to an input archive.
     * @param id Optional name used to map the storage within the registry.
     * @return A valid loader to continue restoring data.
     */
    template<typename Type, typename Archive>
    basic_snapshot_loader &get(Archive &archive, const id_type id = type_hash<Type>::value()) {
        auto &storage = reg->template storage<Type>(id);
        typename traits_type::entity_type length{};

        archive(length);

        if constexpr(std::is_same_v<Type, entity_type>) {
            typename traits_type::entity_type count{};

            storage.reserve(length);
            archive(count);

            for(entity_type entity = null; length; --length) {
                archive(entity);
                storage.emplace(entity);
            }

            storage.free_list(count);
        } else {
            auto &other = reg->template storage<entity_type>();
            entity_type entt{null};

            while(length--) {
                if(archive(entt); entt != null) {
                    const auto entity = other.contains(entt) ? entt : other.emplace(entt);
                    ENTT_ASSERT(entity == entt, "Entity not available for use");

                    if constexpr(std::tuple_size_v<decltype(storage.get_as_tuple({}))> == 0u) {
                        storage.emplace(entity);
                    } else {
                        Type elem{};
                        archive(elem);
                        storage.emplace(entity, std::move(elem));
                    }
                }
            }
        }

        return *this;
    }

    /**
     * @brief Destroys those entities that have no elements.
     *
     * In case all the entities were serialized but only part of the elements
     * was saved, it could happen that some of the entities have no elements
     * once restored.<br/>
     * This function helps to identify and destroy those entities.
     *
     * @return A valid loader to continue restoring data.
     */
    basic_snapshot_loader &orphans() {
        internal::orphans(*reg);
        return *this;
    }

private:
    registry_type *reg;
};

/**
 * @brief Utility class for _continuous loading_.
 *
 * A _continuous loader_ is designed to load data from a source registry to a
 * (possibly) non-empty destination. The loader can accommodate in a registry
 * more than one snapshot in a sort of _continuous loading_ that updates the
 * destination one step at a time.<br/>
 * Identifiers that entities originally had are not transferred to the target.
 * Instead, the loader maps remote identifiers to local ones while restoring a
 * snapshot.<br/>
 * An example of use is the implementation of a client-server application with
 * the requirement of transferring somehow parts of the representation side to
 * side.
 *
 * @tparam Registry Basic registry type.
 */
template<typename Registry>
class basic_continuous_loader {
    static_assert(!std::is_const_v<Registry>, "Non-const registry type required");
    using traits_type = entt_traits<typename Registry::entity_type>;

    void restore(typename Registry::entity_type entt) {
        if(const auto entity = to_entity(entt); remloc.contains(entity) && remloc[entity].first == entt) {
            if(!reg->valid(remloc[entity].second)) {
                remloc[entity].second = reg->create();
            }
        } else {
            remloc.insert_or_assign(entity, std::make_pair(entt, reg->create()));
        }
    }

    template<typename Container>
    auto update(int, Container &container) -> decltype(typename Container::mapped_type{}, void()) {
        // map like container
        Container other;

        for(auto &&pair: container) {
            using first_type = std::remove_const_t<typename std::decay_t<decltype(pair)>::first_type>;
            using second_type = typename std::decay_t<decltype(pair)>::second_type;

            if constexpr(std::is_same_v<first_type, entity_type> && std::is_same_v<second_type, entity_type>) {
                other.emplace(map(pair.first), map(pair.second));
            } else if constexpr(std::is_same_v<first_type, entity_type>) {
                other.emplace(map(pair.first), std::move(pair.second));
            } else {
                static_assert(std::is_same_v<second_type, entity_type>, "Neither the key nor the value are of entity type");
                other.emplace(std::move(pair.first), map(pair.second));
            }
        }

        using std::swap;
        swap(container, other);
    }

    template<typename Container>
    auto update(char, Container &container) -> decltype(typename Container::value_type{}, void()) {
        // vector like container
        static_assert(std::is_same_v<typename Container::value_type, entity_type>, "Invalid value type");

        for(auto &&entt: container) {
            entt = map(entt);
        }
    }

    template<typename Component, typename Other, typename Member>
    void update([[maybe_unused]] Component &instance, [[maybe_unused]] Member Other::*member) {
        if constexpr(!std::is_same_v<Component, Other>) {
            return;
        } else if constexpr(std::is_same_v<Member, entity_type>) {
            instance.*member = map(instance.*member);
        } else {
            // maybe a container? let's try...
            update(0, instance.*member);
        }
    }

public:
    /*! Basic registry type. */
    using registry_type = Registry;
    /*! @brief Underlying entity identifier. */
    using entity_type = typename registry_type::entity_type;

    /**
     * @brief Constructs an instance that is bound to a given registry.
     * @param source A valid reference to a registry.
     */
    basic_continuous_loader(registry_type &source) noexcept
        : remloc{source.get_allocator()},
          reg{&source} {}

    /*! @brief Default copy constructor, deleted on purpose. */
    basic_continuous_loader(const basic_continuous_loader &) = delete;

    /*! @brief Default move constructor. */
    basic_continuous_loader(basic_continuous_loader &&) noexcept = default;

    /*! @brief Default destructor. */
    ~basic_continuous_loader() noexcept = default;

    /**
     * @brief Default copy assignment operator, deleted on purpose.
     * @return This loader.
     */
    basic_continuous_loader &operator=(const basic_continuous_loader &) = delete;

    /**
     * @brief Default move assignment operator.
     * @return This loader.
     */
    basic_continuous_loader &operator=(basic_continuous_loader &&) noexcept = default;

    /**
     * @brief Restores all elements of a type with associated identifiers.
     *
     * It creates local counterparts for remote elements as needed.<br/>
     * Members are either data members of type entity_type or containers of
     * entities. In both cases, a loader visits them and replaces entities with
     * their local counterpart.
     *
     * @tparam Type Type of elements to restore.
     * @tparam Archive Type of input archive.
     * @param archive A valid reference to an input archive.
     * @param id Optional name used to map the storage within the registry.
     * @return A valid loader to continue restoring data.
     */
    template<typename Type, typename Archive>
    basic_continuous_loader &get(Archive &archive, const id_type id = type_hash<Type>::value()) {
        auto &storage = reg->template storage<Type>(id);
        typename traits_type::entity_type length{};
        entity_type entt{null};

        archive(length);

        if constexpr(std::is_same_v<Type, entity_type>) {
            typename traits_type::entity_type in_use{};

            storage.reserve(length);
            archive(in_use);

            for(std::size_t pos{}; pos < in_use; ++pos) {
                archive(entt);
                restore(entt);
            }

            for(std::size_t pos = in_use; pos < length; ++pos) {
                archive(entt);

                if(const auto entity = to_entity(entt); remloc.contains(entity)) {
                    if(reg->valid(remloc[entity].second)) {
                        reg->destroy(remloc[entity].second);
                    }

                    remloc.erase(entity);
                }
            }
        } else {
            for(auto &&ref: remloc) {
                storage.remove(ref.second.second);
            }

            while(length--) {
                if(archive(entt); entt != null) {
                    restore(entt);

                    if constexpr(std::tuple_size_v<decltype(storage.get_as_tuple({}))> == 0u) {
                        storage.emplace(map(entt));
                    } else {
                        Type elem{};
                        archive(elem);
                        storage.emplace(map(entt), std::move(elem));
                    }
                }
            }
        }

        return *this;
    }

    /**
     * @brief Destroys those entities that have no elements.
     *
     * In case all the entities were serialized but only part of the elements
     * was saved, it could happen that some of the entities have no elements
     * once restored.<br/>
     * This function helps to identify and destroy those entities.
     *
     * @return A non-const reference to this loader.
     */
    basic_continuous_loader &orphans() {
        internal::orphans(*reg);
        return *this;
    }

    /**
     * @brief Tests if a loader knows about a given entity.
     * @param entt A valid identifier.
     * @return True if `entity` is managed by the loader, false otherwise.
     */
    [[nodiscard]] bool contains(entity_type entt) const noexcept {
        const auto it = remloc.find(to_entity(entt));
        return it != remloc.cend() && it->second.first == entt;
    }

    /**
     * @brief Returns the identifier to which an entity refers.
     * @param entt A valid identifier.
     * @return The local identifier if any, the null entity otherwise.
     */
    [[nodiscard]] entity_type map(entity_type entt) const noexcept {
        if(const auto it = remloc.find(to_entity(entt)); it != remloc.cend() && it->second.first == entt) {
            return it->second.second;
        }

        return null;
    }

private:
    dense_map<typename traits_type::entity_type, std::pair<entity_type, entity_type>> remloc;
    registry_type *reg;
};

} // namespace entt

#endif