Compare commits

..

295 Commits

Author SHA1 Message Date
Michele Caini
bd83fba6cd updated version 2018-08-02 17:17:09 +02:00
Michele Caini
15b9255a25 fix #120 2018-08-02 16:55:03 +02:00
Michele Caini
6794d21487 one shot bubble sort alg 2018-07-31 09:11:18 +02:00
Michele Caini
118c4432ec typo 2018-07-24 09:25:01 +02:00
Michele Caini
ccda429bf1 Update README.md 2018-07-23 12:10:48 +02:00
Michele Caini
590937d2a0 added Registry::entity 2018-07-20 22:17:18 +02:00
Michele Caini
241827dd80 added gitter badge 2018-07-20 22:03:24 +02:00
Michele Caini
77b4e0b4bd EnTT in action: Face Smash 2018-07-18 15:01:36 +02:00
Michele Caini
6a53cb32d8 updated TODO 2018-07-18 14:08:30 +02:00
Michele Caini
f12ff3b15e fix #116 2018-07-18 14:07:48 +02:00
Michele Caini
69ad8676b7 added USE_ASAN option 2018-07-18 14:07:43 +02:00
Michele Caini
d0fd756f6b logo + review doc 2018-07-12 15:30:52 +02:00
Michele Caini
7f8ab67e9e performance improvements 2018-07-09 16:48:35 +02:00
Michele Caini
0e68bb3d2c added entt::label 2018-07-07 13:40:20 +02:00
Michele Caini
d5b3933752 updated README (added a note on EnTT and shared libraries - see #111) 2018-07-05 16:14:42 +02:00
Michele Caini
0b7206a92d review: README 2018-07-04 13:42:37 +02:00
Michele Caini
e875f306fd added FIND_GTEST_PACKAGE to force using system-wide gtest version (#106) 2018-07-03 22:09:28 +02:00
Michele Caini
8ed5e5ee28 updated cmake min version 2018-07-03 16:57:46 +02:00
Indi Kernick
948b0d40f6 Update packages with Travis-CI (#110) 2018-07-03 12:57:36 +02:00
David Kalnischkies
48f4feb7a7 Fix README: identifiers are accessed via type<>() 2018-07-02 13:29:03 +02:00
Michele Caini
ddc0a32bbc fix: runtime view (#108) 2018-07-02 08:40:30 +02:00
Michele Caini
10a7c54364 runtime view 2018-06-28 14:31:04 +02:00
Michele Caini
a66fa9d844 review: capacity 2018-06-28 08:36:24 +02:00
Michele Caini
a16f2ac15c fixed build system 2018-06-27 22:53:21 +02:00
Michele Caini
b699797a40 naming convention 2018-06-25 14:02:31 +02:00
Michele Caini
a6e9520d06 updated TODO 2018-06-25 13:16:11 +02:00
Michele Caini
f8310b1296 added monostate (built-in config system) 2018-06-23 19:43:22 +02:00
Michele Caini
353bf99cd5 now working with vs2017 (again) 2018-06-22 14:46:43 +02:00
Michele Caini
a478e4acc9 fixed compilation errors and suppressed warnings with clang 2018-06-22 14:16:02 +02:00
Michele Caini
d810e0ba7d review ident 2018-06-22 09:59:03 +02:00
Michele Caini
1e51ffdb72 user defined string literal for hashed strings 2018-06-20 17:08:14 +02:00
Michele Caini
7da1d1fc64 minor changes 2018-06-19 15:36:21 +02:00
Michele Caini
957697c383 review: delegate (see #101 and #102) 2018-06-18 17:10:31 +02:00
Michele Caini
107eb72225 updated TODO 2018-06-18 13:25:34 +02:00
Michele Caini
810b77f9da use null entity everywhere 2018-06-18 08:34:27 +02:00
Michele Caini
5e3bc2049b clean up 2018-06-14 14:48:19 +02:00
Michele Caini
229500347d review: process scheduler 2018-06-14 14:46:39 +02:00
Michele Caini
1f461db0a1 minor changes 2018-06-13 23:33:47 +02:00
Malte
6c55aafee3 Export CMake Config file and "modernize" CMake scripts (#87)
* CMake modifications and Config file generation

* CMake minor style changes

* Get rid of commented lines, fix indentation

* Respect Windows conventions for CMake config directory, Fix error with Config Version file, Export CMake package

* Add CMake option for use of ENTT_COMPILE_OPTIONS, Add CMake option for using libc++, Remove  from EnTT target and move it to test targets

* Fix indentation

* Fix indentation (again)

* Fix Windows problems with compile option -Wall in not using it on Windows

* Improved generator expression
The problem with -Wall is not due to the platform but due to the compiler MSVC

* Set compatibility for ConfigVersion file to AnyNewerVersion, Add PATH_VARS CMAKE_INSTALL_INCLUDE_DIR of configure_package_config_file, Remove redundant options, correct target_include_directory for INSTALL_INTERFACE, set the Version in EnTTConfig file and check CMake version

* Add missing closing brace, Add a special config file for the build tree
2018-06-13 14:04:05 +02:00
Michele Caini
d57e55b719 improved sort 2018-06-12 22:32:11 +02:00
Michele Caini
bf772e5fe5 docs 2018-06-12 13:00:33 +02:00
Michele Caini
413f3356ce updated README 2018-06-12 08:46:05 +02:00
Michele Caini
f147326fe0 typo 2018-06-11 14:50:43 +02:00
Michele Caini
30c59644b6 minor changes 2018-06-11 13:57:37 +02:00
Michele Caini
3fa5acf2e6 updated TOC 2018-06-11 08:26:53 +02:00
Michele Caini
3e6ded8823 more on destroy 2018-06-11 08:24:48 +02:00
Michele Caini
612017aaa2 null entity 2018-06-11 08:23:07 +02:00
Michele Caini
ef57d7e7b6 removed wrong noexcept 2018-06-10 00:10:12 +02:00
Michele Caini
a8d0db5036 updated README 2018-06-09 23:51:57 +02:00
Michele Caini
ad6b5f8fc1 fixed tests 2018-06-09 23:51:48 +02:00
Michele Caini
e3cb6a0aec minor changes 2018-06-09 21:58:49 +02:00
Sztergbaum Roman
cbf18a7dc4 fix warning on windows C4267 (#97) 2018-06-09 21:49:33 +02:00
Michele Caini
01559410a9 updated TODO 2018-06-09 12:26:59 +02:00
Michele Caini
f2ab94fa7f added operator[] to sparse set and views 2018-06-09 00:36:22 +02:00
Michele Caini
d7394a8369 more on prototype 2018-06-08 23:03:05 +02:00
Michele Caini
9feef11d6f cleanup + tests 2018-06-08 22:58:12 +02:00
Michele Caini
dc4e5ddc3c review: iterators (sparse set/view) 2018-06-08 22:30:50 +02:00
Michele Caini
8600781bb6 fixed doc + minor changes 2018-06-08 19:04:19 +02:00
Michele Caini
bdc7bbdc9d DefaultPrototype depends on DefaultRegistry now 2018-06-06 14:39:56 +02:00
Michele Caini
73badef594 updated gtest (#92) 2018-06-06 13:42:09 +02:00
Michele Caini
9474e6c08c updated prototype (#91) 2018-06-05 08:38:27 +02:00
Michele Caini
653ded0e6f updated version 2018-06-04 08:52:10 +02:00
Michele Caini
e34bec7dee cloning an entity is no longer allowed 2018-06-04 08:49:13 +02:00
Michele Caini
610b560fb5 typo 2018-06-03 22:24:45 +02:00
Michele Caini
0a03ddb8a7 typo 2018-06-03 22:17:06 +02:00
Michele Caini
f31790631a fixed include 2018-06-03 22:10:33 +02:00
Michele Caini
e07128760e review: prototype (#89) 2018-06-03 19:06:12 +02:00
Michele Caini
dd02ae313d minor changes 2018-06-02 17:06:44 +02:00
Michele Caini
d14b0b6843 updated version 2018-05-30 22:46:47 +02:00
Michele Caini
f763c8a777 docs 2018-05-30 22:40:06 +02:00
Michele Caini
4231b040d8 documented an already existent feature (#86) 2018-05-30 22:19:04 +02:00
Michele Caini
67c587e673 updated README.md 2018-05-23 23:35:39 +02:00
Michele Caini
3978e24fd8 added CONTRIBUTING.md 2018-05-23 23:12:23 +02:00
Michele Caini
c45de0c032 tests + bug fixing 2018-05-23 12:28:10 +02:00
Michele Caini
ff935efea1 updated README 2018-05-23 12:27:53 +02:00
Michele Caini
808464f47d more on save/restore (#67) 2018-05-23 12:26:53 +02:00
Michele Caini
c986a6c4dd added clone functionality 2018-05-22 22:49:24 +02:00
Michele Caini
17c0479343 minor changes 2018-05-22 22:45:09 +02:00
Michele Caini
d93238912a workaround for an ICE of g++-5 (see #79) 2018-05-18 09:27:57 +02:00
Michele Caini
d6ef0956e6 performance improvements 2018-05-17 17:47:02 +02:00
Michele Caini
05db0aad29 fixed constness of iterators' member functions 2018-05-16 17:04:44 +02:00
Michele Caini
89bbdfa1fe benchmark: clean up 2018-05-16 16:59:45 +02:00
Michele Caini
871bda6198 fixed toc 2018-05-15 23:30:45 +02:00
Michele Caini
20732c9206 added const begin/end on views + tests 2018-05-15 22:51:47 +02:00
Michele Caini
2a34a3ebb6 fixed and added more tests for prototype 2018-05-15 22:31:27 +02:00
Michele Caini
3f04247a53 fixed errors with vs2017 + const begin/end on iterators for sparse set 2018-05-15 22:21:51 +02:00
Michele Caini
ca0a1f8f8b review: multi component standard view 2018-05-15 17:30:22 +02:00
Michele Caini
d8a9f0ca12 minor changes 2018-05-15 17:29:05 +02:00
Michele Caini
c2116b841e fixed typo 2018-05-15 14:16:24 +02:00
Michele Caini
700cf69f18 prefer a clean api instead of cumbersome ones 2018-05-11 23:19:11 +02:00
Michele Caini
ed5dee5218 fixed error with msvc - logic flipped upside down :-( 2018-05-11 22:51:50 +02:00
Michele Caini
b224dfdfac trying to work around msvc limitations 2018-05-11 22:25:03 +02:00
Michele Caini
e7da68547f fixed errors with clang 2018-05-11 22:24:10 +02:00
Michele Caini
9a785ceb2e added prototype class 2018-05-11 22:12:43 +02:00
Indi Kernick
fca1cd5a1c Implement entt::Prototype (#74)
first draft - to be reviewed
2018-05-08 13:37:21 +02:00
Michele Caini
24b862e32e more flexible 2018-05-06 13:58:50 +02:00
Michele Caini
2ec9043cf2 fixed comments 2018-05-04 17:18:53 +02:00
Michele Caini
1102d63469 fix #73 2018-05-02 22:50:55 +02:00
Michele Caini
b89f39d78c added has for tag + entity to test ownership 2018-05-02 17:07:20 +02:00
Michele Caini
7ba479c9c9 minor changes 2018-05-02 13:17:50 +02:00
Michele Caini
8ad6a2980c updated doc 2018-05-01 17:32:11 +02:00
Michele Caini
d3b6ed78d9 custom sort function (#72) 2018-04-30 17:14:36 +02:00
Michele Caini
8bd5605c2a now works also with VS2017 and GCC6 2018-04-27 23:19:08 +02:00
Michele Caini
08dc2fcf33 performance improvement 2018-04-27 15:27:16 +02:00
Michele Caini
caa8d16371 updated README 2018-04-24 14:01:18 +02:00
Michele Caini
bce92b3d85 updated README + AUTHORS 2018-04-22 23:23:15 +02:00
Michele Caini
67858bf300 faster accommodate 2018-04-22 13:32:38 +02:00
Michele Caini
7157e7e77d minor changes 2018-04-20 17:11:57 +02:00
Michele Caini
cf5074bdc5 added Registry::data/::raw 2018-04-20 16:23:39 +02:00
Michele Caini
fda44063ce removed Registry::persistent/Registry::raw 2018-04-20 15:32:30 +02:00
Michele Caini
f9becda02c more tests 2018-04-20 14:57:21 +02:00
Michele Caini
fb9fc952c6 more tests 2018-04-20 14:28:40 +02:00
Michele Caini
18451edfe9 review: views and sparse sets 2018-04-20 13:17:50 +02:00
Michele Caini
8c73cac72f added ENTT_NOEXCEPT macro to fully disable exception handling (ie required with UE4) 2018-04-18 16:36:14 +02:00
Michele Caini
c54cedf14b readme: updated benchmarks 2018-04-18 16:16:15 +02:00
Michele Caini
8ef4cdc9c3 improvements 2018-04-18 13:48:50 +02:00
Michele Caini
c0213e84f6 signals on tags 2018-04-16 17:14:22 +02:00
Michele Caini
29de6d89d4 improvements 2018-04-13 22:54:20 +02:00
Michele Caini
c9bf38ce36 fixed dispatcher + minor changes 2018-04-13 14:01:34 +02:00
Michele Caini
338eb75bab review: actor + tests 2018-04-12 08:18:10 +02:00
Michele Caini
31b1b453b0 updated doc and tests 2018-04-10 15:12:42 +02:00
Michele Caini
aaf0e145eb fixed - no more anonymous namespaces 2018-04-10 11:25:17 +02:00
Michele Caini
089b3e13fd no more anonymous namespaces 2018-04-10 09:00:15 +02:00
Michele Caini
e9da2ce12a (maybe) fixed 2018-04-10 08:45:54 +02:00
Michele Caini
92048ac17b removed signal + added dependency function(s) 2018-04-09 23:26:39 +02:00
Michele Caini
5e8561a578 more on tags and components 2018-04-09 08:14:35 +02:00
Michele Caini
d2f5e13074 typo 2018-04-08 23:25:32 +02:00
Michele Caini
820178f006 tag dispatching to disambiguate tags and components (#65) 2018-04-07 00:29:09 +02:00
Michele Caini
0a36a91e6d review + docs 2018-04-06 23:30:13 +02:00
Michele Caini
5013a92795 review snapshot/loaders 2018-04-06 22:08:23 +02:00
Michele Caini
d81ecfec32 removed extra create functions from the registry (#52) 2018-04-06 22:06:44 +02:00
Michele Caini
e99d7e2c3c signals on component creation/destruction (#62) 2018-04-06 22:04:58 +02:00
Michele Caini
d417984ff3 review: iterators + fixed bug on raw views 2018-03-30 14:54:14 +02:00
Michele Caini
d38b3e641b added a note about thread safety (see #64) 2018-03-29 23:38:50 +02:00
Michele Caini
28ce491dd5 review sigh + added set/move for tags 2018-03-29 22:30:23 +02:00
Michele Caini
c260d72125 fixed typo 2018-03-28 22:35:30 +02:00
Michele Caini
d1d1b3156d fixed doc for #27 2018-03-28 22:29:01 +02:00
Michele Caini
472064b751 ensure -> assure (#63) 2018-03-28 22:04:16 +02:00
Michele Caini
95ab9a0b70 updated TODO 2018-03-28 17:20:31 +02:00
Michele Caini
4b03f6a039 minor changes 2018-03-28 15:49:02 +02:00
Michele Caini
c3460727fa updated TODO 2018-03-28 10:24:01 +02:00
Michele Caini
2cc1850212 save/restore - see #27 2018-03-28 10:23:47 +02:00
Matteo Galeotti
2d7443acaf Add Dispatcher header to EnTT global include (#59)
Add dispatcher.hpp to entt.hpp
2018-03-22 14:05:55 +01:00
Michele Caini
13d0b0940c raw views 2018-03-15 22:09:43 +01:00
Michele Caini
c101797924 minor changes 2018-03-15 22:03:18 +01:00
Michele Caini
83b55f8e3f fixed benchmark 2018-03-14 14:11:29 +01:00
Michele Caini
b3b6362cd9 minor changes 2018-03-14 14:00:48 +01:00
Nicholas Farshidmehr
fc9af32d5f Fix spelling mistakes. (#57)
Fix spelling mistakes.
2018-03-14 13:47:23 +01:00
Michele Caini
4cd1025011 cleanup 2018-03-14 08:41:31 +01:00
Michele Caini
5233fe8abc updated TODO 2018-03-14 08:39:33 +01:00
Michele Caini
041e31ea78 removed spaces: not satisfied with the current implementation 2018-03-14 08:38:20 +01:00
Michele Caini
7a3e881099 review: benchmark 2018-03-14 08:28:56 +01:00
Michele Caini
631bf42f84 cleanup 2018-03-13 13:55:37 +01:00
Michele Caini
1f704a7019 updated TODO list 2018-03-12 11:28:00 +01:00
Michele Caini
d295c88474 spaces 2018-03-11 23:11:45 +01:00
Michele Caini
1dd9da4dff improved views (extended API + better performance) 2018-03-11 23:07:10 +01:00
Michele Caini
f2eb0c8427 added Registry::fast 2018-03-11 23:05:56 +01:00
Michele Caini
c8ba11faf8 more tests 2018-03-11 23:04:32 +01:00
Michele Caini
a2e243d992 improved multi component standard view 2018-03-07 22:38:21 +01:00
Michele Caini
c588fff5ca minor changes 2018-03-07 17:24:44 +01:00
Michele Caini
87f9599fea minor changes 2018-03-07 08:52:13 +01:00
Michele Caini
0459599b1d added estimated number of entities for multi component standard view 2018-03-07 08:31:03 +01:00
Michele Caini
9447b1a696 fixed 2018-03-06 22:34:46 +01:00
Michele Caini
0ccb7443c2 only the registry should create views 2018-03-06 22:34:38 +01:00
Michele Caini
02cf27091f coding style 2018-03-06 22:22:52 +01:00
Michele Caini
fdfbd04503 review 2018-03-06 13:27:29 +01:00
Michele Caini
866c18200a iterators from sparse sets and views have now operator+/operator+= 2018-03-04 16:45:24 +01:00
Michele Caini
c1cada49d4 review 2018-03-04 16:03:59 +01:00
Michele Caini
7bf550a75f id/version review 2018-03-04 15:32:08 +01:00
Michele Caini
9c540c03aa thread safe family class + minor changes 2018-03-04 15:21:10 +01:00
Michele Caini
b3df46db19 better test 2018-03-02 08:58:09 +01:00
Michele Caini
7ca615a1c1 sfinaed construct in sparse set to favor emplace_back with arguments when possible (#48) 2018-03-02 08:45:59 +01:00
Michele Caini
c83db557a6 more tests + minor changes 2018-03-01 19:24:12 +01:00
Michele Caini
d54594f11d orphans/orphan + minor changes 2018-03-01 19:23:42 +01:00
Michele Caini
434e38608f fixed typo 2018-03-01 19:22:26 +01:00
Michele Caini
871f090ca0 bug fixing 2018-03-01 16:18:23 +01:00
Michele Caini
d1d235e025 Fixed #46 (#47)
Use libc++ if possible
2018-02-28 19:02:12 +01:00
Michele Caini
e822a5fd53 more tests 2018-02-27 23:42:19 +01:00
Michele Caini
7b82a4ae50 updated TODO 2018-02-27 23:42:05 +01:00
Michele Caini
c532e9f2eb updated TODO list 2018-02-25 22:53:57 +01:00
Michele Caini
3fd034816e more tests on sparse set 2018-02-22 23:23:46 +01:00
Michele Caini
bb4b868c79 improvement: standard multi component view 2018-02-22 22:46:42 +01:00
Michele Caini
3b3da11a36 cleanup 2018-02-22 13:13:02 +01:00
Nick Lange
f2cbb5306b Fix MSVC 2017 warning C4458 (#43)
Fix MSVC 2017 warning C4458.
2018-02-22 13:08:36 +01:00
Michele Caini
94ede1b324 updated TODO 2018-02-21 22:24:23 +01:00
Michele Caini
0367248338 Documentation (#42)
Everything is finally documented.
2018-02-21 22:16:02 +01:00
Michele Caini
936db30e58 Fewer allocations, faster destroy (#41)
Overall improvement of the registry.
2018-02-20 10:10:13 +01:00
Michele Caini
4822f0dd11 fixed 2018-02-18 23:19:26 +01:00
Michele Caini
456d220829 updated TODO 2018-02-15 09:27:39 +01:00
Michele Caini
b459ba6ea7 TODO list 2018-02-15 08:46:15 +01:00
Michele Caini
a19ef9bd16 slightly improved 2018-02-12 19:24:07 +01:00
Paolo Monteverde
59cec88a28 fixing clang build (#38) 2018-02-08 14:56:07 +01:00
Michele Caini
3ebc75af80 updated version 2018-02-08 12:42:38 +01:00
Michele Caini
4dce474e03 revert: too risky a function 2018-02-08 12:27:48 +01:00
Michele Caini
31a18da578 fix #37 2018-02-08 12:23:48 +01:00
Michele Caini
8c499850fc fixed doc 2018-02-04 12:36:50 +01:00
Michele Caini
6b6998a247 duktape is now an external 2018-02-04 12:31:24 +01:00
Michele Caini
a6cb0fc856 added Registry::alive and Registry::orphans 2018-02-02 17:35:15 +01:00
Michele Caini
e36b93e87b fixed 2018-02-02 12:58:10 +01:00
Michele Caini
1e3723b8bb minor changes 2018-02-02 12:38:17 +01:00
Michele Caini
412372289e updated copyright 2018-01-26 17:28:40 +01:00
Michele Caini
96f7e66073 fixed 2018-01-14 00:53:55 +01:00
Michele Caini
6040f8f263 issue #31: multi component get 2018-01-14 00:32:23 +01:00
Michele Caini
9761b6e14a updated version 2017-12-29 18:29:38 +01:00
Michele Caini
cb49910ed2 allow attaching listeners at any time, allow removing current listener 2017-12-29 18:25:49 +01:00
Michele Caini
62bd742673 fixed doc 2017-12-27 17:59:57 +01:00
Michele Caini
42d0a3d734 v2.4.0 2017-12-27 17:57:04 +01:00
Michele Caini
f0f8681455 bug fixing 2017-12-27 17:55:26 +01:00
Michele Caini
c801afddcb added optional data to process::init 2017-12-23 00:30:00 +01:00
Michele Caini
20e0e1333e minor changes 2017-12-23 00:21:05 +01:00
Michele Caini
a6b373fec4 minor changes 2017-12-23 00:18:23 +01:00
Michele Caini
41c77720bb added optional data to scheduler/process 2017-12-22 23:59:07 +01:00
Michele Caini
92e6340120 cleanup 2017-12-22 23:58:49 +01:00
Michele Caini
1221f63cbd updated doc 2017-12-22 09:24:56 +01:00
Michele Caini
0f24418891 added ResourceCache::temp 2017-12-20 13:39:23 +01:00
Michele Caini
f477c0ab87 fixed reserve 2017-12-18 14:57:23 +01:00
Michele Caini
9358691901 added reserve 2017-12-18 14:08:38 +01:00
Michele Caini
cd343ba598 updated appveyor.yml (waiting for a new stable release of googletest) 2017-12-15 23:06:43 +01:00
Michele Caini
50069d3743 fixed docs 2017-12-14 23:15:47 +01:00
Michele Caini
1e03f27f23 v2.3.0 2017-12-14 22:56:40 +01:00
Michele Caini
36bb55a9ce doc: fixed 2017-12-13 16:20:36 +01:00
Michele Caini
451e4050db cleanup 2017-12-11 22:35:48 +01:00
Michele Caini
367fd3e87f minor changes 2017-12-11 16:04:25 +01:00
Michele Caini
a67a2e12fd minor changes 2017-12-11 15:03:43 +01:00
Michele Caini
292978daf0 #23: runtime components (doc) 2017-12-11 15:03:35 +01:00
Michele Caini
85a4a76a14 mod example with duktape 2017-12-10 17:43:48 +01:00
Michele Caini
9d0ab7ed70 added target entt_aob 2017-12-04 15:10:52 +01:00
Michele Caini
3d5b6a5e0b exposed family types 2017-12-04 14:59:08 +01:00
Michele Caini
ab20372093 minor changes 2017-12-04 14:06:10 +01:00
Michele Caini
ab887f30e4 typo 2017-11-21 08:33:48 +01:00
Michele Caini
6cb6a8c25f minor changes 2017-11-20 15:45:08 +01:00
Michele Caini
9d1d2aca0a updated build system 2017-11-18 17:31:11 +01:00
Michele Caini
75cb2cd1f7 improved sort functionalities 2017-11-18 15:54:04 +01:00
Michele Caini
ed6adbbfd7 Update README.md 2017-11-15 22:45:35 +01:00
Michele Caini
b6c950ffc5 tests, tags and few other features 2017-11-15 22:25:37 +01:00
Michele Caini
8b89c69d5f fixed #20 2017-11-14 22:48:37 +01:00
Michele Caini
290dda50fe now it works with MSVC2017 (#19)
#18
2017-11-13 10:39:55 +01:00
Michele Caini
a7278573a8 review: hashed_string 2017-11-13 08:49:04 +01:00
Michele Caini
68ce4dc689 added actor class 2017-11-12 16:11:32 +01:00
Michele Caini
a9f5118013 updated documentation 2017-11-11 23:48:08 +01:00
Michele Caini
d1f2e8ecf9 updated tests 2017-11-11 23:47:31 +01:00
Michele Caini
fe6873b61a updated version 2017-11-11 23:46:29 +01:00
Michele Caini
7c7bcf80cf added stuff for resource management 2017-11-11 23:46:10 +01:00
Michele Caini
cf6022866d added process and scheduler 2017-11-11 23:42:52 +01:00
Michele Caini
c630cb1de2 added core/hashed_string 2017-11-11 23:41:48 +01:00
Michele Caini
2e6c8d542c updated signal module 2017-11-11 23:41:16 +01:00
Michele Caini
2f781906b5 updated entity module 2017-11-11 23:40:50 +01:00
Michele Caini
b4f3b6f7bd updated readme 2017-10-28 00:15:42 +02:00
Michele Caini
71b464f44a updated build system 2017-10-28 00:15:20 +02:00
Michele Caini
438070ed58 updated entt.hpp 2017-10-28 00:15:01 +02:00
Michele Caini
a06c891969 updated entity-component system 2017-10-28 00:14:32 +02:00
Michele Caini
a935bd09aa updated core stuff 2017-10-28 00:13:56 +02:00
Michele Caini
fb8745ccf0 minimal locator implementation 2017-10-28 00:13:29 +02:00
Michele Caini
53a4c4be7f signalling stuff 2017-10-28 00:13:06 +02:00
Michele Caini
c0a110ea8a updated travis config 2017-10-28 00:12:27 +02:00
Michele Caini
c426a8e331 removed tests with 50M entities (jenkins gives up with them) 2017-10-19 17:52:17 +02:00
Michele Caini
526e4f69a4 updated version 2017-10-19 16:23:20 +02:00
Michele Caini
f901fa50ff fixed: custom registry required to manage 50M entities 2017-10-19 16:07:33 +02:00
Michele Caini
bea9eeac16 fixed: registry.destroy makes available the wrong entity identifier 2017-10-19 15:53:59 +02:00
Michele Caini
3055da5316 fixed typo 2017-10-18 18:24:13 +02:00
Michele Caini
3706fbdfee EnTT v2 (#14)
EnTT v2
2017-10-18 09:19:14 +02:00
Michele Caini
b4d18e94da more tests 2017-09-17 21:31:38 +02:00
Michele Caini
41523d9555 typo 2017-09-17 21:18:30 +02:00
Michele Caini
3b4c025743 update version 2017-09-14 13:30:29 +02:00
Michele Caini
df065c5647 Now it works on VS2017 (#11)
* update appveyor config
* update build system
* refactoring
2017-09-14 13:27:56 +02:00
Michele Caini
21380aacb8 fixed example code 2017-09-13 22:05:05 +02:00
Michele Caini
5884b1cec5 cleanup 2017-09-11 13:46:42 +02:00
Michele Caini
05860fcf9b WIP: docs 2017-09-11 13:38:46 +02:00
Michele Caini
2916aaeda8 WIP: docs 2017-09-10 23:35:00 +02:00
Michele Caini
ec9a221a8f WIP: docs 2017-09-10 23:28:12 +02:00
Michele Caini
97d8ad7fc6 WIP: docs 2017-09-10 23:25:33 +02:00
Michele Caini
adfb4cd694 WIP: docs 2017-09-10 23:07:10 +02:00
Michele Caini
34374afd36 WIP: docs 2017-09-10 22:47:14 +02:00
Michele Caini
b29949c0fa WIP: readme 2017-09-10 22:34:46 +02:00
Michele Caini
d26e163f66 rollback to libstdc++-4.9-dev 2017-09-10 18:30:19 +02:00
Michele Caini
e47fb67d74 it seems that Travis CI doesn't like much libc++ 2017-09-10 18:27:27 +02:00
Michele Caini
b328c49899 struggling against Travis CI 2017-09-10 18:20:42 +02:00
Michele Caini
9f3b602c0a updated CMakeLists.txt 2017-09-10 18:14:33 +02:00
Michele Caini
994a68eb81 updated travis conf 2017-09-10 18:09:36 +02:00
Michele Caini
bc256a989e updated travis conf 2017-09-10 18:05:00 +02:00
Michele Caini
2aeec2d50f WIP: docs 2017-09-10 16:48:23 +02:00
Michele Caini
03afa7652b WIP: documentation 2017-09-10 16:40:32 +02:00
Michele Caini
6791cf1e2e minor changes 2017-09-10 16:40:20 +02:00
Michele Caini
e69b90ef1a WIP: updated readme 2017-09-09 17:36:36 +02:00
Michele Caini
6c925a32b4 updated registry/sparse_set 2017-09-09 17:32:41 +02:00
Michele Caini
8d3f381a5a arguments are no longer accepted by the constructor 2017-09-09 17:07:37 +02:00
Michele Caini
02c424bd21 only internal pool is allowed 2017-09-09 17:02:13 +02:00
Michele Caini
c324ee310a updated build system 2017-09-09 16:16:25 +02:00
Michele Caini
fe7250bfc1 tests 2017-09-08 16:57:48 +02:00
Michele Caini
63c1b046e0 WIP: tests + bug fixing 2017-09-08 15:35:02 +02:00
Michele Caini
ed98ae3e70 fixed: sort functionalities 2017-09-07 14:05:58 +02:00
Michele Caini
2011defb1e tests + bug fixing 2017-09-05 14:06:28 +02:00
Michele Caini
b35737b5d7 WIP: swap/sort functionalities 2017-09-04 15:30:19 +02:00
Michele Caini
aeaf1632c8 minor changes 2017-09-03 16:12:50 +02:00
Michele Caini
af70573634 WIP: improvements and new features 2017-09-03 15:55:33 +02:00
77 changed files with 20916 additions and 1824 deletions

1
.gitignore vendored
View File

@@ -1,2 +1 @@
# QtCreator
*.user

View File

@@ -11,6 +11,13 @@ matrix:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-6']
env: COMPILER=g++-6
- os: linux
compiler: gcc
addons:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-7']
env: COMPILER=g++-7
- os: linux
compiler: clang
addons:
@@ -18,23 +25,34 @@ matrix:
sources: ['ubuntu-toolchain-r-test', 'llvm-toolchain-trusty-4.0']
packages: ['clang-4.0', 'libstdc++-4.9-dev']
env: COMPILER=clang++-4.0
- os: linux
compiler: clang
addons:
apt:
sources: ['ubuntu-toolchain-r-test', 'llvm-toolchain-trusty-5.0']
packages: ['clang-5.0', 'libstdc++-4.9-dev']
env: COMPILER=clang++-5.0
- os: osx
osx_image: xcode8.3
compiler: clang
env: COMPILER=clang++
- os: osx
osx_image: xcode9.4
compiler: clang
env: COMPILER=clang++
- os: linux
compiler: gcc
addons:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-6']
packages: ['g++-7']
env:
- COMPILER=g++-6
- COMPILER=g++-7
- CXXFLAGS="-O0 --coverage -fno-inline -fno-inline-small-functions -fno-default-inline"
before_script:
- pip install --user cpp-coveralls
after_success:
- coveralls --gcov gcov-6 --gcov-options '\-lp' --root ${TRAVIS_BUILD_DIR} --build-root ${TRAVIS_BUILD_DIR}/build --extension cpp --extension hpp --exclude deps --include src
- coveralls --gcov gcov-7 --gcov-options '\-lp' --root ${TRAVIS_BUILD_DIR} --build-root ${TRAVIS_BUILD_DIR}/build --extension cpp --extension hpp --exclude deps --include src
notifications:
email:
@@ -51,5 +69,11 @@ install:
script:
- mkdir -p build && cd build
- cmake -DCMAKE_BUILD_TYPE=Release .. && make -j4
- cmake .. && make -j4
- CTEST_OUTPUT_ON_FAILURE=1 make test
deploy:
provider: script
script: scripts/update_packages.sh $TRAVIS_TAG
on:
tags: true

View File

@@ -5,3 +5,7 @@ Michele Caini aka skypjack
# Contributors
Paolo Monteverde aka morbo84
David Nerjes aka DavidHamburg
Indi Kernick aka Kerndog73
Malte Müller-Rowold aka m-waka
Richard Caseres aka richardbmx

View File

@@ -2,7 +2,7 @@
# EnTT
#
cmake_minimum_required(VERSION 3.2)
cmake_minimum_required(VERSION 3.7.2)
#
# Building in-tree is not allowed (we take care of your craziness).
@@ -16,7 +16,9 @@ endif()
# Project configuration
#
project(entt VERSION 1.0.0)
project(EnTT VERSION 2.7.2)
include(GNUInstallDirs)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
@@ -29,52 +31,193 @@ set(PROJECT_AUTHOR_EMAIL "michele.caini@gmail.com")
message("*")
message("* ${PROJECT_NAME} v${PROJECT_VERSION} (${CMAKE_BUILD_TYPE})")
message("* Copyright (c) 2017 ${PROJECT_AUTHOR} <${PROJECT_AUTHOR_EMAIL}>")
message("* Copyright (c) 2017-2018 ${PROJECT_AUTHOR} <${PROJECT_AUTHOR_EMAIL}>")
message("*")
#
# Compile stuff
#
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic -Wall -Wconversion")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g -DDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -DRELEASE")
option(USE_LIBCPP "Use libc++ by adding -stdlib=libc++ flag if availbale." ON)
option(USE_ASAN "Use address sanitizer by adding -fsanitize=address -fno-omit-frame-pointer flags" OFF)
option(USE_COMPILE_OPTIONS "Use compile options from EnTT." ON)
#
# CMake configuration
# Compiler stuff
#
set(PROJECT_CMAKE_IN ${entt_SOURCE_DIR}/cmake/in)
set(PROJECT_DEPS_DIR ${entt_SOURCE_DIR}/deps)
set(PROJECT_SRC_DIR ${entt_SOURCE_DIR}/src)
if(NOT MSVC AND USE_LIBCPP)
include(CheckCXXSourceCompiles)
include(CMakePushCheckState)
set(PROJECT_RUNTIME_OUTPUT_DIRECTORY bin)
cmake_push_check_state()
set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -stdlib=libc++")
check_cxx_source_compiles("
#include<type_traits>
int main() { return std::is_same<int, int>::value ? 0 : 1; }
" HAS_LIBCPP)
if(NOT HAS_LIBCPP)
message(WARNING "The option USE_LIBCPP is set (by default) but libc++ is not available. The flag will not be added to the target.")
endif()
cmake_pop_check_state()
endif()
#
# Enable test support using ctest-like interface
# Add EnTT target
#
add_library(EnTT INTERFACE)
target_include_directories(
EnTT INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
target_compile_definitions(
EnTT
INTERFACE $<$<AND:$<CONFIG:Debug>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>:DEBUG>
INTERFACE $<$<AND:$<CONFIG:Release>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>:RELEASE>
)
if(USE_ASAN)
target_compile_options(EnTT INTERFACE $<$<AND:$<CONFIG:Debug>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>:-fsanitize=address -fno-omit-frame-pointer>)
target_link_libraries(EnTT INTERFACE $<$<AND:$<CONFIG:Debug>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>:-fsanitize=address -fno-omit-frame-pointer>)
endif()
if(USE_COMPILE_OPTIONS)
target_compile_options(
EnTT
INTERFACE $<$<AND:$<CONFIG:Debug>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>:-O0 -g>
# it seems that -O3 ruins a bit the performance when using clang ...
INTERFACE $<$<AND:$<CONFIG:Release>,$<CXX_COMPILER_ID:Clang>>:-O2>
# ... on the other side, GCC is incredibly comfortable with it.
INTERFACE $<$<AND:$<CONFIG:Release>,$<CXX_COMPILER_ID:GNU>>:-O3>
)
endif()
if(HAS_LIBCPP)
target_compile_options(EnTT BEFORE INTERFACE -stdlib=libc++)
endif()
target_compile_features(EnTT INTERFACE cxx_std_14)
#
# Install EnTT
#
if(${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
set(CUSTOM_INSTALL_CONFIGDIR cmake)
else()
set(CUSTOM_INSTALL_CONFIGDIR ${CMAKE_INSTALL_LIBDIR}/cmake/entt)
endif()
install(DIRECTORY src/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(TARGETS EnTT EXPORT EnTTTargets)
export(EXPORT EnTTTargets FILE ${EnTT_BINARY_DIR}/EnTTTargets.cmake)
install(
EXPORT EnTTTargets
FILE EnTTTargets.cmake
DESTINATION ${CUSTOM_INSTALL_CONFIGDIR}
)
#
# Build tree package config file
#
configure_file(cmake/in/EnTTBuildConfig.cmake.in EnTTConfig.cmake @ONLY)
include(CMakePackageConfigHelpers)
#
# Install tree package config file
#
configure_package_config_file(
cmake/in/EnTTConfig.cmake.in
${CUSTOM_INSTALL_CONFIGDIR}/EnTTConfig.cmake
INSTALL_DESTINATION ${CUSTOM_INSTALL_CONFIGDIR}
PATH_VARS CMAKE_INSTALL_INCLUDEDIR
NO_CHECK_REQUIRED_COMPONENTS_MACRO
)
write_basic_package_version_file(
${EnTT_BINARY_DIR}/EnTTConfigVersion.cmake
VERSION ${PROJECT_VERSION}
COMPATIBILITY AnyNewerVersion
)
install(
FILES
${EnTT_BINARY_DIR}/${CUSTOM_INSTALL_CONFIGDIR}/EnTTConfig.cmake
${EnTT_BINARY_DIR}/EnTTConfigVersion.cmake
DESTINATION ${CUSTOM_INSTALL_CONFIGDIR}
)
export(PACKAGE EnTT)
#
# Tests
#
option(BUILD_TESTING "Enable testing with ctest." ON)
#
# build testing stuff if required
#
if(BUILD_TESTING)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
# gtest, gtest_main, gmock and gmock_main targets are available from now on
set(GOOGLETEST_DEPS_DIR ${PROJECT_DEPS_DIR}/googletest)
configure_file(${PROJECT_CMAKE_IN}/googletest.in ${GOOGLETEST_DEPS_DIR}/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . WORKING_DIRECTORY ${GOOGLETEST_DEPS_DIR})
execute_process(COMMAND ${CMAKE_COMMAND} --build . WORKING_DIRECTORY ${GOOGLETEST_DEPS_DIR})
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
add_subdirectory(${GOOGLETEST_DEPS_DIR}/src ${GOOGLETEST_DEPS_DIR}/build)
option(FIND_GTEST_PACKAGE "Enable finding gtest package." OFF)
if(FIND_GTEST_PACKAGE)
find_package(GTest REQUIRED)
else()
# gtest, gtest_main, gmock and gmock_main targets are available from now on
set(GOOGLETEST_DEPS_DIR ${EnTT_SOURCE_DIR}/deps/googletest)
configure_file(${EnTT_SOURCE_DIR}/cmake/in/googletest.in ${GOOGLETEST_DEPS_DIR}/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . WORKING_DIRECTORY ${GOOGLETEST_DEPS_DIR})
execute_process(COMMAND ${CMAKE_COMMAND} --build . WORKING_DIRECTORY ${GOOGLETEST_DEPS_DIR})
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
add_subdirectory(${GOOGLETEST_DEPS_DIR}/src ${GOOGLETEST_DEPS_DIR}/build)
add_library(GTest::Main ALIAS gtest_main)
endif()
option(BUILD_BENCHMARK "Build benchmark." OFF)
option(BUILD_MOD "Build mod example." OFF)
option(BUILD_SNAPSHOT "Build snapshot example." OFF)
enable_testing()
add_subdirectory(test)
endif()
#
# Documentation
#
option(BUILD_DOCS "Enable building with documentation." OFF)
if(BUILD_DOCS)
find_package(Doxygen 1.8)
if(DOXYGEN_FOUND)
add_subdirectory(docs)
endif()
endif()
#
# AOB
#
add_custom_target(
entt_aob
SOURCES
appveyor.yml
AUTHORS
LICENSE
README.md
TODO
.travis.yml
docs/CONTRIBUTING.md
docs/extra.dox
)

View File

@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2017 Michele Caini
Copyright (c) 2017-2018 Michele Caini
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

3038
README.md

File diff suppressed because it is too large Load Diff

15
TODO Normal file
View File

@@ -0,0 +1,15 @@
* custom allocators and EnTT allocator-aware in general (long term feature, I don't actually need it at the moment) - see #22
* scene management (I prefer the concept of spaces, that is a kind of scene anyway)
* review doc: separate it in multiple md/dox files, reduce the readme to a minimum and provide users with links to the online documentation on gh-pages
* debugging tools (#60): the issue online already contains interesting tips on this, look at it
* define basic reactive systems (track entities to which component is attached, track entities from which component is removed, and so on)
* define systems as composable mixins (initializazion, reactive, update, whatever) with flexible auto-detected arguments (registry, views, etc)
* create dedicated flat map based on types implementation (sort of "type map") for types to use within the registry and so on...
* registry::create with a "hint" on the entity identifier to use, it should ease combining multiple registries
* optimize for empty components, it would be a mid improvement in terms of memory usage
* add some lazy iterative sorters like "single bubble sort loop"
* can we do more for shared libraries? who knows... see #144
* work stealing job system (see #100)
* reflection system (maybe)
* C++17. That's all.
* AOB

View File

@@ -1,7 +1,7 @@
# can use variables like {build} and {branch}
version: 1.0.{build}
image: Visual Studio 2015
image: Visual Studio 2017
environment:
BUILD_DIR: "%APPVEYOR_BUILD_FOLDER%\\build"
@@ -13,9 +13,8 @@ configuration:
- Release
before_build:
- deps.bat
- cd %BUILD_DIR%
- cmake .. -G"%CMAKE_GENERATOR_NAME%"
- cmake .. -DCMAKE_CXX_FLAGS=/D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING -G"Visual Studio 15 2017"
build:
parallel: true

View File

@@ -0,0 +1,6 @@
set(ENTT_VERSION "@PROJECT_VERSION@")
set(ENTT_INCLUDE_DIRS "@CMAKE_CURRENT_SOURCE_DIR@/src")
if(NOT CMAKE_VERSION VERSION_LESS "3.0")
include("${CMAKE_CURRENT_LIST_DIR}/EnTTTargets.cmake")
endif()

View File

@@ -0,0 +1,11 @@
set(ENTT_VERSION "@PROJECT_VERSION@")
@PACKAGE_INIT@
set_and_check(ENTT_INCLUDE_DIRS "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@")
if(NOT CMAKE_VERSION VERSION_LESS "3.0")
include("${CMAKE_CURRENT_LIST_DIR}/EnTTTargets.cmake")
endif()
check_required_components("@PROJECT_NAME@")

19
cmake/in/cereal.in Normal file
View File

@@ -0,0 +1,19 @@
project(cereal-download NONE)
cmake_minimum_required(VERSION 3.2)
include(ExternalProject)
ExternalProject_Add(
cereal
GIT_REPOSITORY https://github.com/USCiLab/cereal.git
GIT_TAG v1.2.2
DOWNLOAD_DIR ${CEREAL_DEPS_DIR}
TMP_DIR ${CEREAL_DEPS_DIR}/tmp
STAMP_DIR ${CEREAL_DEPS_DIR}/stamp
SOURCE_DIR ${CEREAL_DEPS_DIR}/src
BINARY_DIR ${CEREAL_DEPS_DIR}/build
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)

19
cmake/in/duktape.in Normal file
View File

@@ -0,0 +1,19 @@
project(duktape-download NONE)
cmake_minimum_required(VERSION 3.2)
include(ExternalProject)
ExternalProject_Add(
duktape
GIT_REPOSITORY https://github.com/svaarala/duktape-releases.git
GIT_TAG v2.2.0
DOWNLOAD_DIR ${DUKTAPE_DEPS_DIR}
TMP_DIR ${DUKTAPE_DEPS_DIR}/tmp
STAMP_DIR ${DUKTAPE_DEPS_DIR}/stamp
SOURCE_DIR ${DUKTAPE_DEPS_DIR}/src
BINARY_DIR ${DUKTAPE_DEPS_DIR}/build
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)

22
docs/CMakeLists.txt Normal file
View File

@@ -0,0 +1,22 @@
#
# Doxygen configuration (documentation)
#
set(DOXY_SOURCE_DIRECTORY ${EnTT_SOURCE_DIR}/src)
set(DOXY_DOCS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
set(DOXY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
configure_file(doxy.in doxy.cfg @ONLY)
add_custom_target(
docs ALL
COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxy.cfg
WORKING_DIRECTORY ${EnTT_SOURCE_DIR}
VERBATIM
SOURCES doxy.in
)
install(
DIRECTORY ${DOXY_OUTPUT_DIRECTORY}/html
DESTINATION share/${PROJECT_NAME}-${PROJECT_VERSION}/
)

43
docs/CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,43 @@
# Contributing
First of all, thank you very much for taking the time to contribute to the
`EnTT` framework.<br/>
How to do it mostly depends on the type of contribution:
* If you have a question, **please** ensure there isn't already an answer for
you by searching on GitHub under
[issues](https://github.com/skypjack/entt/issues). Do not forget to search
also through the closed ones. If you are unable to find a proper answer, feel
free to [open a new issue](https://github.com/skypjack/entt/issues/new).
Usually, questions are marked as such and closed in a few days.
* If you want to fix a typo in the inline documentation or in the README file,
if you want to add some new sections or if you want to help me with the
language by reviewing what I wrote so far (I'm not a native speaker after
all), **please** open a new
[pull request](https://github.com/skypjack/entt/pulls) with your changes.
* If you found a bug, **please** ensure there isn't already an answer for you by
searching on GitHub under [issues](https://github.com/skypjack/entt/issues).
If you are unable to find an open issue addressing the problem, feel free to
[open a new one](https://github.com/skypjack/entt/issues/new). **Please**, do
not forget to carefully describe how to reproduce the problem, then add all
the informaion about the system on which you are experiencing it and point out
the version of `EnTT` you are using (tag or commit).
* If you found a bug and you wrote a patch to fix it, open a new
[pull request](https://github.com/skypjack/entt/pulls) with your code.
**Please**, add some tests to avoid regressions in future if possible, it
would be really appreciated. Note that the `EnTT` framework has a
[coverage at 100%](https://coveralls.io/github/skypjack/entt?branch=master)
(at least it was at 100% at the time I wrote this file) and this is the reason
for which you can be confident with using it in a production environment.
* If you want to propose a new feature and you know how to code it, **please**
do not issue directly a pull request. Before to do it,
[create a new issue](https://github.com/skypjack/entt/issues/new) to discuss
your proposal. Other users could be interested in your idea and the discussion
that will follow can refine it and therefore give us a better solution.
* If you want to request a new feature, I'm available for hiring. Take a look at
[my profile](https://github.com/skypjack) and feel free to write me.

2446
docs/doxy.in Normal file

File diff suppressed because it is too large Load Diff

5
docs/extra.dox Normal file
View File

@@ -0,0 +1,5 @@
/**
* @namespace entt
*
* @brief `EnTT` default namespace.
*/

60
scripts/update_homebrew.sh Executable file
View File

@@ -0,0 +1,60 @@
#!/bin/sh
# only argument should be the version to upgrade to
if [ $# != 1 ]
then
echo "Expected a version tag like v2.7.1"
exit 1
fi
VERSION="$1"
URL="https://github.com/skypjack/entt/archive/$VERSION.tar.gz"
FORMULA="entt.rb"
echo "Updating homebrew package to $VERSION"
echo "Cloning..."
git clone https://github.com/skypjack/homebrew-entt.git
if [ $? != 0 ]
then
exit 1
fi
cd homebrew-entt
# download the repo at the version
# exit with error messages if curl fails
echo "Curling..."
curl "$URL" --location --fail --silent --show-error --output archive.tar.gz
if [ $? != 0 ]
then
exit 1
fi
# compute sha256 hash
echo "Hashing..."
HASH="$(openssl sha256 archive.tar.gz | cut -d " " -f 2)"
# delete the archive
rm archive.tar.gz
echo "Sedding..."
# change the url in the formula file
# the slashes in the URL must be escaped
ESCAPED_URL="$(sed -e 's/[\/&]/\\&/g' <<< "$URL")"
sed -i -e '/url/s/".*"/"'$ESCAPED_URL'"/' $FORMULA
# change the hash in the formula file
sed -i -e '/sha256/s/".*"/"'$HASH'"/' $FORMULA
# delete temporary file created by sed
rm "$FORMULA-e"
# update remote repo
echo "Gitting..."
git add entt.rb
git commit -m "Update to $VERSION"
git push origin master
# out of homebrew-entt dir
cd ..

3
scripts/update_packages.sh Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
scripts/update_homebrew.sh $1

View File

@@ -1,235 +0,0 @@
#ifndef ENTT_COMPONENT_POOL_HPP
#define ENTT_COMPONENT_POOL_HPP
#include <utility>
#include <vector>
#include <cassert>
namespace entt {
template<typename, typename, typename...>
class ComponentPool;
template<typename Entity, typename Component>
class ComponentPool<Entity, Component> {
public:
using component_type = Component;
using entity_type = Entity;
using pos_type = entity_type;
using size_type = typename std::vector<component_type>::size_type;
using iterator_type = typename std::vector<entity_type>::iterator;
using const_iterator_type = typename std::vector<entity_type>::const_iterator;
private:
inline bool valid(entity_type entity) const noexcept {
return entity < reverse.size() && reverse[entity] < direct.size() && direct[reverse[entity]] == entity;
}
public:
explicit ComponentPool(size_type dim = 4098) noexcept {
assert(!(dim < 0));
data.reserve(dim);
}
ComponentPool(ComponentPool &&) = default;
~ComponentPool() noexcept {
assert(empty());
}
ComponentPool & operator=(ComponentPool &&) = default;
bool empty() const noexcept {
return data.empty();
}
size_type capacity() const noexcept {
return data.capacity();
}
size_type size() const noexcept {
return data.size();
}
iterator_type begin() noexcept {
return direct.begin();
}
const_iterator_type cbegin() const noexcept {
return direct.cbegin();
}
iterator_type end() noexcept {
return direct.end();
}
const_iterator_type cend() const noexcept {
return direct.cend();
}
bool has(entity_type entity) const noexcept {
return valid(entity);
}
const component_type & get(entity_type entity) const noexcept {
assert(valid(entity));
return data[reverse[entity]];
}
component_type & get(entity_type entity) noexcept {
return const_cast<component_type &>(const_cast<const ComponentPool *>(this)->get(entity));
}
template<typename... Args>
component_type & construct(entity_type entity, Args... args) {
assert(!valid(entity));
if(!(entity < reverse.size())) {
reverse.resize(entity+1);
}
reverse[entity] = pos_type(direct.size());
direct.emplace_back(entity);
data.push_back({ args... });
return data.back();
}
void destroy(entity_type entity) {
assert(valid(entity));
auto last = direct.size() - 1;
reverse[direct[last]] = reverse[entity];
direct[reverse[entity]] = direct[last];
data[reverse[entity]] = std::move(data[last]);
direct.pop_back();
data.pop_back();
}
void reset() {
data.clear();
reverse.resize(0);
direct.clear();
}
private:
std::vector<component_type> data;
std::vector<pos_type> reverse;
std::vector<entity_type> direct;
};
template<typename Entity, typename Component, typename... Components>
class ComponentPool
: ComponentPool<Entity, Component>, ComponentPool<Entity, Components>...
{
template<typename Comp>
using Pool = ComponentPool<Entity, Comp>;
public:
using entity_type = typename Pool<Component>::entity_type;
using pos_type = typename Pool<Component>::pos_type;
using size_type = typename Pool<Component>::size_type;
using iterator_type = typename Pool<Component>::iterator_type;
using const_iterator_type = typename Pool<Component>::const_iterator_type;
explicit ComponentPool(size_type dim = 4098) noexcept
#ifdef _MSC_VER
: ComponentPool<Entity, Component>{dim}, ComponentPool<Entity, Components>{dim}...
#else
: Pool<Component>{dim}, Pool<Components>{dim}...
#endif
{
assert(!(dim < 0));
}
ComponentPool(const ComponentPool &) = delete;
ComponentPool(ComponentPool &&) = delete;
ComponentPool & operator=(const ComponentPool &) = delete;
ComponentPool & operator=(ComponentPool &&) = delete;
template<typename Comp>
bool empty() const noexcept {
return Pool<Comp>::empty();
}
template<typename Comp>
size_type capacity() const noexcept {
return Pool<Comp>::capacity();
}
template<typename Comp>
size_type size() const noexcept {
return Pool<Comp>::size();
}
template<typename Comp>
iterator_type begin() noexcept {
return Pool<Comp>::begin();
}
template<typename Comp>
const_iterator_type cbegin() const noexcept {
return Pool<Comp>::cbegin();
}
template<typename Comp>
iterator_type end() noexcept {
return Pool<Comp>::end();
}
template<typename Comp>
const_iterator_type cend() const noexcept {
return Pool<Comp>::cend();
}
template<typename Comp>
bool has(entity_type entity) const noexcept {
return Pool<Comp>::has(entity);
}
template<typename Comp>
const Comp & get(entity_type entity) const noexcept {
return Pool<Comp>::get(entity);
}
template<typename Comp>
Comp & get(entity_type entity) noexcept {
return const_cast<Comp &>(const_cast<const ComponentPool *>(this)->get<Comp>(entity));
}
template<typename Comp, typename... Args>
Comp & construct(entity_type entity, Args... args) {
return Pool<Comp>::construct(entity, args...);
}
template<typename Comp>
void destroy(entity_type entity) {
Pool<Comp>::destroy(entity);
}
template<typename Comp>
void reset() {
Pool<Comp>::reset();
}
void reset() {
using accumulator_type = int[];
Pool<Component>::reset();
accumulator_type accumulator = { (Pool<Components>::reset(), 0)... };
(void)accumulator;
}
};
}
#endif // ENTT_COMPONENT_POOL_HPP

16
src/entt/config/config.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef ENTT_CONFIG_CONFIG_H
#define ENTT_CONFIG_CONFIG_H
#ifndef ENTT_NOEXCEPT
#define ENTT_NOEXCEPT noexcept
#endif // ENTT_NOEXCEPT
#ifndef ENTT_HS_SUFFIX
#define ENTT_HS_SUFFIX _hs
#endif // ENTT_HS_SUFFIX
#endif // ENTT_CONFIG_CONFIG_H

111
src/entt/core/algorithm.hpp Normal file
View File

@@ -0,0 +1,111 @@
#ifndef ENTT_CORE_ALGORITHM_HPP
#define ENTT_CORE_ALGORITHM_HPP
#include <functional>
#include <algorithm>
#include <utility>
namespace entt {
/**
* @brief Function object to wrap `std::sort` in a class type.
*
* Unfortunately, `std::sort` cannot be passed as template argument to a class
* template or a function template.<br/>
* This class fills the gap by wrapping some flavors of `std::sort` in a
* function object.
*/
struct StdSort final {
/**
* @brief Sorts the elements in a range.
*
* Sorts the elements in a range using the given binary comparison function.
*
* @tparam It Type of random access iterator.
* @tparam Compare Type of comparison function object.
* @tparam Args Types of arguments to forward to the sort function.
* @param first An iterator to the first element of the range to sort.
* @param last An iterator past the last element of the range to sort.
* @param compare A valid comparison function object.
* @param args Arguments to forward to the sort function, if any.
*/
template<typename It, typename Compare = std::less<>, typename... Args>
void operator()(It first, It last, Compare compare = Compare{}, Args &&... args) const {
std::sort(std::forward<Args>(args)..., std::move(first), std::move(last), std::move(compare));
}
};
/*! @brief Function object for performing insertion sort. */
struct InsertionSort final {
/**
* @brief Sorts the elements in a range.
*
* Sorts the elements in a range using the given binary comparison function.
*
* @tparam It Type of random access iterator.
* @tparam Compare Type of comparison function object.
* @param first An iterator to the first element of the range to sort.
* @param last An iterator past the last element of the range to sort.
* @param compare A valid comparison function object.
*/
template<typename It, typename Compare = std::less<>>
void operator()(It first, It last, Compare compare = Compare{}) const {
auto it = first + 1;
while(it != last) {
auto value = *it;
auto pre = it;
while(pre != first && compare(value, *(pre-1))) {
*pre = *(pre-1);
--pre;
}
*pre = value;
++it;
}
}
};
/*! @brief Function object for performing bubble sort (single iteration). */
struct OneShotBubbleSort final {
/**
* @brief Tries to sort the elements in a range.
*
* Performs a single iteration to sort the elements in a range using the
* given binary comparison function. The range may not be completely sorted
* after running this function.
*
* @tparam It Type of random access iterator.
* @tparam Compare Type of comparison function object.
* @param first An iterator to the first element of the range to sort.
* @param last An iterator past the last element of the range to sort.
* @param compare A valid comparison function object.
*/
template<typename It, typename Compare = std::less<>>
void operator()(It first, It last, Compare compare = Compare{}) const {
if(first != last) {
auto it = first++;
while(first != last) {
if(compare(*first, *it)) {
using std::swap;
std::swap(*first, *it);
}
it = first++;
}
}
}
};
}
#endif // ENTT_CORE_ALGORITHM_HPP

53
src/entt/core/family.hpp Normal file
View File

@@ -0,0 +1,53 @@
#ifndef ENTT_CORE_FAMILY_HPP
#define ENTT_CORE_FAMILY_HPP
#include <type_traits>
#include <cstddef>
#include <atomic>
#include "../config/config.h"
namespace entt {
/**
* @brief Dynamic identifier generator.
*
* Utility class template that can be used to assign unique identifiers to types
* at runtime. Use different specializations to create separate sets of
* identifiers.
*/
template<typename...>
class Family {
static std::atomic<std::size_t> identifier;
template<typename...>
static std::size_t family() ENTT_NOEXCEPT {
static const std::size_t value = identifier.fetch_add(1);
return value;
}
public:
/*! @brief Unsigned integer type. */
using family_type = std::size_t;
/**
* @brief Returns an unique identifier for the given type.
* @return Statically generated unique identifier for the given type.
*/
template<typename... Type>
inline static family_type type() ENTT_NOEXCEPT {
return family<std::decay_t<Type>...>();
}
};
template<typename... Types>
std::atomic<std::size_t> Family<Types...>::identifier{};
}
#endif // ENTT_CORE_FAMILY_HPP

View File

@@ -0,0 +1,121 @@
#ifndef ENTT_CORE_HASHED_STRING_HPP
#define ENTT_CORE_HASHED_STRING_HPP
#include <cstddef>
#include <cstdint>
#include "../config/config.h"
namespace entt {
/**
* @brief Zero overhead resource identifier.
*
* A hashed string is a compile-time tool that allows users to use
* human-readable identifers in the codebase while using their numeric
* counterparts at runtime.<br/>
* Because of that, a hashed string can also be used in constant expressions if
* required.
*/
class HashedString final {
struct ConstCharWrapper final {
// non-explicit constructor on purpose
constexpr ConstCharWrapper(const char *str) ENTT_NOEXCEPT: str{str} {}
const char *str;
};
static constexpr std::uint64_t offset = 14695981039346656037ull;
static constexpr std::uint64_t prime = 1099511628211ull;
// FowlerNollVo hash function v. 1a - the good
static constexpr std::uint64_t helper(std::uint64_t partial, const char *str) ENTT_NOEXCEPT {
return str[0] == 0 ? partial : helper((partial^str[0])*prime, str+1);
}
public:
/*! @brief Unsigned integer type. */
using hash_type = std::uint64_t;
/**
* @brief Constructs a hashed string from an array of const chars.
*
* Forcing template resolution avoids implicit conversions. An
* human-readable identifier can be anything but a plain, old bunch of
* characters.<br/>
* Example of use:
* @code{.cpp}
* HashedString sh{"my.png"};
* @endcode
*
* @tparam N Number of characters of the identifier.
* @param str Human-readable identifer.
*/
template <std::size_t N>
constexpr HashedString(const char (&str)[N]) ENTT_NOEXCEPT
: hash{helper(offset, str)}, str{str}
{}
/**
* @brief Explicit constructor on purpose to avoid constructing a hashed
* string directly from a `const char *`.
*
* @param wrapper Helps achieving the purpose by relying on overloading.
*/
explicit constexpr HashedString(ConstCharWrapper wrapper) ENTT_NOEXCEPT
: hash{helper(offset, wrapper.str)}, str{wrapper.str}
{}
/**
* @brief Returns the human-readable representation of a hashed string.
* @return The string used to initialize the instance.
*/
constexpr operator const char *() const ENTT_NOEXCEPT { return str; }
/**
* @brief Returns the numeric representation of a hashed string.
* @return The numeric representation of the instance.
*/
constexpr operator hash_type() const ENTT_NOEXCEPT { return hash; }
/**
* @brief Compares two hashed strings.
* @param other Hashed string with which to compare.
* @return True if the two hashed strings are identical, false otherwise.
*/
constexpr bool operator==(const HashedString &other) const ENTT_NOEXCEPT {
return hash == other.hash;
}
private:
const hash_type hash;
const char *str;
};
/**
* @brief Compares two hashed strings.
* @param lhs A valid hashed string.
* @param rhs A valid hashed string.
* @return True if the two hashed strings are identical, false otherwise.
*/
constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) ENTT_NOEXCEPT {
return !(lhs == rhs);
}
}
/**
* @brief User defined literal for hashed strings.
* @param str The literal without its suffix.
* @return A properly initialized hashed string.
*/
constexpr entt::HashedString operator"" ENTT_HS_SUFFIX(const char *str, std::size_t) ENTT_NOEXCEPT {
return entt::HashedString{str};
}
#endif // ENTT_CORE_HASHED_STRING_HPP

104
src/entt/core/ident.hpp Normal file
View File

@@ -0,0 +1,104 @@
#ifndef ENTT_CORE_IDENT_HPP
#define ENTT_CORE_IDENT_HPP
#include <type_traits>
#include <cstddef>
#include <utility>
#include <tuple>
#include "../config/config.h"
namespace entt {
namespace internal {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
template<typename...>
struct IsPartOf;
template<typename Type, typename Current, typename... Other>
struct IsPartOf<Type, Current, Other...>: std::conditional_t<std::is_same<Type, Current>::value, std::true_type, IsPartOf<Type, Other...>> {};
template<typename Type>
struct IsPartOf<Type>: std::false_type {};
/**
* Internal details not to be documented.
* @endcond TURN_OFF_DOXYGEN
*/
}
/**
* @brief Types identifiers.
*
* Variable template used to generate identifiers at compile-time for the given
* types. Use the `get` member function to know what's the identifier associated
* to the specific type.
*
* @note
* Identifiers are constant expression and can be used in any context where such
* an expression is required. As an example:
* @code{.cpp}
* using ID = entt::Identifier<AType, AnotherType>;
*
* switch(aTypeIdentifier) {
* case ID::get<AType>():
* // ...
* break;
* case ID::get<AnotherType>():
* // ...
* break;
* default:
* // ...
* }
* @endcode
*
* @tparam Types List of types for which to generate identifiers.
*/
template<typename... Types>
class Identifier final {
using tuple_type = std::tuple<std::decay_t<Types>...>;
template<typename Type, std::size_t... Indexes>
static constexpr std::size_t get(std::index_sequence<Indexes...>) ENTT_NOEXCEPT {
static_assert(internal::IsPartOf<Type, Types...>::value, "!");
std::size_t max{};
using accumulator_type = std::size_t[];
accumulator_type accumulator = { (max = std::is_same<Type, std::tuple_element_t<Indexes, tuple_type>>::value ? Indexes : max)... };
(void)accumulator;
return max;
}
public:
/*! @brief Unsigned integer type. */
using identifier_type = std::size_t;
/**
* @brief Returns the identifier associated with a given type.
* @tparam Type of which to return the identifier.
* @return The identifier associated with the given type.
*/
template<typename Type>
static constexpr identifier_type get() ENTT_NOEXCEPT {
return get<std::decay_t<Type>>(std::make_index_sequence<sizeof...(Types)>{});
}
};
}
#endif // ENTT_CORE_IDENT_HPP

View File

@@ -0,0 +1,61 @@
#ifndef ENTT_CORE_MONOSTATE_HPP
#define ENTT_CORE_MONOSTATE_HPP
#include <atomic>
#include <cassert>
#include "family.hpp"
#include "hashed_string.hpp"
namespace entt {
/**
* @brief Minimal implementation of the monostate pattern.
*
* A minimal, yet complete configuration system built on top of the monostate
* pattern. Thread safe by design, it works only with basic types like `int`s or
* `bool`s.<br/>
* Multiple types and therefore more than one value can be associated with a
* single key. Because of this, users must pay attention to use the same type
* both during an assignment and when they try to read back their data.
* Otherwise, they can incur in unexpected results.
*/
template<HashedString::hash_type>
struct Monostate {
/**
* @brief Assigns a value of a specific type to a given key.
* @tparam Type Type of the value to assign.
* @param val User data to assign to the given key.
*/
template<typename Type>
void operator=(Type val) const ENTT_NOEXCEPT {
Monostate::value<Type> = val;
}
/**
* @brief Gets a value of a specific type for a given key.
* @tparam Type Type of the value to get.
* @return Stored value, if any.
*/
template<typename Type>
operator Type() const ENTT_NOEXCEPT {
return Monostate::value<Type>;
}
private:
template<typename Type>
static std::atomic<Type> value;
};
template<HashedString::hash_type ID>
template<typename Type>
std::atomic<Type> Monostate<ID>::value{};
}
#endif // ENTT_CORE_MONOSTATE_HPP

211
src/entt/entity/actor.hpp Normal file
View File

@@ -0,0 +1,211 @@
#ifndef ENTT_ENTITY_ACTOR_HPP
#define ENTT_ENTITY_ACTOR_HPP
#include <cassert>
#include <utility>
#include "../config/config.h"
#include "registry.hpp"
namespace entt {
/**
* @brief Dedicated to those who aren't confident with entity-component systems.
*
* Tiny wrapper around a registry, for all those users that aren't confident
* with entity-component systems and prefer to iterate objects directly.
*
* @tparam Entity A valid entity type (see entt_traits for more details).
*/
template<typename Entity>
struct Actor {
/*! @brief Type of registry used internally. */
using registry_type = Registry<Entity>;
/*! @brief Underlying entity identifier. */
using entity_type = Entity;
/**
* @brief Constructs an actor by using the given registry.
* @param reg An entity-component system properly initialized.
*/
Actor(Registry<Entity> &reg)
: reg{reg}, entt{reg.create()}
{}
/*! @brief Default destructor. */
virtual ~Actor() {
reg.destroy(entt);
}
/*! @brief Default copy constructor. */
Actor(const Actor &) = default;
/*! @brief Default move constructor. */
Actor(Actor &&) = default;
/*! @brief Default copy assignment operator. @return This actor. */
Actor & operator=(const Actor &) = default;
/*! @brief Default move assignment operator. @return This actor. */
Actor & operator=(Actor &&) = default;
/**
* @brief Assigns the given tag to an actor.
*
* A new instance of the given tag is created and initialized with the
* arguments provided (the tag must have a proper constructor or be of
* aggregate type). Then the tag is removed from its previous owner (if any)
* and assigned to the actor.
*
* @tparam Tag Type of the tag to create.
* @tparam Args Types of arguments to use to construct the tag.
* @param args Parameters to use to initialize the tag.
* @return A reference to the newly created tag.
*/
template<typename Tag, typename... Args>
Tag & assign(tag_t, Args &&... args) {
return (reg.template remove<Tag>(), reg.template assign<Tag>(tag_t{}, entt, std::forward<Args>(args)...));
}
/**
* @brief Assigns the given component to an actor.
*
* A new instance of the given component is created and initialized with the
* arguments provided (the component must have a proper constructor or be of
* aggregate type). Then the component is assigned to the actor.<br/>
* In case the actor already has a component of the given type, it's
* replaced with the new one.
*
* @tparam Component Type of the component to create.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
Component & assign(Args &&... args) {
return reg.template accommodate<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Removes the given tag from an actor.
* @tparam Tag Type of the tag to remove.
*/
template<typename Tag>
void remove(tag_t) {
assert(has<Tag>(tag_t{}));
reg.template remove<Tag>();
}
/**
* @brief Removes the given component from an actor.
* @tparam Component Type of the component to remove.
*/
template<typename Component>
void remove() {
reg.template remove<Component>(entt);
}
/**
* @brief Checks if an actor owns the given tag.
* @tparam Tag Type of the tag for which to perform the check.
* @return True if the actor owns the tag, false otherwise.
*/
template<typename Tag>
bool has(tag_t) const ENTT_NOEXCEPT {
return (reg.template has<Tag>() && (reg.template attachee<Tag>() == entt));
}
/**
* @brief Checks if an actor has the given component.
* @tparam Component Type of the component for which to perform the check.
* @return True if the actor has the component, false otherwise.
*/
template<typename Component>
bool has() const ENTT_NOEXCEPT {
return reg.template has<Component>(entt);
}
/**
* @brief Returns a reference to the given tag for an actor.
* @tparam Tag Type of the tag to get.
* @return A reference to the instance of the tag owned by the actor.
*/
template<typename Tag>
const Tag & get(tag_t) const ENTT_NOEXCEPT {
assert(has<Tag>(tag_t{}));
return reg.template get<Tag>();
}
/**
* @brief Returns a reference to the given tag for an actor.
* @tparam Tag Type of the tag to get.
* @return A reference to the instance of the tag owned by the actor.
*/
template<typename Tag>
inline Tag & get(tag_t) ENTT_NOEXCEPT {
return const_cast<Tag &>(const_cast<const Actor *>(this)->get<Tag>(tag_t{}));
}
/**
* @brief Returns a reference to the given component for an actor.
* @tparam Component Type of the component to get.
* @return A reference to the instance of the component owned by the actor.
*/
template<typename Component>
const Component & get() const ENTT_NOEXCEPT {
return reg.template get<Component>(entt);
}
/**
* @brief Returns a reference to the given component for an actor.
* @tparam Component Type of the component to get.
* @return A reference to the instance of the component owned by the actor.
*/
template<typename Component>
inline Component & get() ENTT_NOEXCEPT {
return const_cast<Component &>(const_cast<const Actor *>(this)->get<Component>());
}
/**
* @brief Returns a reference to the underlying registry.
* @return A reference to the underlying registry.
*/
inline const registry_type & registry() const ENTT_NOEXCEPT {
return reg;
}
/**
* @brief Returns a reference to the underlying registry.
* @return A reference to the underlying registry.
*/
inline registry_type & registry() ENTT_NOEXCEPT {
return const_cast<registry_type &>(const_cast<const Actor *>(this)->registry());
}
/**
* @brief Returns the entity associated with an actor.
* @return The entity associated with the actor.
*/
inline entity_type entity() const ENTT_NOEXCEPT {
return entt;
}
private:
registry_type &reg;
Entity entt;
};
/**
* @brief Default actor class.
*
* The default actor is the best choice for almost all the applications.<br/>
* Users should have a really good reason to choose something different.
*/
using DefaultActor = Actor<DefaultRegistry::entity_type>;
}
#endif // ENTT_ENTITY_ACTOR_HPP

View File

@@ -0,0 +1,87 @@
#ifndef ENTT_ENTITY_ENTITY_HPP
#define ENTT_ENTITY_ENTITY_HPP
#include "../config/config.h"
#include "entt_traits.hpp"
namespace entt {
namespace internal {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
template<typename Entity>
static constexpr auto null = ~typename entt_traits<Entity>::entity_type{};
struct Null {
explicit constexpr Null() = default;
template<typename Entity>
constexpr operator Entity() const ENTT_NOEXCEPT {
return null<Entity>;
}
constexpr bool operator==(Null) const ENTT_NOEXCEPT {
return true;
}
constexpr bool operator!=(Null) const ENTT_NOEXCEPT {
return false;
}
template<typename Entity>
constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT {
return entity == null<Entity>;
}
template<typename Entity>
constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT {
return entity != null<Entity>;
}
};
template<typename Entity>
constexpr bool operator==(const Entity entity, Null null) ENTT_NOEXCEPT {
return null == entity;
}
template<typename Entity>
constexpr bool operator!=(const Entity entity, Null null) ENTT_NOEXCEPT {
return null != entity;
}
/**
* Internal details not to be documented.
* @endcond TURN_OFF_DOXYGEN
*/
}
/**
* @brief Null entity.
*
* There exist implicit conversions from this variable to entity identifiers of
* any allowed type. Similarly, there exist comparision operators between the
* null entity and any other entity identifier.
*/
constexpr auto null = internal::Null{};
}
#endif // ENTT_ENTITY_ENTITY_HPP

View File

@@ -0,0 +1,102 @@
#ifndef ENTT_ENTITY_ENTT_TRAITS_HPP
#define ENTT_ENTITY_ENTT_TRAITS_HPP
#include <cstdint>
namespace entt {
/**
* @brief Entity traits.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is an accepted entity type.
*/
template<typename>
struct entt_traits;
/**
* @brief Entity traits for a 16 bits entity identifier.
*
* A 16 bits entity identifier guarantees:
*
* * 12 bits for the entity number (up to 4k entities).
* * 4 bit for the version (resets in [0-15]).
*/
template<>
struct entt_traits<std::uint16_t> {
/*! @brief Underlying entity type. */
using entity_type = std::uint16_t;
/*! @brief Underlying version type. */
using version_type = std::uint8_t;
/*! @brief Difference type. */
using difference_type = std::int32_t;
/*! @brief Mask to use to get the entity number out of an identifier. */
static constexpr auto entity_mask = 0xFFF;
/*! @brief Mask to use to get the version out of an identifier. */
static constexpr auto version_mask = 0xF;
/*! @brief Extent of the entity number within an identifier. */
static constexpr auto entity_shift = 12;
};
/**
* @brief Entity traits for a 32 bits entity identifier.
*
* A 32 bits entity identifier guarantees:
*
* * 20 bits for the entity number (suitable for almost all the games).
* * 12 bit for the version (resets in [0-4095]).
*/
template<>
struct entt_traits<std::uint32_t> {
/*! @brief Underlying entity type. */
using entity_type = std::uint32_t;
/*! @brief Underlying version type. */
using version_type = std::uint16_t;
/*! @brief Difference type. */
using difference_type = std::int64_t;
/*! @brief Mask to use to get the entity number out of an identifier. */
static constexpr auto entity_mask = 0xFFFFF;
/*! @brief Mask to use to get the version out of an identifier. */
static constexpr auto version_mask = 0xFFF;
/*! @brief Extent of the entity number within an identifier. */
static constexpr auto entity_shift = 20;
};
/**
* @brief Entity traits for a 64 bits entity identifier.
*
* A 64 bits entity identifier guarantees:
*
* * 32 bits for the entity number (an indecently large number).
* * 32 bit for the version (an indecently large number).
*/
template<>
struct entt_traits<std::uint64_t> {
/*! @brief Underlying entity type. */
using entity_type = std::uint64_t;
/*! @brief Underlying version type. */
using version_type = std::uint32_t;
/*! @brief Difference type. */
using difference_type = std::int64_t;
/*! @brief Mask to use to get the entity number out of an identifier. */
static constexpr auto entity_mask = 0xFFFFFFFF;
/*! @brief Mask to use to get the version out of an identifier. */
static constexpr auto version_mask = 0xFFFFFFFF;
/*! @brief Extent of the entity number within an identifier. */
static constexpr auto entity_shift = 32;
};
}
#endif // ENTT_ENTITY_ENTT_TRAITS_HPP

105
src/entt/entity/helper.hpp Normal file
View File

@@ -0,0 +1,105 @@
#ifndef ENTT_ENTITY_HELPER_HPP
#define ENTT_ENTITY_HELPER_HPP
#include <type_traits>
#include "../core/hashed_string.hpp"
#include "../signal/sigh.hpp"
#include "registry.hpp"
#include "utility.hpp"
namespace entt {
/**
* @brief Dependency function prototype.
*
* A _dependency function_ is a built-in listener to use to automatically assign
* components to an entity when a type has a dependency on some other types.
*
* This is a prototype function to use to create dependencies.<br/>
* It isn't intended for direct use, although nothing forbids using it freely.
*
* @tparam Entity A valid entity type (see entt_traits for more details).
* @tparam Component Types of components to assign to an entity if triggered.
* @param registry A valid reference to a registry.
* @param entity A valid entity identifier.
*/
template<typename Entity, typename... Component>
void dependency(Registry<Entity> &registry, const Entity entity) {
using accumulator_type = int[];
accumulator_type accumulator = { ((registry.template has<Component>(entity) ? void() : (registry.template assign<Component>(entity), void())), 0)... };
(void)accumulator;
}
/**
* @brief Connects a dependency function to the given sink.
*
* A _dependency function_ is a built-in listener to use to automatically assign
* components to an entity when a type has a dependency on some other types.
*
* The following adds components `AType` and `AnotherType` whenever `MyType` is
* assigned to an entity:
* @code{.cpp}
* entt::DefaultRegistry registry;
* entt::dependency<AType, AnotherType>(registry.construction<MyType>());
* @endcode
*
* @tparam Dependency Types of components to assign to an entity if triggered.
* @tparam Entity A valid entity type (see entt_traits for more details).
* @param sink A sink object properly initialized.
*/
template<typename... Dependency, typename Entity>
void dependency(Sink<void(Registry<Entity> &, const Entity)> sink) {
sink.template connect<dependency<Entity, Dependency...>>();
}
/**
* @brief Disconnects a dependency function from the given sink.
*
* A _dependency function_ is a built-in listener to use to automatically assign
* components to an entity when a type has a dependency on some other types.
*
* The following breaks the dependency between the component `MyType` and the
* components `AType` and `AnotherType`:
* @code{.cpp}
* entt::DefaultRegistry registry;
* entt::dependency<AType, AnotherType>(entt::break_t{}, registry.construction<MyType>());
* @endcode
*
* @tparam Dependency Types of components used to create the dependency.
* @tparam Entity A valid entity type (see entt_traits for more details).
* @param sink A sink object properly initialized.
*/
template<typename... Dependency, typename Entity>
void dependency(break_t, Sink<void(Registry<Entity> &, const Entity)> sink) {
sink.template disconnect<dependency<Entity, Dependency...>>();
}
/**
* @brief Alias template to ease the assignment of labels to entities.
*
* If used in combination with hashed strings, it simplifies the assignment of
* labels to entities and the use of labels in general where a type would be
* required otherwise.<br/>
* As an example and where the user defined literal for hashed strings hasn't
* been changed:
* @code{.cpp}
* entt::DefaultRegistry registry;
* registry.assign<entt::label<"enemy"_hs>>(entity);
* @endcode
*
* @tparam Value The numeric representation of an instance of hashed string.
*/
template<typename HashedString::hash_type Value>
using label = std::integral_constant<typename HashedString::hash_type, Value>;
}
#endif // ENTT_ENTITY_HELPER_HPP

View File

@@ -0,0 +1,496 @@
#ifndef ENTT_ENTITY_PROTOTYPE_HPP
#define ENTT_ENTITY_PROTOTYPE_HPP
#include <tuple>
#include <utility>
#include <cstddef>
#include <type_traits>
#include <unordered_map>
#include "../config/config.h"
#include "registry.hpp"
namespace entt {
/**
* @brief Prototype container for _concepts_.
*
* A prototype is used to define a _concept_ in terms of components.<br/>
* Prototypes act as templates for those specific types of an application which
* users would otherwise define through a series of component assignments to
* entities. In other words, prototypes can be used to assign components to
* entities of a registry at once.
*
* @note
* Components used along with prototypes must be copy constructible. Prototypes
* wrap component types with custom types, so they do not interfere with other
* users of the registry they were built with.
*
* @warning
* Prototypes directly use their underlying registries to store entities and
* components for their purposes. Users must ensure that the lifetime of a
* registry and its contents exceed that of the prototypes that use it.
*
* @tparam Entity A valid entity type (see entt_traits for more details).
*/
template<typename Entity>
class Prototype final {
using basic_fn_type = void(const Prototype &, Registry<Entity> &, const Entity);
using component_type = typename Registry<Entity>::component_type;
template<typename Component>
struct Wrapper { Component component; };
struct Handler {
basic_fn_type *accommodate;
basic_fn_type *assign;
};
void release() {
if(registry->valid(entity)) {
registry->destroy(entity);
}
}
public:
/*! @brief Registry type. */
using registry_type = Registry<Entity>;
/*! @brief Underlying entity identifier. */
using entity_type = Entity;
/*! @brief Unsigned integer type. */
using size_type = std::size_t;
/**
* @brief Constructs a prototype that is bound to a given registry.
* @param registry A valid reference to a registry.
*/
Prototype(Registry<Entity> &registry)
: registry{&registry},
entity{registry.create()}
{}
/**
* @brief Releases all its resources.
*/
~Prototype() {
release();
}
/*! @brief Copying a prototype isn't allowed. */
Prototype(const Prototype &) = delete;
/**
* @brief Move constructor.
*
* After prototype move construction, instances that have been moved from
* are placed in a valid but unspecified state. It's highly discouraged to
* continue using them.
*
* @param other The instance to move from.
*/
Prototype(Prototype &&other)
: handlers{std::move(other.handlers)},
registry{other.registry},
entity{other.entity}
{
other.entity = ~entity_type{};
}
/*! @brief Copying a prototype isn't allowed. @return This Prototype. */
Prototype & operator=(const Prototype &) = delete;
/**
* @brief Move assignment operator.
*
* After prototype move assignment, instances that have been moved from are
* placed in a valid but unspecified state. It's highly discouraged to
* continue using them.
*
* @param other The instance to move from.
* @return This Prototype.
*/
Prototype & operator=(Prototype &&other) {
if(this != &other) {
auto tmp{std::move(other)};
handlers.swap(tmp.handlers);
std::swap(registry, tmp.registry);
std::swap(entity, tmp.entity);
}
return *this;
}
/**
* @brief Assigns to or replaces the given component of a prototype.
* @tparam Component Type of component to assign or replace.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
Component & set(Args &&... args) {
basic_fn_type *accommodate = [](const Prototype &prototype, Registry<Entity> &other, const Entity dst) {
const auto &wrapper = prototype.registry->template get<Wrapper<Component>>(prototype.entity);
other.template accommodate<Component>(dst, wrapper.component);
};
basic_fn_type *assign = [](const Prototype &prototype, Registry<Entity> &other, const Entity dst) {
if(!other.template has<Component>(dst)) {
const auto &wrapper = prototype.registry->template get<Wrapper<Component>>(prototype.entity);
other.template accommodate<Component>(dst, wrapper.component);
}
};
handlers[registry->template type<Component>()] = Handler{accommodate, assign};
auto &wrapper = registry->template accommodate<Wrapper<Component>>(entity, Component{std::forward<Args>(args)...});
return wrapper.component;
}
/**
* @brief Removes the given component from a prototype.
* @tparam Component Type of component to remove.
*/
template<typename Component>
void unset() ENTT_NOEXCEPT {
registry->template reset<Wrapper<Component>>(entity);
handlers.erase(registry->template type<Component>());
}
/**
* @brief Checks if a prototype owns all the given components.
* @tparam Component Components for which to perform the check.
* @return True if the prototype owns all the components, false otherwise.
*/
template<typename... Component>
bool has() const ENTT_NOEXCEPT {
return registry->template has<Wrapper<Component>...>(entity);
}
/**
* @brief Returns a reference to the given component.
*
* @warning
* Attempting to get a component from a prototype that doesn't own it
* results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* prototype doesn't own an instance of the given component.
*
* @tparam Component Type of component to get.
* @return A reference to the component owned by the prototype.
*/
template<typename Component>
const Component & get() const ENTT_NOEXCEPT {
return registry->template get<Wrapper<Component>>(entity).component;
}
/**
* @brief Returns a reference to the given component.
*
* @warning
* Attempting to get a component from a prototype that doesn't own it
* results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* prototype doesn't own an instance of the given component.
*
* @tparam Component Type of component to get.
* @return A reference to the component owned by the prototype.
*/
template<typename Component>
inline Component & get() ENTT_NOEXCEPT {
return const_cast<Component &>(const_cast<const Prototype *>(this)->get<Component>());
}
/**
* @brief Returns a reference to the given components.
*
* @warning
* Attempting to get components from a prototype that doesn't own them
* results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* prototype doesn't own instances of the given components.
*
* @tparam Component Type of components to get.
* @return References to the components owned by the prototype.
*/
template<typename... Component>
inline std::enable_if_t<(sizeof...(Component) > 1), std::tuple<const Component &...>>
get() const ENTT_NOEXCEPT {
return std::tuple<const Component &...>{get<Component>()...};
}
/**
* @brief Returns a reference to the given components.
*
* @warning
* Attempting to get components from a prototype that doesn't own them
* results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* prototype doesn't own instances of the given components.
*
* @tparam Component Type of components to get.
* @return References to the components owned by the prototype.
*/
template<typename... Component>
inline std::enable_if_t<(sizeof...(Component) > 1), std::tuple<Component &...>>
get() ENTT_NOEXCEPT {
return std::tuple<Component &...>{get<Component>()...};
}
/**
* @brief Creates a new entity using a given prototype.
*
* Utility shortcut, equivalent to the following snippet:
*
* @code{.cpp}
* const auto entity = registry.create();
* prototype(registry, entity);
* @endcode
*
* @note
* The registry may or may not be different from the one already used by
* the prototype. There is also an overload that directly uses the
* underlying registry.
*
* @param other A valid reference to a registry.
* @return A valid entity identifier.
*/
entity_type create(registry_type &other) const {
const auto entity = other.create();
assign(other, entity);
return entity;
}
/**
* @brief Creates a new entity using a given prototype.
*
* Utility shortcut, equivalent to the following snippet:
*
* @code{.cpp}
* const auto entity = registry.create();
* prototype(entity);
* @endcode
*
* @note
* This overload directly uses the underlying registry as a working space.
* Therefore, the components of the prototype and of the entity will share
* the same registry.
*
* @return A valid entity identifier.
*/
inline entity_type create() const {
return create(*registry);
}
/**
* @brief Assigns the components of a prototype to a given entity.
*
* Assigning a prototype to an entity won't overwrite existing components
* under any circumstances.<br/>
* In other words, only those components that the entity doesn't own yet are
* copied over. All the other components remain unchanged.
*
* @note
* The registry may or may not be different from the one already used by
* the prototype. There is also an overload that directly uses the
* underlying registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param other A valid reference to a registry.
* @param dst A valid entity identifier.
*/
void assign(registry_type &other, const entity_type dst) const {
for(auto &handler: handlers) {
handler.second.assign(*this, other, dst);
}
}
/**
* @brief Assigns the components of a prototype to a given entity.
*
* Assigning a prototype to an entity won't overwrite existing components
* under any circumstances.<br/>
* In other words, only those components that the entity doesn't own yet are
* copied over. All the other components remain unchanged.
*
* @note
* This overload directly uses the underlying registry as a working space.
* Therefore, the components of the prototype and of the entity will share
* the same registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param dst A valid entity identifier.
*/
inline void assign(const entity_type dst) const {
assign(*registry, dst);
}
/**
* @brief Assigns or replaces the components of a prototype for an entity.
*
* Existing components are overwritten, if any. All the other components
* will be copied over to the target entity.
*
* @note
* The registry may or may not be different from the one already used by
* the prototype. There is also an overload that directly uses the
* underlying registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param other A valid reference to a registry.
* @param dst A valid entity identifier.
*/
void accommodate(registry_type &other, const entity_type dst) const {
for(auto &handler: handlers) {
handler.second.accommodate(*this, other, dst);
}
}
/**
* @brief Assigns or replaces the components of a prototype for an entity.
*
* Existing components are overwritten, if any. All the other components
* will be copied over to the target entity.
*
* @note
* This overload directly uses the underlying registry as a working space.
* Therefore, the components of the prototype and of the entity will share
* the same registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param dst A valid entity identifier.
*/
inline void accommodate(const entity_type dst) const {
accommodate(*registry, dst);
}
/**
* @brief Assigns the components of a prototype to an entity.
*
* Assigning a prototype to an entity won't overwrite existing components
* under any circumstances.<br/>
* In other words, only the components that the entity doesn't own yet are
* copied over. All the other components remain unchanged.
*
* @note
* The registry may or may not be different from the one already used by
* the prototype. There is also an overload that directly uses the
* underlying registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param other A valid reference to a registry.
* @param dst A valid entity identifier.
*/
inline void operator()(registry_type &other, const entity_type dst) const ENTT_NOEXCEPT {
assign(other, dst);
}
/**
* @brief Assigns the components of a prototype to an entity.
*
* Assigning a prototype to an entity won't overwrite existing components
* under any circumstances.<br/>
* In other words, only the components that the entity doesn't own yet are
* copied over. All the other components remain unchanged.
*
* @note
* This overload directly uses the underlying registry as a working space.
* Therefore, the components of the prototype and of the entity will share
* the same registry.
*
* @warning
* Attempting to use an invalid entity results in undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode in case of
* invalid entity.
*
* @param dst A valid entity identifier.
*/
inline void operator()(const entity_type dst) const ENTT_NOEXCEPT {
assign(*registry, dst);
}
/**
* @brief Creates a new entity using a given prototype.
*
* Utility shortcut, equivalent to the following snippet:
*
* @code{.cpp}
* const auto entity = registry.create();
* prototype(registry, entity);
* @endcode
*
* @note
* The registry may or may not be different from the one already used by
* the prototype. There is also an overload that directly uses the
* underlying registry.
*
* @param other A valid reference to a registry.
* @return A valid entity identifier.
*/
inline entity_type operator()(registry_type &other) const ENTT_NOEXCEPT {
return create(other);
}
/**
* @brief Creates a new entity using a given prototype.
*
* Utility shortcut, equivalent to the following snippet:
*
* @code{.cpp}
* const auto entity = registry.create();
* prototype(entity);
* @endcode
*
* @note
* This overload directly uses the underlying registry as a working space.
* Therefore, the components of the prototype and of the entity will share
* the same registry.
*
* @return A valid entity identifier.
*/
inline entity_type operator()() const ENTT_NOEXCEPT {
return create(*registry);
}
private:
std::unordered_map<component_type, Handler> handlers;
Registry<Entity> *registry;
entity_type entity;
};
/**
* @brief Default prototype
*
* The default prototype is the best choice for almost all the
* applications.<br/>
* Users should have a really good reason to choose something different.
*/
using DefaultPrototype = Prototype<DefaultRegistry::entity_type>;
}
#endif // ENTT_ENTITY_PROTOTYPE_HPP

1629
src/entt/entity/registry.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,720 @@
#ifndef ENTT_ENTITY_SNAPSHOT_HPP
#define ENTT_ENTITY_SNAPSHOT_HPP
#include <array>
#include <cstddef>
#include <utility>
#include <cassert>
#include <iterator>
#include <type_traits>
#include <unordered_map>
#include "../config/config.h"
#include "entt_traits.hpp"
#include "utility.hpp"
namespace entt {
/**
* @brief Forward declaration of the registry class.
*/
template<typename>
class Registry;
/**
* @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 components and tags of interest.<br/>
* This type can be used in both cases if provided with a correctly configured
* output archive.
*
* @tparam Entity A valid entity type (see entt_traits for more details).
*/
template<typename Entity>
class Snapshot final {
/*! @brief A registry is allowed to create snapshots. */
friend class Registry<Entity>;
using follow_fn_type = Entity(const Registry<Entity> &, const Entity);
Snapshot(const Registry<Entity> &registry, Entity seed, follow_fn_type *follow) ENTT_NOEXCEPT
: registry{registry},
seed{seed},
follow{follow}
{}
template<typename Component, typename Archive, typename It>
void get(Archive &archive, std::size_t sz, It first, It last) const {
archive(static_cast<Entity>(sz));
while(first != last) {
const auto entity = *(first++);
if(registry.template has<Component>(entity)) {
archive(entity, registry.template get<Component>(entity));
}
}
}
template<typename... Component, typename Archive, typename It, std::size_t... Indexes>
void component(Archive &archive, It first, It last, std::index_sequence<Indexes...>) const {
std::array<std::size_t, sizeof...(Indexes)> size{};
auto begin = first;
while(begin != last) {
const auto entity = *(begin++);
using accumulator_type = std::size_t[];
accumulator_type accumulator = { (registry.template has<Component>(entity) ? ++size[Indexes] : size[Indexes])... };
(void)accumulator;
}
using accumulator_type = int[];
accumulator_type accumulator = { (get<Component>(archive, size[Indexes], first, last), 0)... };
(void)accumulator;
}
public:
/*! @brief Copying a snapshot isn't allowed. */
Snapshot(const Snapshot &) = delete;
/*! @brief Default move constructor. */
Snapshot(Snapshot &&) = default;
/*! @brief Copying a snapshot isn't allowed. @return This snapshot. */
Snapshot & operator=(const Snapshot &) = delete;
/*! @brief Default move assignment operator. @return This snapshot. */
Snapshot & operator=(Snapshot &&) = default;
/**
* @brief Puts aside all the entities that are still in use.
*
* Entities are serialized along with their versions. Destroyed entities are
* not taken in consideration by this function.
*
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename Archive>
const Snapshot & entities(Archive &archive) const {
archive(static_cast<Entity>(registry.alive()));
registry.each([&archive](const auto entity) { archive(entity); });
return *this;
}
/**
* @brief Puts aside destroyed entities.
*
* Entities are serialized along with their versions. Entities that are
* still in use are not taken in consideration by this function.
*
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename Archive>
const Snapshot & destroyed(Archive &archive) const {
auto size = registry.size() - registry.alive();
archive(static_cast<Entity>(size));
auto curr = seed;
for(; size; --size) {
archive(curr);
curr = follow(registry, curr);
}
return *this;
}
/**
* @brief Puts aside the given component.
*
* Each instance is serialized together with the entity to which it belongs.
* Entities are serialized along with their versions.
*
* @tparam Component Type of component to serialize.
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename Component, typename Archive>
const Snapshot & component(Archive &archive) const {
const auto sz = registry.template size<Component>();
const auto *entities = registry.template data<Component>();
archive(static_cast<Entity>(sz));
for(std::remove_const_t<decltype(sz)> i{}; i < sz; ++i) {
const auto entity = entities[i];
archive(entity, registry.template get<Component>(entity));
};
return *this;
}
/**
* @brief Puts aside the given components.
*
* Each instance is serialized together with the entity to which it belongs.
* Entities are serialized along with their versions.
*
* @tparam Component Types of components to serialize.
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename... Component, typename Archive>
std::enable_if_t<(sizeof...(Component) > 1), const Snapshot &>
component(Archive &archive) const {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (component<Component>(archive), 0)... };
(void)accumulator;
return *this;
}
/**
* @brief Puts aside the given components for the entities in a range.
*
* Each instance is serialized together with the entity to which it belongs.
* Entities are serialized along with their versions.
*
* @tparam Component Types of components 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.
* @return An object of this type to continue creating the snapshot.
*/
template<typename... Component, typename Archive, typename It>
const Snapshot & component(Archive &archive, It first, It last) const {
component<Component...>(archive, first, last, std::make_index_sequence<sizeof...(Component)>{});
return *this;
}
/**
* @brief Puts aside the given tag.
*
* Each instance is serialized together with the entity to which it belongs.
* Entities are serialized along with their versions.
*
* @tparam Tag Type of tag to serialize.
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename Tag, typename Archive>
const Snapshot & tag(Archive &archive) const {
const bool has = registry.template has<Tag>();
// numerical length is forced for tags to facilitate loading
archive(has ? Entity(1): Entity{});
if(has) {
archive(registry.template attachee<Tag>(), registry.template get<Tag>());
}
return *this;
}
/**
* @brief Puts aside the given tags.
*
* Each instance is serialized together with the entity to which it belongs.
* Entities are serialized along with their versions.
*
* @tparam Tag Types of tags to serialize.
* @tparam Archive Type of output archive.
* @param archive A valid reference to an output archive.
* @return An object of this type to continue creating the snapshot.
*/
template<typename... Tag, typename Archive>
std::enable_if_t<(sizeof...(Tag) > 1), const Snapshot &>
tag(Archive &archive) const {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (tag<Tag>(archive), 0)... };
(void)accumulator;
return *this;
}
private:
const Registry<Entity> &registry;
const Entity seed;
follow_fn_type *follow;
};
/**
* @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 Entity A valid entity type (see entt_traits for more details).
*/
template<typename Entity>
class SnapshotLoader final {
/*! @brief A registry is allowed to create snapshot loaders. */
friend class Registry<Entity>;
using assure_fn_type = void(Registry<Entity> &, const Entity, const bool);
SnapshotLoader(Registry<Entity> &registry, assure_fn_type *assure_fn) ENTT_NOEXCEPT
: registry{registry},
assure_fn{assure_fn}
{
// restore a snapshot as a whole requires a clean registry
assert(!registry.capacity());
}
template<typename Archive>
void assure(Archive &archive, bool destroyed) const {
Entity length{};
archive(length);
while(length--) {
Entity entity{};
archive(entity);
assure_fn(registry, entity, destroyed);
}
}
template<typename Type, typename Archive, typename... Args>
void assign(Archive &archive, Args... args) const {
Entity length{};
archive(length);
while(length--) {
Entity entity{};
Type instance{};
archive(entity, instance);
static constexpr auto destroyed = false;
assure_fn(registry, entity, destroyed);
registry.template assign<Type>(args..., entity, static_cast<const Type &>(instance));
}
}
public:
/*! @brief Copying a snapshot loader isn't allowed. */
SnapshotLoader(const SnapshotLoader &) = delete;
/*! @brief Default move constructor. */
SnapshotLoader(SnapshotLoader &&) = default;
/*! @brief Copying a snapshot loader isn't allowed. @return This loader. */
SnapshotLoader & operator=(const SnapshotLoader &) = delete;
/*! @brief Default move assignment operator. @return This loader. */
SnapshotLoader & operator=(SnapshotLoader &&) = default;
/**
* @brief Restores entities that were in use during serialization.
*
* This function restores the entities that were in use during serialization
* and gives them the versions they originally had.
*
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A valid loader to continue restoring data.
*/
template<typename Archive>
const SnapshotLoader & entities(Archive &archive) const {
static constexpr auto destroyed = false;
assure(archive, destroyed);
return *this;
}
/**
* @brief Restores entities that were destroyed during serialization.
*
* This function restores the entities that were destroyed during
* serialization and gives them the versions they originally had.
*
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A valid loader to continue restoring data.
*/
template<typename Archive>
const SnapshotLoader & destroyed(Archive &archive) const {
static constexpr auto destroyed = true;
assure(archive, destroyed);
return *this;
}
/**
* @brief Restores components and assigns them to the right entities.
*
* The template parameter list must be exactly the same used during
* serialization. In the event that the entity to which the component is
* assigned doesn't exist yet, the loader will take care to create it with
* the version it originally had.
*
* @tparam Component Types of components to restore.
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A valid loader to continue restoring data.
*/
template<typename... Component, typename Archive>
const SnapshotLoader & component(Archive &archive) const {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (assign<Component>(archive), 0)... };
(void)accumulator;
return *this;
}
/**
* @brief Restores tags and assigns them to the right entities.
*
* The template parameter list must be exactly the same used during
* serialization. In the event that the entity to which the tag is assigned
* doesn't exist yet, the loader will take care to create it with the
* version it originally had.
*
* @tparam Tag Types of tags to restore.
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A valid loader to continue restoring data.
*/
template<typename... Tag, typename Archive>
const SnapshotLoader & tag(Archive &archive) const {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (assign<Tag>(archive, tag_t{}), 0)... };
(void)accumulator;
return *this;
}
/**
* @brief Destroys those entities that have neither components nor tags.
*
* In case all the entities were serialized but only part of the components
* and tags was saved, it could happen that some of the entities have
* neither components nor tags once restored.<br/>
* This functions helps to identify and destroy those entities.
*
* @return A valid loader to continue restoring data.
*/
const SnapshotLoader & orphans() const {
registry.orphans([this](const auto entity) {
registry.destroy(entity);
});
return *this;
}
private:
Registry<Entity> &registry;
assure_fn_type *assure_fn;
};
/**
* @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 accomodate 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 applications with
* the requirement of transferring somehow parts of the representation side to
* side.
*
* @tparam Entity A valid entity type (see entt_traits for more details).
*/
template<typename Entity>
class ContinuousLoader final {
using traits_type = entt_traits<Entity>;
void destroy(Entity entity) {
const auto it = remloc.find(entity);
if(it == remloc.cend()) {
const auto local = registry.create();
remloc.emplace(entity, std::make_pair(local, true));
registry.destroy(local);
}
}
void restore(Entity entity) {
const auto it = remloc.find(entity);
if(it == remloc.cend()) {
const auto local = registry.create();
remloc.emplace(entity, std::make_pair(local, true));
} else {
remloc[entity].first =
registry.valid(remloc[entity].first)
? remloc[entity].first
: registry.create();
// set the dirty flag
remloc[entity].second = true;
}
}
template<typename Type, typename Member>
std::enable_if_t<std::is_same<Member, Entity>::value>
update(Type &instance, Member Type:: *member) {
instance.*member = map(instance.*member);
}
template<typename Type, typename Member>
std::enable_if_t<std::is_same<typename std::iterator_traits<typename Member::iterator>::value_type, Entity>::value>
update(Type &instance, Member Type:: *member) {
for(auto &entity: instance.*member) {
entity = map(entity);
}
}
template<typename Other, typename Type, typename Member>
std::enable_if_t<!std::is_same<Other, Type>::value>
update(Other &, Member Type:: *) {}
template<typename Archive>
void assure(Archive &archive, void(ContinuousLoader:: *member)(Entity)) {
Entity length{};
archive(length);
while(length--) {
Entity entity{};
archive(entity);
(this->*member)(entity);
}
}
template<typename Component>
void reset() {
for(auto &&ref: remloc) {
const auto local = ref.second.first;
if(registry.valid(local)) {
registry.template reset<Component>(local);
}
}
}
template<typename Other, typename Archive, typename Func, typename... Type, typename... Member>
void assign(Archive &archive, Func func, Member Type:: *... member) {
Entity length{};
archive(length);
while(length--) {
Entity entity{};
Other instance{};
archive(entity, instance);
restore(entity);
using accumulator_type = int[];
accumulator_type accumulator = { 0, (update(instance, member), 0)... };
(void)accumulator;
func(map(entity), instance);
}
}
public:
/*! @brief Underlying entity identifier. */
using entity_type = Entity;
/**
* @brief Constructs a loader that is bound to a given registry.
* @param registry A valid reference to a registry.
*/
ContinuousLoader(Registry<entity_type> &registry) ENTT_NOEXCEPT
: registry{registry}
{}
/*! @brief Copying a snapshot loader isn't allowed. */
ContinuousLoader(const ContinuousLoader &) = delete;
/*! @brief Default move constructor. */
ContinuousLoader(ContinuousLoader &&) = default;
/*! @brief Copying a snapshot loader isn't allowed. @return This loader. */
ContinuousLoader & operator=(const ContinuousLoader &) = delete;
/*! @brief Default move assignment operator. @return This loader. */
ContinuousLoader & operator=(ContinuousLoader &&) = default;
/**
* @brief Restores entities that were in use during serialization.
*
* This function restores the entities that were in use during serialization
* and creates local counterparts for them if required.
*
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A non-const reference to this loader.
*/
template<typename Archive>
ContinuousLoader & entities(Archive &archive) {
assure(archive, &ContinuousLoader::restore);
return *this;
}
/**
* @brief Restores entities that were destroyed during serialization.
*
* This function restores the entities that were destroyed during
* serialization and creates local counterparts for them if required.
*
* @tparam Archive Type of input archive.
* @param archive A valid reference to an input archive.
* @return A non-const reference to this loader.
*/
template<typename Archive>
ContinuousLoader & destroyed(Archive &archive) {
assure(archive, &ContinuousLoader::destroy);
return *this;
}
/**
* @brief Restores components and assigns them to the right entities.
*
* The template parameter list must be exactly the same used during
* serialization. In the event that the entity to which the component is
* assigned doesn't exist yet, the loader will take care to create a local
* counterpart for it.<br/>
* Members can be either data members of type entity_type or containers of
* entities. In both cases, the loader will visit them and update the
* entities by replacing each one with its local counterpart.
*
* @tparam Component Type of component to restore.
* @tparam Archive Type of input archive.
* @tparam Type Types of components to update with local counterparts.
* @tparam Member Types of members to update with their local counterparts.
* @param archive A valid reference to an input archive.
* @param member Members to update with their local counterparts.
* @return A non-const reference to this loader.
*/
template<typename... Component, typename Archive, typename... Type, typename... Member>
ContinuousLoader & component(Archive &archive, Member Type:: *... member) {
auto apply = [this](const auto entity, const auto &component) {
registry.template accommodate<std::decay_t<decltype(component)>>(entity, component);
};
using accumulator_type = int[];
accumulator_type accumulator = { 0, (reset<Component>(), assign<Component>(archive, apply, member...), 0)... };
(void)accumulator;
return *this;
}
/**
* @brief Restores tags and assigns them to the right entities.
*
* The template parameter list must be exactly the same used during
* serialization. In the event that the entity to which the tag is assigned
* doesn't exist yet, the loader will take care to create a local
* counterpart for it.<br/>
* Members can be either data members of type entity_type or containers of
* entities. In both cases, the loader will visit them and update the
* entities by replacing each one with its local counterpart.
*
* @tparam Tag Type of tag to restore.
* @tparam Archive Type of input archive.
* @tparam Type Types of components to update with local counterparts.
* @tparam Member Types of members to update with their local counterparts.
* @param archive A valid reference to an input archive.
* @param member Members to update with their local counterparts.
* @return A non-const reference to this loader.
*/
template<typename... Tag, typename Archive, typename... Type, typename... Member>
ContinuousLoader & tag(Archive &archive, Member Type:: *... member) {
auto apply = [this](const auto entity, const auto &tag) {
registry.template assign<std::decay_t<decltype(tag)>>(tag_t{}, entity, tag);
};
using accumulator_type = int[];
accumulator_type accumulator = { 0, (registry.template remove<Tag>(), assign<Tag>(archive, apply, member...), 0)... };
(void)accumulator;
return *this;
}
/**
* @brief Helps to purge entities that no longer have a conterpart.
*
* Users should invoke this member function after restoring each snapshot,
* unless they know exactly what they are doing.
*
* @return A non-const reference to this loader.
*/
ContinuousLoader & shrink() {
auto it = remloc.begin();
while(it != remloc.cend()) {
const auto local = it->second.first;
bool &dirty = it->second.second;
if(dirty) {
dirty = false;
++it;
} else {
if(registry.valid(local)) {
registry.destroy(local);
}
it = remloc.erase(it);
}
}
return *this;
}
/**
* @brief Destroys those entities that have neither components nor tags.
*
* In case all the entities were serialized but only part of the components
* and tags was saved, it could happen that some of the entities have
* neither components nor tags once restored.<br/>
* This functions helps to identify and destroy those entities.
*
* @return A non-const reference to this loader.
*/
ContinuousLoader & orphans() {
registry.orphans([this](const auto entity) {
registry.destroy(entity);
});
return *this;
}
/**
* @brief Tests if a loader knows about a given entity.
* @param entity An entity identifier.
* @return True if `entity` is managed by the loader, false otherwise.
*/
bool has(entity_type entity) const ENTT_NOEXCEPT {
return (remloc.find(entity) != remloc.cend());
}
/**
* @brief Returns the identifier to which an entity refers.
*
* @warning
* Attempting to use an entity that isn't managed by the loader results in
* undefined behavior.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* loader doesn't knows about the entity.
*
* @param entity An entity identifier.
* @return The identifier to which `entity` refers in the target registry.
*/
entity_type map(entity_type entity) const ENTT_NOEXCEPT {
assert(has(entity));
return remloc.find(entity)->second.first;
}
private:
std::unordered_map<Entity, std::pair<Entity, bool>> remloc;
Registry<Entity> &registry;
};
}
#endif // ENTT_ENTITY_SNAPSHOT_HPP

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
#ifndef ENTT_ENTITY_UTILITY_HPP
#define ENTT_ENTITY_UTILITY_HPP
namespace entt {
/*! @brief Tag class type used to disambiguate overloads. */
struct tag_t final {};
/*! @brief Persistent view type used to disambiguate overloads. */
struct persistent_t final {};
/*! @brief Raw view type used to disambiguate overloads. */
struct raw_t final {};
/*! @brief Break type used to disambiguate overloads. */
struct break_t final {};
}
#endif // ENTT_ENTITY_UTILITY_HPP

1889
src/entt/entity/view.hpp Normal file

File diff suppressed because it is too large Load Diff

25
src/entt/entt.hpp Normal file
View File

@@ -0,0 +1,25 @@
#include "core/algorithm.hpp"
#include "core/family.hpp"
#include "core/hashed_string.hpp"
#include "core/ident.hpp"
#include "core/monostate.hpp"
#include "entity/actor.hpp"
#include "entity/entity.hpp"
#include "entity/entt_traits.hpp"
#include "entity/helper.hpp"
#include "entity/prototype.hpp"
#include "entity/registry.hpp"
#include "entity/snapshot.hpp"
#include "entity/sparse_set.hpp"
#include "entity/utility.hpp"
#include "entity/view.hpp"
#include "locator/locator.hpp"
#include "process/process.hpp"
#include "process/scheduler.hpp"
#include "resource/cache.hpp"
#include "resource/handle.hpp"
#include "resource/loader.hpp"
#include "signal/delegate.hpp"
#include "signal/dispatcher.hpp"
#include "signal/emitter.hpp"
#include "signal/sigh.hpp"

View File

@@ -0,0 +1,116 @@
#ifndef ENTT_LOCATOR_LOCATOR_HPP
#define ENTT_LOCATOR_LOCATOR_HPP
#include <memory>
#include <utility>
#include <cassert>
#include "../config/config.h"
namespace entt {
/**
* @brief Service locator, nothing more.
*
* A service locator can be used to do what it promises: locate services.<br/>
* Usually service locators are tightly bound to the services they expose and
* thus it's hard to define a general purpose class to do that. This template
* based implementation tries to fill the gap and to get rid of the burden of
* defining a different specific locator for each application.
*
* @tparam Service Type of service managed by the locator.
*/
template<typename Service>
struct ServiceLocator final {
/*! @brief Type of service offered. */
using service_type = Service;
/*! @brief Default constructor, deleted on purpose. */
ServiceLocator() = delete;
/*! @brief Default destructor, deleted on purpose. */
~ServiceLocator() = delete;
/**
* @brief Tests if a valid service implementation is set.
* @return True if the service is set, false otherwise.
*/
inline static bool empty() ENTT_NOEXCEPT {
return !static_cast<bool>(service);
}
/**
* @brief Returns a weak pointer to a service implementation, if any.
*
* Clients of a service shouldn't retain references to it. The recommended
* way is to retrieve the service implementation currently set each and
* every time the need of using it arises. Otherwise users can incur in
* unexpected behaviors.
*
* @return A reference to the service implementation currently set, if any.
*/
inline static std::weak_ptr<Service> get() ENTT_NOEXCEPT {
return service;
}
/**
* @brief Returns a weak reference to a service implementation, if any.
*
* Clients of a service shouldn't retain references to it. The recommended
* way is to retrieve the service implementation currently set each and
* every time the need of using it arises. Otherwise users can incur in
* unexpected behaviors.
*
* @warning
* In case no service implementation has been set, a call to this function
* results in undefined behavior.
*
* @return A reference to the service implementation currently set, if any.
*/
inline static Service & ref() ENTT_NOEXCEPT {
return *service;
}
/**
* @brief Sets or replaces a service.
* @tparam Impl Type of the new service to use.
* @tparam Args Types of arguments to use to construct the service.
* @param args Parameters to use to construct the service.
*/
template<typename Impl = Service, typename... Args>
inline static void set(Args &&... args) {
service = std::make_shared<Impl>(std::forward<Args>(args)...);
}
/**
* @brief Sets or replaces a service.
* @param ptr Service to use to replace the current one.
*/
inline static void set(std::shared_ptr<Service> ptr) {
assert(static_cast<bool>(ptr));
service = std::move(ptr);
}
/**
* @brief Resets a service.
*
* The service is no longer valid after a reset.
*/
inline static void reset() {
service.reset();
}
private:
static std::shared_ptr<Service> service;
};
template<typename Service>
std::shared_ptr<Service> ServiceLocator<Service>::service{};
}
#endif // ENTT_LOCATOR_LOCATOR_HPP

View File

@@ -0,0 +1,339 @@
#ifndef ENTT_PROCESS_PROCESS_HPP
#define ENTT_PROCESS_PROCESS_HPP
#include <type_traits>
#include <functional>
#include <utility>
#include "../config/config.h"
namespace entt {
/**
* @brief Base class for processes.
*
* This class stays true to the CRTP idiom. Derived classes must specify what's
* the intended type for elapsed times.<br/>
* A process should expose publicly the following member functions whether
* required:
*
* * @code{.cpp}
* void update(Delta, void *);
* @endcode
*
* It's invoked once per tick until a process is explicitly aborted or it
* terminates either with or without errors. Even though it's not mandatory to
* declare this member function, as a rule of thumb each process should at
* least define it to work properly. The `void *` parameter is an opaque
* pointer to user data (if any) forwarded directly to the process during an
* update.
*
* * @code{.cpp}
* void init(void *);
* @endcode
*
* It's invoked at the first tick, immediately before an update. The `void *`
* parameter is an opaque pointer to user data (if any) forwarded directly to
* the process during an update.
*
* * @code{.cpp}
* void succeeded();
* @endcode
*
* It's invoked in case of success, immediately after an update and during the
* same tick.
*
* * @code{.cpp}
* void failed();
* @endcode
*
* It's invoked in case of errors, immediately after an update and during the
* same tick.
*
* * @code{.cpp}
* void aborted();
* @endcode
*
* It's invoked only if a process is explicitly aborted. There is no guarantee
* that it executes in the same tick, this depends solely on whether the
* process is aborted immediately or not.
*
* Derived classes can change the internal state of a process by invoking the
* `succeed` and `fail` protected member functions and even pause or unpause the
* process itself.
*
* @sa Scheduler
*
* @tparam Derived Actual type of process that extends the class template.
* @tparam Delta Type to use to provide elapsed time.
*/
template<typename Derived, typename Delta>
class Process {
enum class State: unsigned int {
UNINITIALIZED = 0,
RUNNING,
PAUSED,
SUCCEEDED,
FAILED,
ABORTED,
FINISHED
};
template<State state>
using tag = std::integral_constant<State, state>;
template<typename Target = Derived>
auto tick(int, tag<State::UNINITIALIZED>, void *data)
-> decltype(std::declval<Target>().init(data)) {
static_cast<Target *>(this)->init(data);
}
template<typename Target = Derived>
auto tick(int, tag<State::RUNNING>, Delta delta, void *data)
-> decltype(std::declval<Target>().update(delta, data)) {
static_cast<Target *>(this)->update(delta, data);
}
template<typename Target = Derived>
auto tick(int, tag<State::SUCCEEDED>)
-> decltype(std::declval<Target>().succeeded()) {
static_cast<Target *>(this)->succeeded();
}
template<typename Target = Derived>
auto tick(int, tag<State::FAILED>)
-> decltype(std::declval<Target>().failed()) {
static_cast<Target *>(this)->failed();
}
template<typename Target = Derived>
auto tick(int, tag<State::ABORTED>)
-> decltype(std::declval<Target>().aborted()) {
static_cast<Target *>(this)->aborted();
}
template<State S, typename... Args>
void tick(char, tag<S>, Args &&...) const ENTT_NOEXCEPT {}
protected:
/**
* @brief Terminates a process with success if it's still alive.
*
* The function is idempotent and it does nothing if the process isn't
* alive.
*/
void succeed() ENTT_NOEXCEPT {
if(alive()) {
current = State::SUCCEEDED;
}
}
/**
* @brief Terminates a process with errors if it's still alive.
*
* The function is idempotent and it does nothing if the process isn't
* alive.
*/
void fail() ENTT_NOEXCEPT {
if(alive()) {
current = State::FAILED;
}
}
/**
* @brief Stops a process if it's in a running state.
*
* The function is idempotent and it does nothing if the process isn't
* running.
*/
void pause() ENTT_NOEXCEPT {
if(current == State::RUNNING) {
current = State::PAUSED;
}
}
/**
* @brief Restarts a process if it's paused.
*
* The function is idempotent and it does nothing if the process isn't
* paused.
*/
void unpause() ENTT_NOEXCEPT {
if(current == State::PAUSED) {
current = State::RUNNING;
}
}
public:
/*! @brief Type used to provide elapsed time. */
using delta_type = Delta;
/*! @brief Default destructor. */
virtual ~Process() ENTT_NOEXCEPT {
static_assert(std::is_base_of<Process, Derived>::value, "!");
}
/**
* @brief Aborts a process if it's still alive.
*
* The function is idempotent and it does nothing if the process isn't
* alive.
*
* @param immediately Requests an immediate operation.
*/
void abort(const bool immediately = false) ENTT_NOEXCEPT {
if(alive()) {
current = State::ABORTED;
if(immediately) {
tick(0);
}
}
}
/**
* @brief Returns true if a process is either running or paused.
* @return True if the process is still alive, false otherwise.
*/
bool alive() const ENTT_NOEXCEPT {
return current == State::RUNNING || current == State::PAUSED;
}
/**
* @brief Returns true if a process is already terminated.
* @return True if the process is terminated, false otherwise.
*/
bool dead() const ENTT_NOEXCEPT {
return current == State::FINISHED;
}
/**
* @brief Returns true if a process is currently paused.
* @return True if the process is paused, false otherwise.
*/
bool paused() const ENTT_NOEXCEPT {
return current == State::PAUSED;
}
/**
* @brief Returns true if a process terminated with errors.
* @return True if the process terminated with errors, false otherwise.
*/
bool rejected() const ENTT_NOEXCEPT {
return stopped;
}
/**
* @brief Updates a process and its internal state if required.
* @param delta Elapsed time.
* @param data Optional data.
*/
void tick(const Delta delta, void *data = nullptr) {
switch (current) {
case State::UNINITIALIZED:
tick(0, tag<State::UNINITIALIZED>{}, data);
current = State::RUNNING;
// no break on purpose, tasks are executed immediately
case State::RUNNING:
tick(0, tag<State::RUNNING>{}, delta, data);
default:
// suppress warnings
break;
}
// if it's dead, it must be notified and removed immediately
switch(current) {
case State::SUCCEEDED:
tick(0, tag<State::SUCCEEDED>{});
current = State::FINISHED;
break;
case State::FAILED:
tick(0, tag<State::FAILED>{});
current = State::FINISHED;
stopped = true;
break;
case State::ABORTED:
tick(0, tag<State::ABORTED>{});
current = State::FINISHED;
stopped = true;
break;
default:
// suppress warnings
break;
}
}
private:
State current{State::UNINITIALIZED};
bool stopped{false};
};
/**
* @brief Adaptor for lambdas and functors to turn them into processes.
*
* Lambdas and functors can't be used directly with a scheduler for they are not
* properly defined processes with managed life cycles.<br/>
* This class helps in filling the gap and turning lambdas and functors into
* full featured processes usable by a scheduler.
*
* The signature of the function call operator should be equivalent to the
* following:
*
* @code{.cpp}
* void(Delta delta, void *data, auto succeed, auto fail);
* @endcode
*
* Where:
*
* * `delta` is the elapsed time.
* * `data` is an opaque pointer to user data if any, `nullptr` otherwise.
* * `succeed` is a function to call when a process terminates with success.
* * `fail` is a function to call when a process terminates with errors.
*
* The signature of the function call operator of both `succeed` and `fail`
* is equivalent to the following:
*
* @code{.cpp}
* void();
* @endcode
*
* Usually users shouldn't worry about creating adaptors. A scheduler will
* create them internally each and avery time a lambda or a functor is used as
* a process.
*
* @sa Process
* @sa Scheduler
*
* @tparam Func Actual type of process.
* @tparam Delta Type to use to provide elapsed time.
*/
template<typename Func, typename Delta>
struct ProcessAdaptor: Process<ProcessAdaptor<Func, Delta>, Delta>, private Func {
/**
* @brief Constructs a process adaptor from a lambda or a functor.
* @tparam Args Types of arguments to use to initialize the actual process.
* @param args Parameters to use to initialize the actual process.
*/
template<typename... Args>
ProcessAdaptor(Args &&... args)
: Func{std::forward<Args>(args)...}
{}
/**
* @brief Updates a process and its internal state if required.
* @param delta Elapsed time.
* @param data Optional data.
*/
void update(const Delta delta, void *data) {
Func::operator()(delta, data, [this]() { this->succeed(); }, [this]() { this->fail(); });
}
};
}
#endif // ENTT_PROCESS_PROCESS_HPP

View File

@@ -0,0 +1,311 @@
#ifndef ENTT_PROCESS_SCHEDULER_HPP
#define ENTT_PROCESS_SCHEDULER_HPP
#include <vector>
#include <memory>
#include <utility>
#include <algorithm>
#include <type_traits>
#include "../config/config.h"
#include "process.hpp"
namespace entt {
/**
* @brief Cooperative scheduler for processes.
*
* A cooperative scheduler runs processes and helps managing their life cycles.
*
* Each process is invoked once per tick. If a process terminates, it's
* removed automatically from the scheduler and it's never invoked again.<br/>
* A process can also have a child. In this case, the process is replaced with
* its child when it terminates if it returns with success. In case of errors,
* both the process and its child are discarded.
*
* Example of use (pseudocode):
*
* @code{.cpp}
* scheduler.attach([](auto delta, void *, auto succeed, auto fail) {
* // code
* }).then<MyProcess>(arguments...);
* @endcode
*
* In order to invoke all scheduled processes, call the `update` member function
* passing it the elapsed time to forward to the tasks.
*
* @sa Process
*
* @tparam Delta Type to use to provide elapsed time.
*/
template<typename Delta>
class Scheduler final {
struct ProcessHandler final {
using instance_type = std::unique_ptr<void, void(*)(void *)>;
using update_fn_type = bool(ProcessHandler &, Delta, void *);
using abort_fn_type = void(ProcessHandler &, bool);
using next_type = std::unique_ptr<ProcessHandler>;
instance_type instance;
update_fn_type *update;
abort_fn_type *abort;
next_type next;
};
struct Then final {
Then(ProcessHandler *handler)
: handler{handler}
{}
template<typename Proc, typename... Args>
decltype(auto) then(Args &&... args) && {
static_assert(std::is_base_of<Process<Proc, Delta>, Proc>::value, "!");
handler = Scheduler::then<Proc>(handler, std::forward<Args>(args)...);
return std::move(*this);
}
template<typename Func>
decltype(auto) then(Func &&func) && {
using Proc = ProcessAdaptor<std::decay_t<Func>, Delta>;
return std::move(*this).template then<Proc>(std::forward<Func>(func));
}
private:
ProcessHandler *handler;
};
template<typename Proc>
static bool update(ProcessHandler &handler, const Delta delta, void *data) {
auto *process = static_cast<Proc *>(handler.instance.get());
process->tick(delta, data);
auto dead = process->dead();
if(dead) {
if(handler.next && !process->rejected()) {
handler = std::move(*handler.next);
dead = handler.update(handler, delta, data);
} else {
handler.instance.reset();
}
}
return dead;
}
template<typename Proc>
static void abort(ProcessHandler &handler, const bool immediately) {
static_cast<Proc *>(handler.instance.get())->abort(immediately);
}
template<typename Proc>
static void deleter(void *proc) {
delete static_cast<Proc *>(proc);
}
template<typename Proc, typename... Args>
static auto then(ProcessHandler *handler, Args &&... args) {
if(handler) {
auto proc = typename ProcessHandler::instance_type{new Proc{std::forward<Args>(args)...}, &Scheduler::deleter<Proc>};
handler->next.reset(new ProcessHandler{std::move(proc), &Scheduler::update<Proc>, &Scheduler::abort<Proc>, nullptr});
handler = handler->next.get();
}
return handler;
}
public:
/*! @brief Unsigned integer type. */
using size_type = typename std::vector<ProcessHandler>::size_type;
/*! @brief Default constructor. */
Scheduler() ENTT_NOEXCEPT = default;
/*! @brief Copying a scheduler isn't allowed. */
Scheduler(const Scheduler &) = delete;
/*! @brief Default move constructor. */
Scheduler(Scheduler &&) = default;
/*! @brief Copying a scheduler isn't allowed. @return This scheduler. */
Scheduler & operator=(const Scheduler &) = delete;
/*! @brief Default move assignment operator. @return This scheduler. */
Scheduler & operator=(Scheduler &&) = default;
/**
* @brief Number of processes currently scheduled.
* @return Number of processes currently scheduled.
*/
size_type size() const ENTT_NOEXCEPT {
return handlers.size();
}
/**
* @brief Returns true if at least a process is currently scheduled.
* @return True if there are scheduled processes, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return handlers.empty();
}
/**
* @brief Discards all scheduled processes.
*
* Processes aren't aborted. They are discarded along with their children
* and never executed again.
*/
void clear() {
handlers.clear();
}
/**
* @brief Schedules a process for the next tick.
*
* Returned value is an opaque object that can be used to attach a child to
* the given process. The child is automatically scheduled when the process
* terminates and only if the process returns with success.
*
* Example of use (pseudocode):
*
* @code{.cpp}
* // schedules a task in the form of a process class
* scheduler.attach<MyProcess>(arguments...)
* // appends a child in the form of a lambda function
* .then([](auto delta, void *, auto succeed, auto fail) {
* // code
* })
* // appends a child in the form of another process class
* .then<MyOtherProcess>();
* @endcode
*
* @tparam Proc Type of process to schedule.
* @tparam Args Types of arguments to use to initialize the process.
* @param args Parameters to use to initialize the process.
* @return An opaque object to use to concatenate processes.
*/
template<typename Proc, typename... Args>
auto attach(Args &&... args) {
static_assert(std::is_base_of<Process<Proc, Delta>, Proc>::value, "!");
auto proc = typename ProcessHandler::instance_type{new Proc{std::forward<Args>(args)...}, &Scheduler::deleter<Proc>};
ProcessHandler handler{std::move(proc), &Scheduler::update<Proc>, &Scheduler::abort<Proc>, nullptr};
handlers.push_back(std::move(handler));
return Then{&handlers.back()};
}
/**
* @brief Schedules a process for the next tick.
*
* A process can be either a lambda or a functor. The scheduler wraps both
* of them in a process adaptor internally.<br/>
* The signature of the function call operator should be equivalent to the
* following:
*
* @code{.cpp}
* void(Delta delta, auto succeed, auto fail);
* @endcode
*
* Where:
*
* * `delta` is the elapsed time.
* * `succeed` is a function to call when a process terminates with success.
* * `fail` is a function to call when a process terminates with errors.
*
* The signature of the function call operator of both `succeed` and `fail`
* is equivalent to the following:
*
* @code{.cpp}
* void();
* @endcode
*
* Returned value is an opaque object that can be used to attach a child to
* the given process. The child is automatically scheduled when the process
* terminates and only if the process returns with success.
*
* Example of use (pseudocode):
*
* @code{.cpp}
* // schedules a task in the form of a lambda function
* scheduler.attach([](auto delta, void *, auto succeed, auto fail) {
* // code
* })
* // appends a child in the form of another lambda function
* .then([](auto delta, void *, auto succeed, auto fail) {
* // code
* })
* // appends a child in the form of a process class
* .then<MyProcess>(arguments...);
* @endcode
*
* @sa ProcessAdaptor
*
* @tparam Func Type of process to schedule.
* @param func Either a lambda or a functor to use as a process.
* @return An opaque object to use to concatenate processes.
*/
template<typename Func>
auto attach(Func &&func) {
using Proc = ProcessAdaptor<std::decay_t<Func>, Delta>;
return attach<Proc>(std::forward<Func>(func));
}
/**
* @brief Updates all scheduled processes.
*
* All scheduled processes are executed in no specific order.<br/>
* If a process terminates with success, it's replaced with its child, if
* any. Otherwise, if a process terminates with an error, it's removed along
* with its child.
*
* @param delta Elapsed time.
* @param data Optional data.
*/
void update(const Delta delta, void *data = nullptr) {
bool clean = false;
for(auto pos = handlers.size(); pos; --pos) {
auto &handler = handlers[pos-1];
const bool dead = handler.update(handler, delta, data);
clean = clean || dead;
}
if(clean) {
handlers.erase(std::remove_if(handlers.begin(), handlers.end(), [](auto &handler) {
return !handler.instance;
}), handlers.end());
}
}
/**
* @brief Aborts all scheduled processes.
*
* Unless an immediate operation is requested, the abort is scheduled for
* the next tick. Processes won't be executed anymore in any case.<br/>
* Once a process is fully aborted and thus finished, it's discarded along
* with its child, if any.
*
* @param immediately Requests an immediate operation.
*/
void abort(const bool immediately = false) {
decltype(handlers) exec;
exec.swap(handlers);
std::for_each(exec.begin(), exec.end(), [immediately](auto &handler) {
handler.abort(handler, immediately);
});
std::move(handlers.begin(), handlers.end(), std::back_inserter(exec));
handlers.swap(exec);
}
private:
std::vector<ProcessHandler> handlers{};
};
}
#endif // ENTT_PROCESS_SCHEDULER_HPP

201
src/entt/resource/cache.hpp Normal file
View File

@@ -0,0 +1,201 @@
#ifndef ENTT_RESOURCE_CACHE_HPP
#define ENTT_RESOURCE_CACHE_HPP
#include <memory>
#include <utility>
#include <type_traits>
#include <unordered_map>
#include "../config/config.h"
#include "../core/hashed_string.hpp"
#include "handle.hpp"
#include "loader.hpp"
namespace entt {
/**
* @brief Simple cache for resources of a given type.
*
* Minimal implementation of a cache for resources of a given type. It doesn't
* offer much functionalities but it's suitable for small or medium sized
* applications and can be freely inherited to add targeted functionalities for
* large sized applications.
*
* @tparam Resource Type of resources managed by a cache.
*/
template<typename Resource>
class ResourceCache {
using container_type = std::unordered_map<HashedString::hash_type, std::shared_ptr<Resource>>;
public:
/*! @brief Unsigned integer type. */
using size_type = typename container_type::size_type;
/*! @brief Type of resources managed by a cache. */
using resource_type = HashedString;
/*! @brief Default constructor. */
ResourceCache() = default;
/*! @brief Copying a cache isn't allowed. */
ResourceCache(const ResourceCache &) ENTT_NOEXCEPT = delete;
/*! @brief Default move constructor. */
ResourceCache(ResourceCache &&) ENTT_NOEXCEPT = default;
/*! @brief Copying a cache isn't allowed. @return This cache. */
ResourceCache & operator=(const ResourceCache &) ENTT_NOEXCEPT = delete;
/*! @brief Default move assignment operator. @return This cache. */
ResourceCache & operator=(ResourceCache &&) ENTT_NOEXCEPT = default;
/**
* @brief Number of resources managed by a cache.
* @return Number of resources currently stored.
*/
size_type size() const ENTT_NOEXCEPT {
return resources.size();
}
/**
* @brief Returns true if a cache contains no resources, false otherwise.
* @return True if the cache contains no resources, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return resources.empty();
}
/**
* @brief Clears a cache and discards all its resources.
*
* Handles are not invalidated and the memory used by a resource isn't
* freed as long as at least a handle keeps the resource itself alive.
*/
void clear() ENTT_NOEXCEPT {
resources.clear();
}
/**
* @brief Loads the resource that corresponds to a given identifier.
*
* In case an identifier isn't already present in the cache, it loads its
* resource and stores it aside for future uses. Arguments are forwarded
* directly to the loader in order to construct properly the requested
* resource.
*
* @note
* If the identifier is already present in the cache, this function does
* nothing and the arguments are simply discarded.
*
* @tparam Loader Type of loader to use to load the resource if required.
* @tparam Args Types of arguments to use to load the resource if required.
* @param id Unique resource identifier.
* @param args Arguments to use to load the resource if required.
* @return True if the resource is ready to use, false otherwise.
*/
template<typename Loader, typename... Args>
bool load(const resource_type id, Args &&... args) {
static_assert(std::is_base_of<ResourceLoader<Loader, Resource>, Loader>::value, "!");
bool loaded = true;
if(resources.find(id) == resources.cend()) {
std::shared_ptr<Resource> resource = Loader{}.get(std::forward<Args>(args)...);
loaded = (static_cast<bool>(resource) ? (resources[id] = std::move(resource), loaded) : false);
}
return loaded;
}
/**
* @brief Reloads a resource or loads it for the first time if not present.
*
* Equivalent to the following snippet (pseudocode):
*
* @code{.cpp}
* cache.discard(id);
* cache.load(id, args...);
* @endcode
*
* Arguments are forwarded directly to the loader in order to construct
* properly the requested resource.
*
* @tparam Loader Type of loader to use to load the resource.
* @tparam Args Types of arguments to use to load the resource.
* @param id Unique resource identifier.
* @param args Arguments to use to load the resource.
* @return True if the resource is ready to use, false otherwise.
*/
template<typename Loader, typename... Args>
bool reload(const resource_type id, Args &&... args) {
return (discard(id), load<Loader>(id, std::forward<Args>(args)...));
}
/**
* @brief Creates a temporary handle for a resource.
*
* Arguments are forwarded directly to the loader in order to construct
* properly the requested resource. The handle isn't stored aside and the
* cache isn't in charge of the lifetime of the resource itself.
*
* @tparam Loader Type of loader to use to load the resource.
* @tparam Args Types of arguments to use to load the resource.
* @param args Arguments to use to load the resource.
* @return A handle for the given resource.
*/
template<typename Loader, typename... Args>
ResourceHandle<Resource> temp(Args &&... args) const {
return { Loader{}.get(std::forward<Args>(args)...) };
}
/**
* @brief Creates a handle for a given resource identifier.
*
* A resource handle can be in a either valid or invalid state. In other
* terms, a resource handle is properly initialized with a resource if the
* cache contains the resource itself. Otherwise the returned handle is
* uninitialized and accessing it results in undefined behavior.
*
* @sa ResourceHandle
*
* @param id Unique resource identifier.
* @return A handle for the given resource.
*/
ResourceHandle<Resource> handle(const resource_type id) const {
auto it = resources.find(id);
return { it == resources.end() ? nullptr : it->second };
}
/**
* @brief Checks if a cache contains a given identifier.
* @param id Unique resource identifier.
* @return True if the cache contains the resource, false otherwise.
*/
bool contains(const resource_type id) const ENTT_NOEXCEPT {
return (resources.find(id) != resources.cend());
}
/**
* @brief Discards the resource that corresponds to a given identifier.
*
* Handles are not invalidated and the memory used by the resource isn't
* freed as long as at least a handle keeps the resource itself alive.
*
* @param id Unique resource identifier.
*/
void discard(const resource_type id) ENTT_NOEXCEPT {
auto it = resources.find(id);
if(it != resources.end()) {
resources.erase(it);
}
}
private:
container_type resources;
};
}
#endif // ENTT_RESOURCE_CACHE_HPP

View File

@@ -0,0 +1,116 @@
#ifndef ENTT_RESOURCE_HANDLE_HPP
#define ENTT_RESOURCE_HANDLE_HPP
#include <memory>
#include <utility>
#include <cassert>
#include "../config/config.h"
namespace entt {
template<typename Resource>
class ResourceCache;
/**
* @brief Shared resource handle.
*
* A shared resource handle is a small class that wraps a resource and keeps it
* alive even if it's deleted from the cache. It can be either copied or
* moved. A handle shares a reference to the same resource with all the other
* handles constructed for the same identifier.<br/>
* As a rule of thumb, resources should never be copied nor moved. Handles are
* the way to go to keep references to them.
*
* @tparam Resource Type of resource managed by a handle.
*/
template<typename Resource>
class ResourceHandle final {
/*! @brief Resource handles are friends of their caches. */
friend class ResourceCache<Resource>;
ResourceHandle(std::shared_ptr<Resource> res) ENTT_NOEXCEPT
: resource{std::move(res)}
{}
public:
/*! @brief Default copy constructor. */
ResourceHandle(const ResourceHandle &) ENTT_NOEXCEPT = default;
/*! @brief Default move constructor. */
ResourceHandle(ResourceHandle &&) ENTT_NOEXCEPT = default;
/*! @brief Default copy assignment operator. @return This handle. */
ResourceHandle & operator=(const ResourceHandle &) ENTT_NOEXCEPT = default;
/*! @brief Default move assignment operator. @return This handle. */
ResourceHandle & operator=(ResourceHandle &&) ENTT_NOEXCEPT = default;
/**
* @brief Gets a reference to the managed resource.
*
* @warning
* The behavior is undefined if the handle doesn't contain a resource.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* handle is empty.
*
* @return A reference to the managed resource.
*/
const Resource & get() const ENTT_NOEXCEPT {
assert(static_cast<bool>(resource));
return *resource;
}
/**
* @brief Casts a handle and gets a reference to the managed resource.
*
* @warning
* The behavior is undefined if the handle doesn't contain a resource.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* handle is empty.
*/
inline operator const Resource &() const ENTT_NOEXCEPT { return get(); }
/**
* @brief Dereferences a handle to obtain the managed resource.
*
* @warning
* The behavior is undefined if the handle doesn't contain a resource.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* handle is empty.
*
* @return A reference to the managed resource.
*/
inline const Resource & operator *() const ENTT_NOEXCEPT { return get(); }
/**
* @brief Gets a pointer to the managed resource from a handle.
*
* @warning
* The behavior is undefined if the handle doesn't contain a resource.<br/>
* An assertion will abort the execution at runtime in debug mode if the
* handle is empty.
*
* @return A pointer to the managed resource or `nullptr` if the handle
* contains no resource at all.
*/
inline const Resource * operator ->() const ENTT_NOEXCEPT {
assert(static_cast<bool>(resource));
return resource.get();
}
/**
* @brief Returns true if the handle contains a resource, false otherwise.
*/
explicit operator bool() const { return static_cast<bool>(resource); }
private:
std::shared_ptr<Resource> resource;
};
}
#endif // ENTT_RESOURCE_HANDLE_HPP

View File

@@ -0,0 +1,62 @@
#ifndef ENTT_RESOURCE_LOADER_HPP
#define ENTT_RESOURCE_LOADER_HPP
#include <memory>
namespace entt {
template<typename Resource>
class ResourceCache;
/**
* @brief Base class for resource loaders.
*
* Resource loaders must inherit from this class and stay true to the CRTP
* idiom. Moreover, a resource loader must expose a public, const member
* function named `load` that accepts a variable number of arguments and returns
* a shared pointer to the resource just created.<br/>
* As an example:
*
* @code{.cpp}
* struct MyResource {};
*
* struct MyLoader: entt::ResourceLoader<MyLoader, MyResource> {
* std::shared_ptr<MyResource> load(int) const {
* // use the integer value somehow
* return std::make_shared<MyResource>();
* }
* };
* @endcode
*
* In general, resource loaders should not have a state or retain data of any
* type. They should let the cache manage their resources instead.
*
* @note
* Base class and CRTP idiom aren't strictly required with the current
* implementation. One could argue that a cache can easily work with loaders of
* any type. However, future changes won't be breaking ones by forcing the use
* of a base class today and that's why the model is already in its place.
*
* @tparam Loader Type of the derived class.
* @tparam Resource Type of resource for which to use the loader.
*/
template<typename Loader, typename Resource>
class ResourceLoader {
/*! @brief Resource loaders are friends of their caches. */
friend class ResourceCache<Resource>;
template<typename... Args>
std::shared_ptr<Resource> get(Args &&... args) const {
return static_cast<const Loader *>(this)->load(std::forward<Args>(args)...);
}
};
}
#endif // ENTT_RESOURCE_LOADER_HPP

View File

@@ -0,0 +1,145 @@
#ifndef ENTT_SIGNAL_DELEGATE_HPP
#define ENTT_SIGNAL_DELEGATE_HPP
#include <utility>
#include "../config/config.h"
namespace entt {
/**
* @brief Basic delegate implementation.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*/
template<typename>
class Delegate;
/**
* @brief Utility class to send around functions and member functions.
*
* Unmanaged delegate for function pointers and member functions. Users of this
* class are in charge of disconnecting instances before deleting them.
*
* A delegate can be used as general purpose invoker with no memory overhead for
* free functions and member functions provided along with an instance on which
* to invoke them.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
class Delegate<Ret(Args...)> final {
using proto_fn_type = Ret(void *, Args...);
using stub_type = std::pair<void *, proto_fn_type *>;
template<Ret(*Function)(Args...)>
static Ret proto(void *, Args... args) {
return (Function)(args...);
}
template<typename Class, Ret(Class:: *Member)(Args...)>
static Ret proto(void *instance, Args... args) {
return (static_cast<Class *>(instance)->*Member)(args...);
}
public:
/*! @brief Default constructor. */
Delegate() ENTT_NOEXCEPT
: stub{}
{}
/**
* @brief Checks whether a delegate actually stores a listener.
* @return True if the delegate is empty, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
// no need to test also stub.first
return !stub.second;
}
/**
* @brief Binds a free function to a delegate.
* @tparam Function A valid free function pointer.
*/
template<Ret(*Function)(Args...)>
void connect() ENTT_NOEXCEPT {
stub = std::make_pair(nullptr, &proto<Function>);
}
/**
* @brief Connects a member function for a given instance to a delegate.
*
* The delegate isn't responsible for the connected object. Users must
* guarantee that the lifetime of the instance overcomes the one of the
* delegate.
*
* @tparam Class Type of class to which the member function belongs.
* @tparam Member Member function to connect to the delegate.
* @param instance A valid instance of type pointer to `Class`.
*/
template<typename Class, Ret(Class:: *Member)(Args...)>
void connect(Class *instance) ENTT_NOEXCEPT {
stub = std::make_pair(instance, &proto<Class, Member>);
}
/**
* @brief Resets a delegate.
*
* After a reset, a delegate can be safely invoked with no effect.
*/
void reset() ENTT_NOEXCEPT {
stub.second = nullptr;
}
/**
* @brief Triggers a delegate.
* @param args Arguments to use to invoke the underlying function.
* @return The value returned by the underlying function.
*/
Ret operator()(Args... args) const {
return stub.second(stub.first, args...);
}
/**
* @brief Checks if the contents of the two delegates are different.
*
* Two delegates are identical if they contain the same listener.
*
* @param other Delegate with which to compare.
* @return True if the two delegates are identical, false otherwise.
*/
bool operator==(const Delegate<Ret(Args...)> &other) const ENTT_NOEXCEPT {
return stub.first == other.stub.first && stub.second == other.stub.second;
}
private:
stub_type stub;
};
/**
* @brief Checks if the contents of the two delegates are different.
*
* Two delegates are identical if they contain the same listener.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
* @param lhs A valid delegate object.
* @param rhs A valid delegate object.
* @return True if the two delegates are different, false otherwise.
*/
template<typename Ret, typename... Args>
bool operator!=(const Delegate<Ret(Args...)> &lhs, const Delegate<Ret(Args...)> &rhs) ENTT_NOEXCEPT {
return !(lhs == rhs);
}
}
#endif // ENTT_SIGNAL_DELEGATE_HPP

View File

@@ -0,0 +1,188 @@
#ifndef ENTT_SIGNAL_DISPATCHER_HPP
#define ENTT_SIGNAL_DISPATCHER_HPP
#include <vector>
#include <memory>
#include <utility>
#include <cstdint>
#include <algorithm>
#include <type_traits>
#include "../config/config.h"
#include "../core/family.hpp"
#include "sigh.hpp"
namespace entt {
/**
* @brief Basic dispatcher implementation.
*
* A dispatcher can be used either to trigger an immediate event or to enqueue
* events to be published all together once per tick.<br/>
* Listeners are provided in the form of member functions. For each event of
* type `Event`, listeners must have the following function type:
* @code{.cpp}
* void(const Event &)
* @endcode
*
* Member functions named `receive` are automatically detected and registered or
* unregistered by the dispatcher. The type of the instances is `Class *` (a
* naked pointer). It means that users must guarantee that the lifetimes of the
* instances overcome the one of the dispatcher itself to avoid crashes.
*/
class Dispatcher final {
using event_family = Family<struct InternalDispatcherEventFamily>;
template<typename Class, typename Event>
using instance_type = typename SigH<void(const Event &)>::template instance_type<Class>;
struct BaseSignalWrapper {
virtual ~BaseSignalWrapper() = default;
virtual void publish() = 0;
};
template<typename Event>
struct SignalWrapper final: BaseSignalWrapper {
using sink_type = typename SigH<void(const Event &)>::sink_type;
void publish() override {
const auto &curr = current++;
current %= std::extent<decltype(events)>::value;
std::for_each(events[curr].cbegin(), events[curr].cend(), [this](const auto &event) { signal.publish(event); });
events[curr].clear();
}
inline sink_type sink() ENTT_NOEXCEPT {
return signal.sink();
}
template<typename... Args>
inline void trigger(Args &&... args) {
signal.publish({ std::forward<Args>(args)... });
}
template<typename... Args>
inline void enqueue(Args &&... args) {
events[current].push_back({ std::forward<Args>(args)... });
}
private:
SigH<void(const Event &)> signal{};
std::vector<Event> events[2];
int current{};
};
template<typename Event>
SignalWrapper<Event> & wrapper() {
const auto type = event_family::type<Event>();
if(!(type < wrappers.size())) {
wrappers.resize(type + 1);
}
if(!wrappers[type]) {
wrappers[type] = std::make_unique<SignalWrapper<Event>>();
}
return static_cast<SignalWrapper<Event> &>(*wrappers[type]);
}
public:
/*! @brief Type of sink for the given event. */
template<typename Event>
using sink_type = typename SignalWrapper<Event>::sink_type;
/**
* @brief Returns a sink object for the given event.
*
* A sink is an opaque object used to connect listeners to events.
*
* The function type for a listener is:
* @code{.cpp}
* void(const Event &)
* @endcode
*
* The order of invocation of the listeners isn't guaranteed.
*
* @sa SigH::Sink
*
* @tparam Event Type of event of which to get the sink.
* @return A temporary sink object.
*/
template<typename Event>
inline sink_type<Event> sink() ENTT_NOEXCEPT {
return wrapper<Event>().sink();
}
/**
* @brief Triggers an immediate event of the given type.
*
* All the listeners registered for the given type are immediately notified.
* The event is discarded after the execution.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
inline void trigger(Args &&... args) {
wrapper<Event>().trigger(std::forward<Args>(args)...);
}
/**
* @brief Enqueues an event of the given type.
*
* An event of the given type is queued. No listener is invoked. Use the
* `update` member function to notify listeners when ready.
*
* @tparam Event Type of event to trigger.
* @tparam Args Types of arguments to use to construct the event.
* @param args Arguments to use to construct the event.
*/
template<typename Event, typename... Args>
inline void enqueue(Args &&... args) {
wrapper<Event>().enqueue(std::forward<Args>(args)...);
}
/**
* @brief Delivers all the pending events of the given type.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*
* @tparam Event Type of events to send.
*/
template<typename Event>
inline void update() {
wrapper<Event>().publish();
}
/**
* @brief Delivers all the pending events.
*
* This method is blocking and it doesn't return until all the events are
* delivered to the registered listeners. It's responsibility of the users
* to reduce at a minimum the time spent in the bodies of the listeners.
*/
inline void update() const {
for(auto pos = wrappers.size(); pos; --pos) {
auto &wrapper = wrappers[pos-1];
if(wrapper) {
wrapper->publish();
}
}
}
private:
std::vector<std::unique_ptr<BaseSignalWrapper>> wrappers;
};
}
#endif // ENTT_SIGNAL_DISPATCHER_HPP

336
src/entt/signal/emitter.hpp Normal file
View File

@@ -0,0 +1,336 @@
#ifndef ENTT_SIGNAL_EMITTER_HPP
#define ENTT_SIGNAL_EMITTER_HPP
#include <type_traits>
#include <functional>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <memory>
#include <vector>
#include <list>
#include "../config/config.h"
#include "../core/family.hpp"
namespace entt {
/**
* @brief General purpose event emitter.
*
* The emitter class template follows the CRTP idiom. To create a custom emitter
* type, derived classes must inherit directly from the base class as:
*
* ```cpp
* struct MyEmitter: Emitter<MyEmitter> {
* // ...
* }
* ```
*
* Handlers for the type of events are created internally on the fly. It's not
* required to specify in advance the full list of accepted types.<br/>
* Moreover, whenever an event is published, an emitter provides the listeners
* with a reference to itself along with a const reference to the event.
* Therefore listeners have an handy way to work with it without incurring in
* the need of capturing a reference to the emitter.
*
* @tparam Derived Actual type of emitter that extends the class template.
*/
template<typename Derived>
class Emitter {
using handler_family = Family<struct InternalEmitterHandlerFamily>;
struct BaseHandler {
virtual ~BaseHandler() = default;
virtual bool empty() const ENTT_NOEXCEPT = 0;
virtual void clear() ENTT_NOEXCEPT = 0;
};
template<typename Event>
struct Handler final: BaseHandler {
using listener_type = std::function<void(const Event &, Derived &)>;
using element_type = std::pair<bool, listener_type>;
using container_type = std::list<element_type>;
using connection_type = typename container_type::iterator;
bool empty() const ENTT_NOEXCEPT override {
auto pred = [](auto &&element) { return element.first; };
return std::all_of(onceL.cbegin(), onceL.cend(), pred) &&
std::all_of(onL.cbegin(), onL.cend(), pred);
}
void clear() ENTT_NOEXCEPT override {
if(publishing) {
auto func = [](auto &&element) { element.first = true; };
std::for_each(onceL.begin(), onceL.end(), func);
std::for_each(onL.begin(), onL.end(), func);
} else {
onceL.clear();
onL.clear();
}
}
inline connection_type once(listener_type listener) {
return onceL.emplace(onceL.cend(), false, std::move(listener));
}
inline connection_type on(listener_type listener) {
return onL.emplace(onL.cend(), false, std::move(listener));
}
void erase(connection_type conn) ENTT_NOEXCEPT {
conn->first = true;
if(!publishing) {
auto pred = [](auto &&element) { return element.first; };
onceL.remove_if(pred);
onL.remove_if(pred);
}
}
void publish(const Event &event, Derived &ref) {
container_type currentL;
onceL.swap(currentL);
auto func = [&event, &ref](auto &&element) {
return element.first ? void() : element.second(event, ref);
};
publishing = true;
std::for_each(onL.rbegin(), onL.rend(), func);
std::for_each(currentL.rbegin(), currentL.rend(), func);
publishing = false;
onL.remove_if([](auto &&element) { return element.first; });
}
private:
bool publishing{false};
container_type onceL{};
container_type onL{};
};
template<typename Event>
Handler<Event> & handler() ENTT_NOEXCEPT {
const std::size_t family = handler_family::type<Event>();
if(!(family < handlers.size())) {
handlers.resize(family+1);
}
if(!handlers[family]) {
handlers[family] = std::make_unique<Handler<Event>>();
}
return static_cast<Handler<Event> &>(*handlers[family]);
}
public:
/** @brief Type of listeners accepted for the given event. */
template<typename Event>
using Listener = typename Handler<Event>::listener_type;
/**
* @brief Generic connection type for events.
*
* Type of the connection object returned by the event emitter whenever a
* listener for the given type is registered.<br/>
* It can be used to break connections still in use.
*
* @tparam Event Type of event for which the connection is created.
*/
template<typename Event>
struct Connection final: private Handler<Event>::connection_type {
/** @brief Event emitters are friend classes of connections. */
friend class Emitter;
/*! @brief Default constructor. */
Connection() ENTT_NOEXCEPT = default;
/**
* @brief Creates a connection that wraps its underlying instance.
* @param conn A connection object to wrap.
*/
Connection(typename Handler<Event>::connection_type conn)
: Handler<Event>::connection_type{std::move(conn)}
{}
/*! @brief Default copy constructor. */
Connection(const Connection &) = default;
/*! @brief Default move constructor. */
Connection(Connection &&) = default;
/**
* @brief Default copy assignment operator.
* @return This connection.
*/
Connection & operator=(const Connection &) = default;
/**
* @brief Default move assignment operator.
* @return This connection.
*/
Connection & operator=(Connection &&) = default;
};
/*! @brief Default constructor. */
Emitter() ENTT_NOEXCEPT = default;
/*! @brief Default destructor. */
virtual ~Emitter() ENTT_NOEXCEPT {
static_assert(std::is_base_of<Emitter<Derived>, Derived>::value, "!");
}
/*! @brief Copying an emitter isn't allowed. */
Emitter(const Emitter &) = delete;
/*! @brief Default move constructor. */
Emitter(Emitter &&) = default;
/*! @brief Copying an emitter isn't allowed. @return This emitter. */
Emitter & operator=(const Emitter &) = delete;
/*! @brief Default move assignment operator. @return This emitter. */
Emitter & operator=(Emitter &&) = default;
/**
* @brief Emits the given event.
*
* All the listeners registered for the specific event type are invoked with
* the given event. The event type must either have a proper constructor for
* the arguments provided or be an aggregate type.
*
* @tparam Event Type of event to publish.
* @tparam Args Types of arguments to use to construct the event.
* @param args Parameters to use to initialize the event.
*/
template<typename Event, typename... Args>
void publish(Args &&... args) {
handler<Event>().publish({ std::forward<Args>(args)... }, *static_cast<Derived *>(this));
}
/**
* @brief Registers a long-lived listener with the event emitter.
*
* This method can be used to register a listener designed to be invoked
* more than once for the given event type.<br/>
* The connection returned by the method can be freely discarded. It's meant
* to be used later to disconnect the listener if required.
*
* The listener is as a callable object that can be moved and the type of
* which is `void(const Event &, Derived &)`.
*
* @note
* Whenever an event is emitted, the emitter provides the listener with a
* reference to the derived class. Listeners don't have to capture those
* instances for later uses.
*
* @tparam Event Type of event to which to connect the listener.
* @param listener The listener to register.
* @return Connection object that can be used to disconnect the listener.
*/
template<typename Event>
Connection<Event> on(Listener<Event> listener) {
return handler<Event>().on(std::move(listener));
}
/**
* @brief Registers a short-lived listener with the event emitter.
*
* This method can be used to register a listener designed to be invoked
* only once for the given event type.<br/>
* The connection returned by the method can be freely discarded. It's meant
* to be used later to disconnect the listener if required.
*
* The listener is as a callable object that can be moved and the type of
* which is `void(const Event &, Derived &)`.
*
* @note
* Whenever an event is emitted, the emitter provides the listener with a
* reference to the derived class. Listeners don't have to capture those
* instances for later uses.
*
* @tparam Event Type of event to which to connect the listener.
* @param listener The listener to register.
* @return Connection object that can be used to disconnect the listener.
*/
template<typename Event>
Connection<Event> once(Listener<Event> listener) {
return handler<Event>().once(std::move(listener));
}
/**
* @brief Disconnects a listener from the event emitter.
*
* Do not use twice the same connection to disconnect a listener, it results
* in undefined behavior. Once used, discard the connection object.
*
* @tparam Event Type of event of the connection.
* @param conn A valid connection.
*/
template<typename Event>
void erase(Connection<Event> conn) ENTT_NOEXCEPT {
handler<Event>().erase(std::move(conn));
}
/**
* @brief Disconnects all the listeners for the given event type.
*
* All the connections previously returned for the given event are
* invalidated. Using them results in undefined behavior.
*
* @tparam Event Type of event to reset.
*/
template<typename Event>
void clear() ENTT_NOEXCEPT {
handler<Event>().clear();
}
/**
* @brief Disconnects all the listeners.
*
* All the connections previously returned are invalidated. Using them
* results in undefined behavior.
*/
void clear() ENTT_NOEXCEPT {
std::for_each(handlers.begin(), handlers.end(), [](auto &&handler) {
return handler ? handler->clear() : void();
});
}
/**
* @brief Checks if there are listeners registered for the specific event.
* @tparam Event Type of event to test.
* @return True if there are no listeners registered, false otherwise.
*/
template<typename Event>
bool empty() const ENTT_NOEXCEPT {
const std::size_t family = handler_family::type<Event>();
return (!(family < handlers.size()) ||
!handlers[family] ||
static_cast<Handler<Event> &>(*handlers[family]).empty());
}
/**
* @brief Checks if there are listeners registered with the event emitter.
* @return True if there are no listeners registered, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return std::all_of(handlers.cbegin(), handlers.cend(), [](auto &&handler) {
return !handler || handler->empty();
});
}
private:
std::vector<std::unique_ptr<BaseHandler>> handlers{};
};
}
#endif // ENTT_SIGNAL_EMITTER_HPP

382
src/entt/signal/sigh.hpp Normal file
View File

@@ -0,0 +1,382 @@
#ifndef ENTT_SIGNAL_SIGH_HPP
#define ENTT_SIGNAL_SIGH_HPP
#include <algorithm>
#include <utility>
#include <vector>
#include "../config/config.h"
namespace entt {
namespace internal {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
template<typename, typename>
struct Invoker;
template<typename Ret, typename... Args, typename Collector>
struct Invoker<Ret(Args...), Collector> {
using proto_fn_type = Ret(void *, Args...);
using call_type = std::pair<void *, proto_fn_type *>;
virtual ~Invoker() = default;
bool invoke(Collector &collector, proto_fn_type *proto, void *instance, Args... args) const {
return collector(proto(instance, args...));
}
};
template<typename... Args, typename Collector>
struct Invoker<void(Args...), Collector> {
using proto_fn_type = void(void *, Args...);
using call_type = std::pair<void *, proto_fn_type *>;
virtual ~Invoker() = default;
bool invoke(Collector &, proto_fn_type *proto, void *instance, Args... args) const {
return (proto(instance, args...), true);
}
};
template<typename Ret>
struct NullCollector final {
using result_type = Ret;
bool operator()(result_type) const ENTT_NOEXCEPT { return true; }
};
template<>
struct NullCollector<void> final {
using result_type = void;
bool operator()() const ENTT_NOEXCEPT { return true; }
};
template<typename>
struct DefaultCollector;
template<typename Ret, typename... Args>
struct DefaultCollector<Ret(Args...)> final {
using collector_type = NullCollector<Ret>;
};
template<typename Function>
using DefaultCollectorType = typename DefaultCollector<Function>::collector_type;
/**
* Internal details not to be documented.
* @endcond TURN_OFF_DOXYGEN
*/
}
/**
* @brief Sink implementation.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
*/
template<typename Function>
class Sink;
/**
* @brief Unmanaged signal handler declaration.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
* @tparam Collector Type of collector to use, if any.
*/
template<typename Function, typename Collector = internal::DefaultCollectorType<Function>>
class SigH;
/**
* @brief Sink implementation.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs.
*
* The clear separation between a signal and a sink permits to store the
* former as private data member without exposing the publish functionality
* to the users of a class.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
class Sink<Ret(Args...)> final {
/*! @brief A signal is allowed to create sinks. */
template<typename, typename>
friend class SigH;
using proto_fn_type = Ret(void *, Args...);
using call_type = std::pair<void *, proto_fn_type *>;
template<Ret(*Function)(Args...)>
static Ret proto(void *, Args... args) {
return (Function)(args...);
}
template<typename Class, Ret(Class:: *Member)(Args... args)>
static Ret proto(void *instance, Args... args) {
return (static_cast<Class *>(instance)->*Member)(args...);
}
Sink(std::vector<call_type> &calls) ENTT_NOEXCEPT
: calls{calls}
{}
public:
/**
* @brief Connects a free function to a signal.
*
* The signal handler performs checks to avoid multiple connections for
* free functions.
*
* @tparam Function A valid free function pointer.
*/
template<Ret(*Function)(Args...)>
void connect() {
disconnect<Function>();
calls.emplace_back(nullptr, &proto<Function>);
}
/**
* @brief Connects a member function for a given instance to a signal.
*
* The signal isn't responsible for the connected object. Users must
* guarantee that the lifetime of the instance overcomes the one of the
* signal. On the other side, the signal handler performs checks to
* avoid multiple connections for the same member function of a given
* instance.
*
* @tparam Class Type of class to which the member function belongs.
* @tparam Member Member function to connect to the signal.
* @param instance A valid instance of type pointer to `Class`.
*/
template <typename Class, Ret(Class:: *Member)(Args...) = &Class::receive>
void connect(Class *instance) {
disconnect<Class, Member>(instance);
calls.emplace_back(instance, &proto<Class, Member>);
}
/**
* @brief Disconnects a free function from a signal.
* @tparam Function A valid free function pointer.
*/
template<Ret(*Function)(Args...)>
void disconnect() {
call_type target{nullptr, &proto<Function>};
calls.erase(std::remove(calls.begin(), calls.end(), std::move(target)), calls.end());
}
/**
* @brief Disconnects the given member function from a signal.
* @tparam Class Type of class to which the member function belongs.
* @tparam Member Member function to connect to the signal.
* @param instance A valid instance of type pointer to `Class`.
*/
template<typename Class, Ret(Class:: *Member)(Args...)>
void disconnect(Class *instance) {
call_type target{instance, &proto<Class, Member>};
calls.erase(std::remove(calls.begin(), calls.end(), std::move(target)), calls.end());
}
/**
* @brief Removes all existing connections for the given instance.
* @tparam Class Type of class to which the member function belongs.
* @param instance A valid instance of type pointer to `Class`.
*/
template<typename Class>
void disconnect(Class *instance) {
auto func = [instance](const call_type &call) { return call.first == instance; };
calls.erase(std::remove_if(calls.begin(), calls.end(), std::move(func)), calls.end());
}
/**
* @brief Disconnects all the listeners from a signal.
*/
void disconnect() {
calls.clear();
}
private:
std::vector<call_type> &calls;
};
/**
* @brief Unmanaged signal handler definition.
*
* Unmanaged signal handler. It works directly with naked pointers to classes
* and pointers to member functions as well as pointers to free functions. Users
* of this class are in charge of disconnecting instances before deleting them.
*
* This class serves mainly two purposes:
*
* * Creating signals used later to notify a bunch of listeners.
* * Collecting results from a set of functions like in a voting system.
*
* The default collector does nothing. To properly collect data, define and use
* a class that has a call operator the signature of which is `bool(Param)` and:
*
* * `Param` is a type to which `Ret` can be converted.
* * The return type is true if the handler must stop collecting data, false
* otherwise.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
* @tparam Collector Type of collector to use, if any.
*/
template<typename Ret, typename... Args, typename Collector>
class SigH<Ret(Args...), Collector> final: private internal::Invoker<Ret(Args...), Collector> {
using call_type = typename internal::Invoker<Ret(Args...), Collector>::call_type;
public:
/*! @brief Unsigned integer type. */
using size_type = typename std::vector<call_type>::size_type;
/*! @brief Collector type. */
using collector_type = Collector;
/*! @brief Sink type. */
using sink_type = Sink<Ret(Args...)>;
/**
* @brief Instance type when it comes to connecting member functions.
* @tparam Class Type of class to which the member function belongs.
*/
template<typename Class>
using instance_type = Class *;
/**
* @brief Number of listeners connected to the signal.
* @return Number of listeners currently connected.
*/
size_type size() const ENTT_NOEXCEPT {
return calls.size();
}
/**
* @brief Returns false if at least a listener is connected to the signal.
* @return True if the signal has no listeners connected, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return calls.empty();
}
/**
* @brief Returns a sink object for the given signal.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs. The order of invocation of the listeners isn't guaranteed.
*
* @return A temporary sink object.
*/
sink_type sink() ENTT_NOEXCEPT {
return { calls };
}
/**
* @brief Triggers a signal.
*
* All the listeners are notified. Order isn't guaranteed.
*
* @param args Arguments to use to invoke listeners.
*/
void publish(Args... args) const {
for(auto pos = calls.size(); pos; --pos) {
auto &call = calls[pos-1];
call.second(call.first, args...);
}
}
/**
* @brief Collects return values from the listeners.
* @param args Arguments to use to invoke listeners.
* @return An instance of the collector filled with collected data.
*/
collector_type collect(Args... args) const {
collector_type collector;
for(auto &&call: calls) {
if(!this->invoke(collector, call.second, call.first, args...)) {
break;
}
}
return collector;
}
/**
* @brief Swaps listeners between the two signals.
* @param lhs A valid signal object.
* @param rhs A valid signal object.
*/
friend void swap(SigH &lhs, SigH &rhs) {
using std::swap;
swap(lhs.calls, rhs.calls);
}
/**
* @brief Checks if the contents of the two signals are identical.
*
* Two signals are identical if they have the same size and the same
* listeners registered exactly in the same order.
*
* @param other Signal with which to compare.
* @return True if the two signals are identical, false otherwise.
*/
bool operator==(const SigH &other) const ENTT_NOEXCEPT {
return std::equal(calls.cbegin(), calls.cend(), other.calls.cbegin(), other.calls.cend());
}
private:
std::vector<call_type> calls;
};
/**
* @brief Checks if the contents of the two signals are different.
*
* Two signals are identical if they have the same size and the same
* listeners registered exactly in the same order.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
* @param lhs A valid signal object.
* @param rhs A valid signal object.
* @return True if the two signals are different, false otherwise.
*/
template<typename Ret, typename... Args>
bool operator!=(const SigH<Ret(Args...)> &lhs, const SigH<Ret(Args...)> &rhs) ENTT_NOEXCEPT {
return !(lhs == rhs);
}
}
#endif // ENTT_SIGNAL_SIGH_HPP

View File

@@ -1,43 +0,0 @@
#ifndef ENTT_IDENT_HPP
#define ENTT_IDENT_HPP
#include<type_traits>
#include<cstddef>
#include<utility>
namespace entt {
namespace details {
template<typename Type>
struct Wrapper {
using type = Type;
constexpr Wrapper(std::size_t index): index{index} {}
const std::size_t index;
};
template<typename... Types>
struct Identifier final: Wrapper<Types>... {
template<std::size_t... Indexes>
constexpr Identifier(std::index_sequence<Indexes...>): Wrapper<Types>{Indexes}... {}
template<typename Type>
constexpr std::size_t get() const { return Wrapper<std::decay_t<Type>>::index; }
};
}
template<typename... Types>
constexpr auto ident = details::Identifier<std::decay_t<Types>...>{std::make_index_sequence<sizeof...(Types)>{}};
}
#endif // ENTT_IDENT_HPP

View File

@@ -1,414 +0,0 @@
#ifndef ENTT_REGISTRY_HPP
#define ENTT_REGISTRY_HPP
#include <vector>
#include <bitset>
#include <utility>
#include <cstddef>
#include <iterator>
#include <cassert>
#include <type_traits>
#include "component_pool.hpp"
#include "ident.hpp"
namespace entt {
template<typename...>
class View;
template<template<typename...> class Pool, typename Entity, typename... Components, typename Type, typename... Types>
class View<Pool<Entity, Components...>, Type, Types...> final {
using pool_type = Pool<Entity, Components...>;
using entity_type = typename pool_type::entity_type;
using mask_type = std::bitset<sizeof...(Components)+1>;
using underlying_iterator_type = typename pool_type::const_iterator_type;
class ViewIterator;
public:
using iterator_type = ViewIterator;
using const_iterator_type = iterator_type;
using size_type = typename pool_type::size_type;
private:
class ViewIterator {
inline bool valid() const noexcept {
return ((mask[*begin] & bitmask) == bitmask);
}
public:
using value_type = entity_type;
using difference_type = std::ptrdiff_t;
using reference = entity_type &;
using pointer = entity_type *;
using iterator_category = std::input_iterator_tag;
ViewIterator(underlying_iterator_type begin, underlying_iterator_type end, const mask_type &bitmask, const mask_type *mask) noexcept
: begin{begin}, end{end}, bitmask{bitmask}, mask{mask}
{
if(begin != end && !valid()) {
++(*this);
}
}
ViewIterator & operator++() noexcept {
++begin;
while(begin != end && !valid()) { ++begin; }
return *this;
}
ViewIterator operator++(int) noexcept {
ViewIterator orig = *this;
return ++(*this), orig;
}
bool operator==(const ViewIterator &other) const noexcept {
return other.begin == begin;
}
bool operator!=(const ViewIterator &other) const noexcept {
return !(*this == other);
}
value_type operator*() const noexcept {
return *begin;
}
private:
underlying_iterator_type begin;
underlying_iterator_type end;
const mask_type bitmask;
const mask_type *mask;
};
template<typename Comp>
void prefer(size_type &size) noexcept {
auto sz = pool.template size<Comp>();
if(sz < size) {
from = pool.template begin<Type>();
to = pool.template end<Type>();
size = sz;
}
}
public:
explicit View(pool_type &pool, const mask_type *mask) noexcept
: from{pool.template begin<Type>()},
to{pool.template end<Type>()},
pool{pool},
mask{mask}
{
using accumulator_type = int[];
size_type size = pool.template size<Type>();
bitmask.set(ident<Components...>.template get<Type>());
accumulator_type types = { 0, (bitmask.set(ident<Components...>.template get<Types>()), 0)... };
accumulator_type pref = { 0, (prefer<Types>(size), 0)... };
(void)types, (void)pref;
}
const_iterator_type begin() const noexcept {
return ViewIterator{from, to, bitmask, mask};
}
iterator_type begin() noexcept {
return const_cast<const View *>(this)->begin();
}
const_iterator_type end() const noexcept {
return ViewIterator{to, to, bitmask, mask};
}
iterator_type end() noexcept {
return const_cast<const View *>(this)->end();
}
void reset() noexcept {
using accumulator_type = int[];
from = pool.template begin<Type>();
to = pool.template end<Type>();
size_type size = pool.template size<Type>();
accumulator_type accumulator = { 0, (prefer<Types>(size), 0)... };
(void)accumulator;
}
private:
underlying_iterator_type from;
underlying_iterator_type to;
pool_type &pool;
const mask_type *mask;
mask_type bitmask;
};
template<template<typename...> class Pool, typename Entity, typename... Components, typename Type>
class View<Pool<Entity, Components...>, Type> final {
using pool_type = Pool<Entity, Components...>;
public:
using size_type = typename pool_type::size_type;
using iterator_type = typename pool_type::const_iterator_type;
using const_iterator_type = iterator_type;
explicit View(pool_type &pool) noexcept
: pool{pool}
{}
const_iterator_type cbegin() const noexcept {
return pool.template cbegin<Type>();
}
iterator_type begin() noexcept {
return pool.template begin<Type>();
}
const_iterator_type cend() const noexcept {
return pool.template cend<Type>();
}
iterator_type end() noexcept {
return pool.template end<Type>();
}
size_type size() const noexcept {
return pool.template size<Type>();
}
private:
pool_type &pool;
};
template<typename>
class Registry;
template<template<typename...> class Pool, typename Entity, typename... Components>
class Registry<Pool<Entity, Components...>> {
static_assert(sizeof...(Components) > 1, "!");
using pool_type = Pool<Entity, Components...>;
using mask_type = std::bitset<sizeof...(Components)+1>;
static constexpr auto validity_bit = sizeof...(Components);
public:
using entity_type = typename pool_type::entity_type;
using size_type = typename std::vector<mask_type>::size_type;
private:
template<typename Comp>
void clone(entity_type to, entity_type from) {
if(entities[from].test(ident<Components...>.template get<Comp>())) {
assign<Comp>(to, pool.template get<Comp>(from));
}
}
template<typename Comp>
void sync(entity_type to, entity_type from) {
bool src = entities[from].test(ident<Components...>.template get<Comp>());
bool dst = entities[to].test(ident<Components...>.template get<Comp>());
if(src && dst) {
copy<Comp>(to, from);
} else if(src) {
clone<Comp>(to, from);
} else if(dst) {
remove<Comp>(to);
}
}
public:
template<typename... Comp>
using view_type = View<pool_type, Comp...>;
template<typename... Args>
Registry(Args&&... args)
: pool{std::forward<Args>(args)...}
{}
Registry(const Registry &) = delete;
Registry(Registry &&) = delete;
Registry & operator=(const Registry &) = delete;
Registry & operator=(Registry &&) = delete;
size_type size() const noexcept {
return entities.size() - available.size();
}
size_type capacity() const noexcept {
return entities.size();
}
template<typename Comp>
bool empty() const noexcept {
return pool.template empty<Comp>();
}
bool empty() const noexcept {
return entities.empty();
}
bool valid(entity_type entity) const noexcept {
return (entity < entities.size() && entities[entity].test(validity_bit));
}
template<typename... Comp>
entity_type create() noexcept {
using accumulator_type = int[];
auto entity = create();
accumulator_type accumulator = { 0, (assign<Comp>(entity), 0)... };
(void)accumulator;
return entity;
}
entity_type create() noexcept {
entity_type entity;
if(available.empty()) {
entity = entity_type(entities.size());
entities.emplace_back();
} else {
entity = available.back();
available.pop_back();
}
entities[entity].set(validity_bit);
return entity;
}
void destroy(entity_type entity) {
assert(valid(entity));
using accumulator_type = int[];
accumulator_type accumulator = { 0, (reset<Components>(entity), 0)... };
available.push_back(entity);
entities[entity].reset();
(void)accumulator;
}
template<typename Comp, typename... Args>
Comp & assign(entity_type entity, Args... args) {
assert(valid(entity));
entities[entity].set(ident<Components...>.template get<Comp>());
return pool.template construct<Comp>(entity, args...);
}
template<typename Comp>
void remove(entity_type entity) {
assert(valid(entity));
entities[entity].reset(ident<Components...>.template get<Comp>());
pool.template destroy<Comp>(entity);
}
template<typename... Comp>
bool has(entity_type entity) const noexcept {
assert(valid(entity));
using accumulator_type = bool[];
bool all = true;
auto &mask = entities[entity];
accumulator_type accumulator = { true, (all = all && mask.test(ident<Components...>.template get<Comp>()))... };
(void)accumulator;
return all;
}
template<typename Comp>
const Comp & get(entity_type entity) const noexcept {
return pool.template get<Comp>(entity);
}
template<typename Comp>
Comp & get(entity_type entity) noexcept {
return pool.template get<Comp>(entity);
}
template<typename Comp, typename... Args>
Comp & replace(entity_type entity, Args... args) {
return (pool.template get<Comp>(entity) = Comp{args...});
}
template<typename Comp, typename... Args>
Comp & accomodate(entity_type entity, Args... args) {
assert(valid(entity));
return (entities[entity].test(ident<Components...>.template get<Comp>())
? this->template replace<Comp>(entity, std::forward<Args>(args)...)
: this->template assign<Comp>(entity, std::forward<Args>(args)...));
}
entity_type clone(entity_type from) {
assert(valid(from));
using accumulator_type = int[];
auto to = create();
accumulator_type accumulator = { 0, (clone<Components>(to, from), 0)... };
(void)accumulator;
return to;
}
template<typename Comp>
Comp & copy(entity_type to, entity_type from) {
return (pool.template get<Comp>(to) = pool.template get<Comp>(from));
}
void copy(entity_type to, entity_type from) {
using accumulator_type = int[];
accumulator_type accumulator = { 0, (sync<Components>(to, from), 0)... };
(void)accumulator;
}
template<typename Comp>
void reset(entity_type entity) {
assert(valid(entity));
if(entities[entity].test(ident<Components...>.template get<Comp>())) {
remove<Comp>(entity);
}
}
template<typename Comp>
void reset() {
for(entity_type entity = 0, last = entity_type(entities.size()); entity < last; ++entity) {
if(entities[entity].test(ident<Components...>.template get<Comp>())) {
remove<Comp>(entity);
}
}
}
void reset() {
entities.clear();
available.clear();
pool.reset();
}
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) == 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{pool}; }
template<typename... Comp>
std::enable_if_t<(sizeof...(Comp) > 1), view_type<Comp...>>
view() noexcept { return view_type<Comp...>{pool, entities.data()}; }
private:
std::vector<mask_type> entities;
std::vector<entity_type> available;
pool_type pool;
};
template<typename Entity, typename... Components>
using StandardRegistry = Registry<ComponentPool<Entity, Components...>>;
template<typename... Components>
using DefaultRegistry = Registry<ComponentPool<std::uint32_t, Components...>>;
}
#endif // ENTT_REGISTRY_HPP

View File

@@ -2,25 +2,93 @@
# Tests configuration
#
set(COMMON_LINK_LIBS gtest_main Threads::Threads)
include_directories($<TARGET_PROPERTY:EnTT,INTERFACE_INCLUDE_DIRECTORIES>)
add_compile_options($<TARGET_PROPERTY:EnTT,INTERFACE_COMPILE_OPTIONS>)
# List of available targets
add_library(odr OBJECT odr.cpp)
set_target_properties(odr PROPERTIES CXX_EXTENSIONS OFF)
target_compile_definitions(odr PRIVATE $<TARGET_PROPERTY:EnTT,INTERFACE_COMPILE_DEFINITIONS>)
target_compile_features(odr PRIVATE $<TARGET_PROPERTY:EnTT,INTERFACE_COMPILE_FEATURES>)
target_compile_options(odr PRIVATE $<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-pedantic -Wall>)
set(TARGET_ENTT entt)
set(TARGET_BENCHMARK benchmark)
macro(SETUP_AND_ADD_TEST TEST_NAME TEST_SOURCE)
add_executable(${TEST_NAME} $<TARGET_OBJECTS:odr> ${TEST_SOURCE})
set_target_properties(${TEST_NAME} PROPERTIES CXX_EXTENSIONS OFF)
target_link_libraries(${TEST_NAME} PRIVATE EnTT GTest::Main Threads::Threads)
target_compile_definitions(${TEST_NAME} PRIVATE $<TARGET_PROPERTY:EnTT,INTERFACE_COMPILE_DEFINITIONS>)
target_compile_features(${TEST_NAME} PRIVATE $<TARGET_PROPERTY:EnTT,INTERFACE_COMPILE_FEATURES>)
target_compile_options(${TEST_NAME} PRIVATE $<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-pedantic -Wall>)
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME})
endmacro()
# Test TARGET_ENTT
# Test benchmark
add_executable(${TARGET_ENTT} component_pool.cpp registry.cpp)
target_include_directories(${TARGET_ENTT} PRIVATE ${PROJECT_SRC_DIR})
target_link_libraries(${TARGET_ENTT} PRIVATE ${COMMON_LINK_LIBS})
add_test(NAME ${TARGET_ENTT} COMMAND ${TARGET_ENTT})
if(BUILD_BENCHMARK)
SETUP_AND_ADD_TEST(benchmark benchmark/benchmark.cpp)
endif()
# Test TARGET_BENCHMARK
# Test mod
IF(CMAKE_BUILD_TYPE MATCHES Release)
add_executable(${TARGET_BENCHMARK} benchmark.cpp)
target_include_directories(${TARGET_BENCHMARK} PRIVATE ${PROJECT_SRC_DIR})
target_link_libraries(${TARGET_BENCHMARK} PRIVATE ${COMMON_LINK_LIBS})
add_test(NAME ${TARGET_BENCHMARK} COMMAND ${TARGET_BENCHMARK})
ENDIF()
if(BUILD_MOD)
set(DUKTAPE_DEPS_DIR ${EnTT_SOURCE_DIR}/deps/duktape)
configure_file(${EnTT_SOURCE_DIR}/cmake/in/duktape.in ${DUKTAPE_DEPS_DIR}/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . WORKING_DIRECTORY ${DUKTAPE_DEPS_DIR})
execute_process(COMMAND ${CMAKE_COMMAND} --build . WORKING_DIRECTORY ${DUKTAPE_DEPS_DIR})
set(DUKTAPE_SRC_DIR ${DUKTAPE_DEPS_DIR}/src/src)
set(MOD_TEST_SOURCE ${DUKTAPE_SRC_DIR}/duktape.c mod/mod.cpp)
SETUP_AND_ADD_TEST(mod "${MOD_TEST_SOURCE}")
target_include_directories(mod PRIVATE ${DUKTAPE_SRC_DIR})
endif()
# Test snapshot
if(BUILD_SNAPSHOT)
set(CEREAL_DEPS_DIR ${EnTT_SOURCE_DIR}/deps/cereal)
configure_file(${EnTT_SOURCE_DIR}/cmake/in/cereal.in ${CEREAL_DEPS_DIR}/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . WORKING_DIRECTORY ${CEREAL_DEPS_DIR})
execute_process(COMMAND ${CMAKE_COMMAND} --build . WORKING_DIRECTORY ${CEREAL_DEPS_DIR})
set(CEREAL_SRC_DIR ${CEREAL_DEPS_DIR}/src/include)
SETUP_AND_ADD_TEST(cereal snapshot/snapshot.cpp)
target_include_directories(cereal PRIVATE ${CEREAL_SRC_DIR})
endif()
# Test core
SETUP_AND_ADD_TEST(algorithm entt/core/algorithm.cpp)
SETUP_AND_ADD_TEST(family entt/core/family.cpp)
SETUP_AND_ADD_TEST(hashed_string entt/core/hashed_string.cpp)
SETUP_AND_ADD_TEST(ident entt/core/ident.cpp)
SETUP_AND_ADD_TEST(monostate entt/core/monostate.cpp)
# Test entity
SETUP_AND_ADD_TEST(actor entt/entity/actor.cpp)
SETUP_AND_ADD_TEST(entity entt/entity/entity.cpp)
SETUP_AND_ADD_TEST(helper entt/entity/helper.cpp)
SETUP_AND_ADD_TEST(prototype entt/entity/prototype.cpp)
SETUP_AND_ADD_TEST(registry entt/entity/registry.cpp)
SETUP_AND_ADD_TEST(snapshot entt/entity/snapshot.cpp)
SETUP_AND_ADD_TEST(sparse_set entt/entity/sparse_set.cpp)
SETUP_AND_ADD_TEST(view entt/entity/view.cpp)
# Test locator
SETUP_AND_ADD_TEST(locator entt/locator/locator.cpp)
# Test process
SETUP_AND_ADD_TEST(process entt/process/process.cpp)
SETUP_AND_ADD_TEST(scheduler entt/process/scheduler.cpp)
# Test resource
SETUP_AND_ADD_TEST(resource entt/resource/resource.cpp)
# Test signal
SETUP_AND_ADD_TEST(delegate entt/signal/delegate.cpp)
SETUP_AND_ADD_TEST(dispatcher entt/signal/dispatcher.cpp)
SETUP_AND_ADD_TEST(emitter entt/signal/emitter.cpp)
SETUP_AND_ADD_TEST(sigh entt/signal/sigh.cpp)

View File

@@ -1,409 +0,0 @@
#include <gtest/gtest.h>
#include <registry.hpp>
#include <iostream>
#include <cstddef>
#include <chrono>
#include <vector>
struct Position {
uint64_t x;
uint64_t y;
};
struct Velocity {
uint64_t x;
uint64_t y;
};
template<std::size_t>
struct Comp {};
struct Timer final {
Timer(): start{std::chrono::system_clock::now()} {}
void elapsed() {
auto now = std::chrono::system_clock::now();
std::cout << std::chrono::duration<double>(now - start).count() << " seconds" << std::endl;
}
private:
std::chrono::time_point<std::chrono::system_clock> start;
};
TEST(DefaultRegistry, Construct) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Constructing 10000000 entities" << std::endl;
Timer timer;
for (uint64_t i = 0; i < 10000000L; i++) {
registry.create();
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, Destroy) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::vector<registry_type::entity_type> entities{};
std::cout << "Destroying 10000000 entities" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
entities.push_back(registry.create());
}
Timer timer;
for (auto entity: entities) {
registry.destroy(entity);
}
timer.elapsed();
}
TEST(DefaultRegistry, IterateCreateDeleteSingleComponent) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Looping 10000 times creating and deleting a random number of entities" << std::endl;
Timer timer;
for(int i = 0; i < 10000; i++) {
for(int j = 0; j < 10000; j++) {
registry.create<Position>();
}
auto view = registry.view<Position>();
for(auto entity: view) {
if(rand() % 2 == 0) {
registry.destroy(entity);
}
}
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateSingleComponent10M) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, one component" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
registry.create<Position>();
}
Timer timer;
auto view = registry.view<Position>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
(void)position;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTwoComponents10M) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, two components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
registry.create<Position, Velocity>();
}
Timer timer;
auto view = registry.view<Position, Velocity>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
(void)position;
(void)velocity;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTwoComponents10MHalf) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, two components, half of the entities have all the components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
auto entity = registry.create<Velocity>();
if(i % 2) { registry.assign<Position>(entity); }
}
Timer timer;
auto view = registry.view<Position, Velocity>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
(void)position;
(void)velocity;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTwoComponents10MOne) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, two components, only one entity has all the components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
auto entity = registry.create<Velocity>();
if(i == 5000000L) { registry.assign<Position>(entity); }
}
Timer timer;
auto view = registry.view<Position, Velocity>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
(void)position;
(void)velocity;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateSingleComponent50M) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 50000000 entities, one component" << std::endl;
for (uint64_t i = 0; i < 50000000L; i++) {
registry.create<Position>();
}
Timer timer;
auto view = registry.view<Position>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
(void)position;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTwoComponents50M) {
using registry_type = entt::DefaultRegistry<Position, Velocity>;
registry_type registry;
std::cout << "Iterating over 50000000 entities, two components" << std::endl;
for (uint64_t i = 0; i < 50000000L; i++) {
registry.create<Position, Velocity>();
}
Timer timer;
auto view = registry.view<Position, Velocity>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
(void)position;
(void)velocity;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateFiveComponents10M) {
using registry_type = entt::DefaultRegistry<Position, Velocity, Comp<1>, Comp<2>, Comp<3>>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, five components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
registry.create<Position, Velocity, Comp<1>, Comp<2>, Comp<3>>();
}
Timer timer;
auto view = registry.view<Position, Velocity, Comp<1>, Comp<2>, Comp<3>>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
auto &comp1 = registry.get<Comp<1>>(entity);
auto &comp2 = registry.get<Comp<2>>(entity);
auto &comp3 = registry.get<Comp<3>>(entity);
(void)position;
(void)velocity;
(void)comp1;
(void)comp2;
(void)comp3;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTenComponents10M) {
using registry_type = entt::DefaultRegistry<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, ten components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
registry.create<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
}
Timer timer;
auto view = registry.view<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
auto &comp1 = registry.get<Comp<1>>(entity);
auto &comp2 = registry.get<Comp<2>>(entity);
auto &comp3 = registry.get<Comp<3>>(entity);
auto &comp4 = registry.get<Comp<4>>(entity);
auto &comp5 = registry.get<Comp<5>>(entity);
auto &comp6 = registry.get<Comp<6>>(entity);
auto &comp7 = registry.get<Comp<7>>(entity);
auto &comp8 = registry.get<Comp<8>>(entity);
(void)position;
(void)velocity;
(void)comp1;
(void)comp2;
(void)comp3;
(void)comp4;
(void)comp5;
(void)comp6;
(void)comp7;
(void)comp8;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTenComponents10MHalf) {
using registry_type = entt::DefaultRegistry<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, ten components, half of the entities have all the components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
auto entity = registry.create<Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
if(i % 2) { registry.assign<Position>(entity); }
}
Timer timer;
auto view = registry.view<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
auto &comp1 = registry.get<Comp<1>>(entity);
auto &comp2 = registry.get<Comp<2>>(entity);
auto &comp3 = registry.get<Comp<3>>(entity);
auto &comp4 = registry.get<Comp<4>>(entity);
auto &comp5 = registry.get<Comp<5>>(entity);
auto &comp6 = registry.get<Comp<6>>(entity);
auto &comp7 = registry.get<Comp<7>>(entity);
auto &comp8 = registry.get<Comp<8>>(entity);
(void)position;
(void)velocity;
(void)comp1;
(void)comp2;
(void)comp3;
(void)comp4;
(void)comp5;
(void)comp6;
(void)comp7;
(void)comp8;
}
timer.elapsed();
registry.reset();
}
TEST(DefaultRegistry, IterateTenComponents10MOne) {
using registry_type = entt::DefaultRegistry<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>;
registry_type registry;
std::cout << "Iterating over 10000000 entities, ten components, only one entity has all the components" << std::endl;
for (uint64_t i = 0; i < 10000000L; i++) {
auto entity = registry.create<Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
if(i == 5000000L) { registry.assign<Position>(entity); }
}
Timer timer;
auto view = registry.view<Position, Velocity, Comp<1>, Comp<2>, Comp<3>, Comp<4>, Comp<5>, Comp<6>, Comp<7>, Comp<8>>();
for(auto entity: view) {
auto &position = registry.get<Position>(entity);
auto &velocity = registry.get<Velocity>(entity);
auto &comp1 = registry.get<Comp<1>>(entity);
auto &comp2 = registry.get<Comp<2>>(entity);
auto &comp3 = registry.get<Comp<3>>(entity);
auto &comp4 = registry.get<Comp<4>>(entity);
auto &comp5 = registry.get<Comp<5>>(entity);
auto &comp6 = registry.get<Comp<6>>(entity);
auto &comp7 = registry.get<Comp<7>>(entity);
auto &comp8 = registry.get<Comp<8>>(entity);
(void)position;
(void)velocity;
(void)comp1;
(void)comp2;
(void)comp3;
(void)comp4;
(void)comp5;
(void)comp6;
(void)comp7;
(void)comp8;
}
timer.elapsed();
registry.reset();
}

1009
test/benchmark/benchmark.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,166 +0,0 @@
#include <cstddef>
#include <gtest/gtest.h>
#include <component_pool.hpp>
TEST(ComponentPool, Functionalities) {
using pool_type = entt::ComponentPool<std::uint8_t, int, double>;
pool_type pool{0};
ASSERT_TRUE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{0});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{0});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{0});
ASSERT_EQ(pool.size<double>(), pool_type::size_type{0});
ASSERT_EQ(pool.begin<int>(), pool.end<int>());
ASSERT_EQ(pool.begin<double>(), pool.end<double>());
ASSERT_FALSE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
}
TEST(ComponentPool, ConstructDestroy) {
using pool_type = entt::ComponentPool<std::uint8_t, double, int>;
pool_type pool{4};
ASSERT_EQ(pool.construct<int>(0, 42), 42);
ASSERT_FALSE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{4});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{4});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{1});
ASSERT_EQ(pool.size<double>(), pool_type::size_type{0});
ASSERT_TRUE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
ASSERT_FALSE(pool.has<int>(1));
ASSERT_FALSE(pool.has<double>(1));
ASSERT_EQ(pool.construct<int>(1), 0);
ASSERT_FALSE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{4});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{4});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{2});
ASSERT_EQ(pool.size<double>(), pool_type::size_type{0});
ASSERT_TRUE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
ASSERT_TRUE(pool.has<int>(1));
ASSERT_FALSE(pool.has<double>(1));
ASSERT_NE(pool.get<int>(0), pool.get<int>(1));
ASSERT_NE(&pool.get<int>(0), &pool.get<int>(1));
ASSERT_NO_THROW(pool.destroy<int>(0));
ASSERT_FALSE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{4});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{4});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{1});
ASSERT_EQ(pool.size<double>(), pool_type::size_type{0});
ASSERT_FALSE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
ASSERT_TRUE(pool.has<int>(1));
ASSERT_FALSE(pool.has<double>(1));
ASSERT_NO_THROW(pool.destroy<int>(1));
ASSERT_TRUE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{4});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{4});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{0});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{0});
ASSERT_FALSE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
ASSERT_FALSE(pool.has<int>(1));
ASSERT_FALSE(pool.has<double>(1));
int *comp[] = {
&pool.construct<int>(0, 0),
&pool.construct<int>(1, 1),
nullptr,
&pool.construct<int>(3, 3)
};
ASSERT_FALSE(pool.empty<int>());
ASSERT_TRUE(pool.empty<double>());
ASSERT_EQ(pool.capacity<int>(), pool_type::size_type{4});
ASSERT_EQ(pool.capacity<double>(), pool_type::size_type{4});
ASSERT_EQ(pool.size<int>(), pool_type::size_type{3});
ASSERT_EQ(pool.size<double>(), pool_type::size_type{0});
ASSERT_TRUE(pool.has<int>(0));
ASSERT_FALSE(pool.has<double>(0));
ASSERT_TRUE(pool.has<int>(1));
ASSERT_FALSE(pool.has<double>(1));
ASSERT_FALSE(pool.has<int>(2));
ASSERT_FALSE(pool.has<double>(2));
ASSERT_TRUE(pool.has<int>(3));
ASSERT_FALSE(pool.has<double>(3));
ASSERT_EQ(&pool.get<int>(0), comp[0]);
ASSERT_EQ(&pool.get<int>(1), comp[1]);
ASSERT_EQ(&pool.get<int>(3), comp[3]);
ASSERT_EQ(pool.get<int>(0), 0);
ASSERT_EQ(pool.get<int>(1), 1);
ASSERT_EQ(pool.get<int>(3), 3);
ASSERT_NO_THROW(pool.destroy<int>(0));
ASSERT_NO_THROW(pool.destroy<int>(1));
ASSERT_NO_THROW(pool.destroy<int>(3));
}
TEST(ComponentPool, HasGet) {
using pool_type = entt::ComponentPool<std::uint8_t, int, char>;
pool_type pool;
const pool_type &cpool = pool;
int &comp = pool.construct<int>(0, 42);
ASSERT_EQ(pool.get<int>(0), comp);
ASSERT_EQ(pool.get<int>(0), 42);
ASSERT_TRUE(pool.has<int>(0));
ASSERT_EQ(cpool.get<int>(0), comp);
ASSERT_EQ(cpool.get<int>(0), 42);
ASSERT_TRUE(cpool.has<int>(0));
ASSERT_NO_THROW(pool.destroy<int>(0));
}
TEST(ComponentPool, BeginEndReset) {
using pool_type = entt::ComponentPool<std::uint8_t, int, char>;
pool_type pool{2};
ASSERT_EQ(pool.construct<int>(0, 0), 0);
ASSERT_EQ(pool.construct<int>(2, 2), 2);
ASSERT_EQ(pool.construct<int>(3, 3), 3);
ASSERT_EQ(pool.construct<int>(1, 1), 1);
ASSERT_EQ(pool.size<int>(), decltype(pool.size<int>()){4});
ASSERT_EQ(*(pool.begin<int>()+0), typename pool_type::entity_type{0});
ASSERT_EQ(*(pool.begin<int>()+1), typename pool_type::entity_type{2});
ASSERT_EQ(*(pool.begin<int>()+2), typename pool_type::entity_type{3});
ASSERT_EQ(*(pool.begin<int>()+3), typename pool_type::entity_type{1});
pool.destroy<int>(2);
ASSERT_EQ(pool.size<int>(), decltype(pool.size<int>()){3});
ASSERT_EQ(*(pool.begin<int>()+0), typename pool_type::entity_type{0});
ASSERT_EQ(*(pool.begin<int>()+1), typename pool_type::entity_type{1});
ASSERT_EQ(*(pool.begin<int>()+2), typename pool_type::entity_type{3});
ASSERT_EQ(pool.construct<char>(0, 'c'), 'c');
ASSERT_FALSE(pool.empty<int>());
ASSERT_FALSE(pool.empty<char>());
ASSERT_NO_THROW(pool.reset<char>());
ASSERT_FALSE(pool.empty<int>());
ASSERT_TRUE(pool.empty<char>());
ASSERT_NO_THROW(pool.reset());
ASSERT_TRUE(pool.empty<int>());
ASSERT_TRUE(pool.empty<char>());
}

View File

@@ -0,0 +1,40 @@
#include <array>
#include <gtest/gtest.h>
#include <entt/core/algorithm.hpp>
TEST(Algorithm, StdSort) {
// well, I'm pretty sure it works, it's std::sort!!
std::array<int, 5> arr{{4, 1, 3, 2, 0}};
entt::StdSort sort;
sort(arr.begin(), arr.end());
for(typename decltype(arr)::size_type i = 0; i < (arr.size() - 1); ++i) {
ASSERT_LT(arr[i], arr[i+1]);
}
}
TEST(Algorithm, InsertionSort) {
std::array<int, 5> arr{{4, 1, 3, 2, 0}};
entt::InsertionSort sort;
sort(arr.begin(), arr.end());
for(typename decltype(arr)::size_type i = 0; i < (arr.size() - 1); ++i) {
ASSERT_LT(arr[i], arr[i+1]);
}
}
TEST(Algorithm, OneShotBubbleSort) {
std::array<int, 5> arr{{4, 1, 3, 2, 0}};
entt::OneShotBubbleSort sort;
sort(arr.begin(), arr.end());
sort(arr.begin(), arr.end());
sort(arr.begin(), arr.end());
sort(arr.begin(), arr.end());
for(typename decltype(arr)::size_type i = 0; i < (arr.size() - 1); ++i) {
ASSERT_LT(arr[i], arr[i+1]);
}
}

22
test/entt/core/family.cpp Normal file
View File

@@ -0,0 +1,22 @@
#include <gtest/gtest.h>
#include <entt/core/family.hpp>
using my_family = entt::Family<struct MyFamily>;
using your_family = entt::Family<struct YourFamily>;
TEST(Family, Functionalities) {
auto myFamilyType = my_family::type<struct MyFamilyType>();
auto mySameFamilyType = my_family::type<struct MyFamilyType>();
auto myOtherFamilyType = my_family::type<struct MyOtherFamilyType>();
auto yourFamilyType = your_family::type<struct YourFamilyType>();
ASSERT_EQ(myFamilyType, mySameFamilyType);
ASSERT_NE(myFamilyType, myOtherFamilyType);
ASSERT_EQ(myFamilyType, yourFamilyType);
}
TEST(Family, Uniqueness) {
ASSERT_EQ(my_family::type<int>(), my_family::type<int &>());
ASSERT_EQ(my_family::type<int>(), my_family::type<int &&>());
ASSERT_EQ(my_family::type<int>(), my_family::type<const int &>());
}

View File

@@ -0,0 +1,34 @@
#include <type_traits>
#include <gtest/gtest.h>
#include <entt/core/hashed_string.hpp>
TEST(HashedString, Functionalities) {
using hash_type = entt::HashedString::hash_type;
const char *bar = "bar";
auto fooHs = entt::HashedString{"foo"};
auto barHs = entt::HashedString{bar};
ASSERT_NE(static_cast<hash_type>(fooHs), static_cast<hash_type>(barHs));
ASSERT_EQ(static_cast<const char *>(fooHs), "foo");
ASSERT_EQ(static_cast<const char *>(barHs), bar);
ASSERT_EQ(fooHs, fooHs);
ASSERT_NE(fooHs, barHs);
entt::HashedString hs{"foobar"};
ASSERT_EQ(static_cast<hash_type>(hs), 0x85944171f73967e8);
ASSERT_EQ(fooHs, "foo"_hs);
ASSERT_NE(barHs, "foo"_hs);
}
TEST(HashedString, Constexprness) {
using hash_type = entt::HashedString::hash_type;
// how would you test a constexpr otherwise?
(void)std::integral_constant<hash_type, entt::HashedString{"quux"}>{};
(void)std::integral_constant<hash_type, "quux"_hs>{};
ASSERT_TRUE(true);
}

32
test/entt/core/ident.cpp Normal file
View File

@@ -0,0 +1,32 @@
#include <type_traits>
#include <gtest/gtest.h>
#include <entt/core/ident.hpp>
struct AType {};
struct AnotherType {};
TEST(Identifier, Uniqueness) {
using ID = entt::Identifier<AType, AnotherType>;
constexpr AType anInstance;
constexpr AnotherType anotherInstance;
ASSERT_NE(ID::get<AType>(), ID::get<AnotherType>());
ASSERT_EQ(ID::get<AType>(), ID::get<decltype(anInstance)>());
ASSERT_NE(ID::get<AType>(), ID::get<decltype(anotherInstance)>());
ASSERT_EQ(ID::get<AType>(), ID::get<AType>());
ASSERT_EQ(ID::get<AnotherType>(), ID::get<AnotherType>());
// test uses in constant expressions
switch(ID::get<AnotherType>()) {
case ID::get<AType>():
FAIL();
case ID::get<AnotherType>():
SUCCEED();
}
}
TEST(Identifier, SingleType) {
using ID = entt::Identifier<AType>;
std::integral_constant<ID::identifier_type, ID::get<AType>()> ic;
(void)ic;
}

View File

@@ -0,0 +1,20 @@
#include <gtest/gtest.h>
#include <entt/core/hashed_string.hpp>
#include <entt/core/monostate.hpp>
TEST(Monostate, Functionalities) {
const bool bPre = entt::Monostate<entt::HashedString{"foobar"}>{};
const int iPre = entt::Monostate<"foobar"_hs>{};
ASSERT_FALSE(bPre);
ASSERT_EQ(iPre, int{});
entt::Monostate<"foobar"_hs>{} = true;
entt::Monostate<"foobar"_hs>{} = 42;
const bool &bPost = entt::Monostate<"foobar"_hs>{};
const int &iPost = entt::Monostate<entt::HashedString{"foobar"}>{};
ASSERT_TRUE(bPost);
ASSERT_EQ(iPost, 42);
}

View File

@@ -0,0 +1,76 @@
#include <functional>
#include <gtest/gtest.h>
#include <entt/entity/actor.hpp>
#include <entt/entity/registry.hpp>
struct ActorComponent final {};
struct ActorTag final {};
TEST(Actor, Component) {
entt::DefaultRegistry registry;
entt::DefaultActor actor{registry};
const auto &cactor = actor;
ASSERT_EQ(&registry, &actor.registry());
ASSERT_EQ(&registry, &cactor.registry());
ASSERT_TRUE(registry.empty<ActorComponent>());
ASSERT_FALSE(registry.empty());
ASSERT_FALSE(actor.has<ActorComponent>());
const auto &component = actor.assign<ActorComponent>();
ASSERT_EQ(&component, &actor.get<ActorComponent>());
ASSERT_EQ(&component, &cactor.get<ActorComponent>());
ASSERT_FALSE(registry.empty<ActorComponent>());
ASSERT_FALSE(registry.empty());
ASSERT_TRUE(actor.has<ActorComponent>());
actor.remove<ActorComponent>();
ASSERT_TRUE(registry.empty<ActorComponent>());
ASSERT_FALSE(registry.empty());
ASSERT_FALSE(actor.has<ActorComponent>());
}
TEST(Actor, Tag) {
entt::DefaultRegistry registry;
entt::DefaultActor actor{registry};
const auto &cactor = actor;
ASSERT_EQ(&registry, &actor.registry());
ASSERT_EQ(&registry, &cactor.registry());
ASSERT_FALSE(registry.has<ActorTag>());
ASSERT_FALSE(actor.has<ActorTag>(entt::tag_t{}));
const auto &tag = actor.assign<ActorTag>(entt::tag_t{});
ASSERT_EQ(&tag, &actor.get<ActorTag>(entt::tag_t{}));
ASSERT_EQ(&tag, &cactor.get<ActorTag>(entt::tag_t{}));
ASSERT_TRUE(registry.has<ActorTag>());
ASSERT_FALSE(registry.empty());
ASSERT_TRUE(actor.has<ActorTag>(entt::tag_t{}));
actor.remove<ActorTag>(entt::tag_t{});
ASSERT_FALSE(registry.has<ActorTag>());
ASSERT_FALSE(registry.empty());
ASSERT_FALSE(actor.has<ActorTag>(entt::tag_t{}));
}
TEST(Actor, EntityLifetime) {
entt::DefaultRegistry registry;
auto *actor = new entt::DefaultActor{registry};
actor->assign<ActorComponent>();
ASSERT_FALSE(registry.empty<ActorComponent>());
ASSERT_FALSE(registry.empty());
registry.each([actor](const auto entity) {
ASSERT_EQ(actor->entity(), entity);
});
delete actor;
ASSERT_TRUE(registry.empty<ActorComponent>());
ASSERT_TRUE(registry.empty());
}

View File

@@ -0,0 +1,27 @@
#include <functional>
#include <gtest/gtest.h>
#include <entt/entity/entity.hpp>
#include <entt/entity/registry.hpp>
template<bool>
struct S {};
TEST(Traits, Null) {
entt::DefaultRegistry registry{};
const auto entity = registry.create();
registry.assign<int>(entity, 42);
ASSERT_TRUE(~typename entt::DefaultRegistry::entity_type{} == entt::null);
ASSERT_TRUE(entt::null == entt::null);
ASSERT_FALSE(entt::null != entt::null);
ASSERT_FALSE(entity == entt::null);
ASSERT_FALSE(entt::null == entity);
ASSERT_TRUE(entity != entt::null);
ASSERT_TRUE(entt::null != entity);
ASSERT_FALSE(registry.valid(entt::null));
}

View File

@@ -0,0 +1,75 @@
#include <gtest/gtest.h>
#include <entt/core/hashed_string.hpp>
#include <entt/entity/helper.hpp>
#include <entt/entity/registry.hpp>
TEST(Helper, Dependency) {
entt::DefaultRegistry registry;
const auto entity = registry.create();
entt::dependency<double, float>(registry.construction<int>());
ASSERT_FALSE(registry.has<double>(entity));
ASSERT_FALSE(registry.has<float>(entity));
registry.assign<char>(entity);
ASSERT_FALSE(registry.has<double>(entity));
ASSERT_FALSE(registry.has<float>(entity));
registry.assign<int>(entity);
ASSERT_TRUE(registry.has<double>(entity));
ASSERT_TRUE(registry.has<float>(entity));
ASSERT_EQ(registry.get<double>(entity), .0);
ASSERT_EQ(registry.get<float>(entity), .0f);
registry.get<double>(entity) = .3;
registry.get<float>(entity) = .1f;
registry.remove<int>(entity);
registry.assign<int>(entity);
ASSERT_EQ(registry.get<double>(entity), .3);
ASSERT_EQ(registry.get<float>(entity), .1f);
registry.remove<int>(entity);
registry.remove<float>(entity);
registry.assign<int>(entity);
ASSERT_TRUE(registry.has<float>(entity));
ASSERT_EQ(registry.get<double>(entity), .3);
ASSERT_EQ(registry.get<float>(entity), .0f);
registry.remove<int>(entity);
registry.remove<double>(entity);
registry.remove<float>(entity);
entt::dependency<double, float>(entt::break_t{}, registry.construction<int>());
registry.assign<int>(entity);
ASSERT_FALSE(registry.has<double>(entity));
ASSERT_FALSE(registry.has<float>(entity));
}
TEST(Helper, Label) {
entt::DefaultRegistry registry;
const auto entity = registry.create();
registry.assign<entt::label<"foobar"_hs>>(entity);
registry.assign<int>(entity, 42);
int counter{};
ASSERT_FALSE(registry.has<entt::label<"barfoo"_hs>>(entity));
ASSERT_TRUE(registry.has<entt::label<"foobar"_hs>>(entity));
for(auto entity: registry.view<int, entt::label<"foobar"_hs>>()) {
(void)entity;
++counter;
}
ASSERT_NE(counter, 0);
for(auto entity: registry.view<entt::label<"foobar"_hs>>()) {
(void)entity;
--counter;
}
ASSERT_EQ(counter, 0);
}

View File

@@ -0,0 +1,153 @@
#include <gtest/gtest.h>
#include <entt/entity/prototype.hpp>
#include <entt/entity/registry.hpp>
TEST(Prototype, SameRegistry) {
entt::DefaultRegistry registry;
entt::DefaultPrototype prototype{registry};
const auto &cprototype = prototype;
ASSERT_FALSE(registry.empty());
ASSERT_FALSE((prototype.has<int, char>()));
ASSERT_EQ(prototype.set<int>(2), 2);
ASSERT_EQ(prototype.set<int>(3), 3);
ASSERT_EQ(prototype.set<char>('c'), 'c');
ASSERT_EQ(prototype.get<int>(), 3);
ASSERT_EQ(cprototype.get<char>(), 'c');
ASSERT_EQ(std::get<0>(prototype.get<int, char>()), 3);
ASSERT_EQ(std::get<1>(cprototype.get<int, char>()), 'c');
const auto e0 = prototype.create();
ASSERT_TRUE((prototype.has<int, char>()));
ASSERT_FALSE(registry.orphan(e0));
const auto e1 = prototype();
prototype(e0);
ASSERT_FALSE(registry.orphan(e0));
ASSERT_FALSE(registry.orphan(e1));
ASSERT_TRUE((registry.has<int, char>(e0)));
ASSERT_TRUE((registry.has<int, char>(e1)));
registry.remove<int>(e0);
registry.remove<int>(e1);
prototype.unset<int>();
ASSERT_FALSE((prototype.has<int, char>()));
ASSERT_FALSE((prototype.has<int>()));
ASSERT_TRUE((prototype.has<char>()));
prototype(e0);
prototype(e1);
ASSERT_FALSE(registry.has<int>(e0));
ASSERT_FALSE(registry.has<int>(e1));
ASSERT_EQ(registry.get<char>(e0), 'c');
ASSERT_EQ(registry.get<char>(e1), 'c');
registry.get<char>(e0) = '*';
prototype.assign(e0);
ASSERT_EQ(registry.get<char>(e0), '*');
registry.get<char>(e1) = '*';
prototype.accommodate(e1);
ASSERT_EQ(registry.get<char>(e1), 'c');
}
TEST(Prototype, OtherRegistry) {
entt::DefaultRegistry registry;
entt::DefaultRegistry repository;
entt::DefaultPrototype prototype{repository};
const auto &cprototype = prototype;
ASSERT_TRUE(registry.empty());
ASSERT_FALSE((prototype.has<int, char>()));
ASSERT_EQ(prototype.set<int>(2), 2);
ASSERT_EQ(prototype.set<int>(3), 3);
ASSERT_EQ(prototype.set<char>('c'), 'c');
ASSERT_EQ(prototype.get<int>(), 3);
ASSERT_EQ(cprototype.get<char>(), 'c');
ASSERT_EQ(std::get<0>(prototype.get<int, char>()), 3);
ASSERT_EQ(std::get<1>(cprototype.get<int, char>()), 'c');
const auto e0 = prototype.create(registry);
ASSERT_TRUE((prototype.has<int, char>()));
ASSERT_FALSE(registry.orphan(e0));
const auto e1 = prototype(registry);
prototype(registry, e0);
ASSERT_FALSE(registry.orphan(e0));
ASSERT_FALSE(registry.orphan(e1));
ASSERT_TRUE((registry.has<int, char>(e0)));
ASSERT_TRUE((registry.has<int, char>(e1)));
registry.remove<int>(e0);
registry.remove<int>(e1);
prototype.unset<int>();
ASSERT_FALSE((prototype.has<int, char>()));
ASSERT_FALSE((prototype.has<int>()));
ASSERT_TRUE((prototype.has<char>()));
prototype(registry, e0);
prototype(registry, e1);
ASSERT_FALSE(registry.has<int>(e0));
ASSERT_FALSE(registry.has<int>(e1));
ASSERT_EQ(registry.get<char>(e0), 'c');
ASSERT_EQ(registry.get<char>(e1), 'c');
registry.get<char>(e0) = '*';
prototype.assign(registry, e0);
ASSERT_EQ(registry.get<char>(e0), '*');
registry.get<char>(e1) = '*';
prototype.accommodate(registry, e1);
ASSERT_EQ(registry.get<char>(e1), 'c');
}
TEST(Prototype, RAII) {
entt::DefaultRegistry registry;
{
entt::DefaultPrototype prototype{registry};
prototype.set<int>(0);
ASSERT_FALSE(registry.empty());
}
ASSERT_TRUE(registry.empty());
}
TEST(Prototype, MoveConstructionAssignment) {
entt::DefaultRegistry registry;
entt::DefaultPrototype prototype{registry};
prototype.set<int>(0);
auto other{std::move(prototype)};
const auto e0 = other();
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{2});
ASSERT_TRUE(registry.has<int>(e0));
prototype = std::move(other);
const auto e1 = prototype();
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{3});
ASSERT_TRUE(registry.has<int>(e1));
}

View File

@@ -0,0 +1,813 @@
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <type_traits>
#include <gtest/gtest.h>
#include <entt/entity/entt_traits.hpp>
#include <entt/entity/registry.hpp>
struct Listener {
template<typename Component>
void incrComponent(entt::DefaultRegistry &registry, entt::DefaultRegistry::entity_type entity) {
ASSERT_TRUE(registry.valid(entity));
ASSERT_TRUE(registry.has<Component>(entity));
last = entity;
++counter;
}
template<typename Tag>
void incrTag(entt::DefaultRegistry &registry, entt::DefaultRegistry::entity_type entity) {
ASSERT_TRUE(registry.valid(entity));
ASSERT_TRUE(registry.has<Tag>());
ASSERT_EQ(registry.attachee<Tag>(), entity);
last = entity;
++counter;
}
template<typename Component>
void decrComponent(entt::DefaultRegistry &registry, entt::DefaultRegistry::entity_type entity) {
ASSERT_TRUE(registry.valid(entity));
ASSERT_TRUE(registry.has<Component>(entity));
last = entity;
--counter;
}
template<typename Tag>
void decrTag(entt::DefaultRegistry &registry, entt::DefaultRegistry::entity_type entity) {
ASSERT_TRUE(registry.valid(entity));
ASSERT_TRUE(registry.has<Tag>());
ASSERT_EQ(registry.attachee<Tag>(), entity);
last = entity;
--counter;
}
entt::DefaultRegistry::entity_type last;
int counter{0};
};
TEST(DefaultRegistry, Types) {
entt::DefaultRegistry registry;
ASSERT_EQ(registry.type<int>(entt::tag_t{}), registry.type<int>(entt::tag_t{}));
ASSERT_EQ(registry.type<int>(), registry.type<int>());
ASSERT_NE(registry.type<int>(entt::tag_t{}), registry.type<double>(entt::tag_t{}));
ASSERT_NE(registry.type<int>(), registry.type<double>(entt::tag_t{}));
}
TEST(DefaultRegistry, Functionalities) {
entt::DefaultRegistry registry;
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{0});
ASSERT_EQ(registry.alive(), entt::DefaultRegistry::size_type{0});
ASSERT_NO_THROW(registry.reserve(42));
ASSERT_NO_THROW(registry.reserve<int>(8));
ASSERT_NO_THROW(registry.reserve<char>(8));
ASSERT_TRUE(registry.empty());
ASSERT_EQ(registry.capacity(), entt::DefaultRegistry::size_type{42});
ASSERT_EQ(registry.capacity<int>(), entt::DefaultRegistry::size_type{8});
ASSERT_EQ(registry.capacity<char>(), entt::DefaultRegistry::size_type{8});
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{0});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{0});
ASSERT_TRUE(registry.empty<int>());
ASSERT_TRUE(registry.empty<char>());
const auto e0 = registry.create();
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
ASSERT_TRUE(registry.has<>(e0));
ASSERT_TRUE(registry.has<>(e1));
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{1});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{1});
ASSERT_FALSE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NE(e0, e1);
ASSERT_FALSE(registry.has<int>(e0));
ASSERT_TRUE(registry.has<int>(e1));
ASSERT_FALSE(registry.has<char>(e0));
ASSERT_TRUE(registry.has<char>(e1));
ASSERT_FALSE((registry.has<int, char>(e0)));
ASSERT_TRUE((registry.has<int, char>(e1)));
ASSERT_EQ(registry.assign<int>(e0, 42), 42);
ASSERT_EQ(registry.assign<char>(e0, 'c'), 'c');
ASSERT_NO_THROW(registry.remove<int>(e1));
ASSERT_NO_THROW(registry.remove<char>(e1));
ASSERT_TRUE(registry.has<int>(e0));
ASSERT_FALSE(registry.has<int>(e1));
ASSERT_TRUE(registry.has<char>(e0));
ASSERT_FALSE(registry.has<char>(e1));
ASSERT_TRUE((registry.has<int, char>(e0)));
ASSERT_FALSE((registry.has<int, char>(e1)));
const auto e2 = registry.create();
registry.accommodate<int>(e2, registry.get<int>(e0));
registry.accommodate<char>(e2, registry.get<char>(e0));
ASSERT_TRUE(registry.has<int>(e2));
ASSERT_TRUE(registry.has<char>(e2));
ASSERT_EQ(registry.get<int>(e0), 42);
ASSERT_EQ(registry.get<char>(e0), 'c');
ASSERT_EQ(std::get<0>(registry.get<int, char>(e0)), 42);
ASSERT_EQ(std::get<1>(static_cast<const entt::DefaultRegistry &>(registry).get<int, char>(e0)), 'c');
ASSERT_EQ(registry.get<int>(e0), registry.get<int>(e2));
ASSERT_EQ(registry.get<char>(e0), registry.get<char>(e2));
ASSERT_NE(&registry.get<int>(e0), &registry.get<int>(e2));
ASSERT_NE(&registry.get<char>(e0), &registry.get<char>(e2));
ASSERT_NO_THROW(registry.replace<int>(e0, 0));
ASSERT_EQ(registry.get<int>(e0), 0);
ASSERT_NO_THROW(registry.accommodate<int>(e0, 1));
ASSERT_NO_THROW(registry.accommodate<int>(e1, 1));
ASSERT_EQ(static_cast<const entt::DefaultRegistry &>(registry).get<int>(e0), 1);
ASSERT_EQ(static_cast<const entt::DefaultRegistry &>(registry).get<int>(e1), 1);
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{3});
ASSERT_EQ(registry.alive(), entt::DefaultRegistry::size_type{3});
ASSERT_FALSE(registry.empty());
ASSERT_EQ(registry.version(e2), entt::DefaultRegistry::version_type{0});
ASSERT_EQ(registry.current(e2), entt::DefaultRegistry::version_type{0});
ASSERT_NO_THROW(registry.destroy(e2));
ASSERT_EQ(registry.version(e2), entt::DefaultRegistry::version_type{0});
ASSERT_EQ(registry.current(e2), entt::DefaultRegistry::version_type{1});
ASSERT_TRUE(registry.valid(e0));
ASSERT_TRUE(registry.fast(e0));
ASSERT_TRUE(registry.valid(e1));
ASSERT_TRUE(registry.fast(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_FALSE(registry.fast(e2));
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{3});
ASSERT_EQ(registry.alive(), entt::DefaultRegistry::size_type{2});
ASSERT_FALSE(registry.empty());
ASSERT_NO_THROW(registry.reset());
ASSERT_EQ(registry.size(), entt::DefaultRegistry::size_type{3});
ASSERT_EQ(registry.alive(), entt::DefaultRegistry::size_type{0});
ASSERT_TRUE(registry.empty());
const auto e3 = registry.create();
registry.assign<int>(e3);
registry.assign<char>(e3);
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{1});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{1});
ASSERT_FALSE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NO_THROW(registry.reset<int>());
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{0});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{1});
ASSERT_TRUE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NO_THROW(registry.reset());
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{0});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{0});
ASSERT_TRUE(registry.empty<int>());
ASSERT_TRUE(registry.empty<char>());
const auto e4 = registry.create();
const auto e5 = registry.create();
registry.assign<int>(e4);
ASSERT_NO_THROW(registry.reset<int>(e4));
ASSERT_NO_THROW(registry.reset<int>(e5));
ASSERT_EQ(registry.size<int>(), entt::DefaultRegistry::size_type{0});
ASSERT_EQ(registry.size<char>(), entt::DefaultRegistry::size_type{0});
ASSERT_TRUE(registry.empty<int>());
}
TEST(DefaultRegistry, Identifiers) {
entt::DefaultRegistry registry;
const auto pre = registry.create();
ASSERT_EQ(pre, registry.entity(pre));
registry.destroy(pre);
const auto post = registry.create();
ASSERT_NE(pre, post);
ASSERT_EQ(registry.entity(pre), registry.entity(post));
ASSERT_NE(registry.version(pre), registry.version(post));
ASSERT_NE(registry.version(pre), registry.current(pre));
ASSERT_EQ(registry.version(post), registry.current(post));
}
TEST(DefaultRegistry, RawData) {
entt::DefaultRegistry registry;
const entt::DefaultRegistry &cregistry = registry;
const auto entity = registry.create();
ASSERT_EQ(registry.raw<int>(), nullptr);
ASSERT_EQ(cregistry.raw<int>(), nullptr);
ASSERT_EQ(cregistry.data<int>(), nullptr);
registry.assign<int>(entity, 42);
ASSERT_NE(registry.raw<int>(), nullptr);
ASSERT_NE(cregistry.raw<int>(), nullptr);
ASSERT_NE(cregistry.data<int>(), nullptr);
ASSERT_EQ(*registry.raw<int>(), 42);
ASSERT_EQ(*cregistry.raw<int>(), 42);
ASSERT_EQ(*cregistry.data<int>(), entity);
}
TEST(DefaultRegistry, CreateDestroyCornerCase) {
entt::DefaultRegistry registry;
const auto e0 = registry.create();
const auto e1 = registry.create();
registry.destroy(e0);
registry.destroy(e1);
registry.each([](auto) { FAIL(); });
ASSERT_EQ(registry.current(e0), entt::DefaultRegistry::version_type{1});
ASSERT_EQ(registry.current(e1), entt::DefaultRegistry::version_type{1});
}
TEST(DefaultRegistry, VersionOverflow) {
entt::DefaultRegistry registry;
const auto entity = registry.create();
registry.destroy(entity);
ASSERT_EQ(registry.version(entity), entt::DefaultRegistry::version_type{});
for(auto i = entt::entt_traits<entt::DefaultRegistry::entity_type>::version_mask; i; --i) {
ASSERT_NE(registry.current(entity), registry.version(entity));
registry.destroy(registry.create());
}
ASSERT_EQ(registry.current(entity), registry.version(entity));
}
TEST(DefaultRegistry, Each) {
entt::DefaultRegistry registry;
entt::DefaultRegistry::size_type tot;
entt::DefaultRegistry::size_type match;
registry.create();
registry.assign<int>(registry.create());
registry.create();
registry.assign<int>(registry.create());
registry.create();
tot = 0u;
match = 0u;
registry.each([&](auto entity) {
if(registry.has<int>(entity)) { ++match; }
registry.create();
++tot;
});
ASSERT_EQ(tot, 5u);
ASSERT_EQ(match, 2u);
tot = 0u;
match = 0u;
registry.each([&](auto entity) {
if(registry.has<int>(entity)) {
registry.destroy(entity);
++match;
}
++tot;
});
ASSERT_EQ(tot, 10u);
ASSERT_EQ(match, 2u);
tot = 0u;
match = 0u;
registry.each([&](auto entity) {
if(registry.has<int>(entity)) { ++match; }
registry.destroy(entity);
++tot;
});
ASSERT_EQ(tot, 8u);
ASSERT_EQ(match, 0u);
registry.each([&](auto) { FAIL(); });
}
TEST(DefaultRegistry, Orphans) {
entt::DefaultRegistry registry;
entt::DefaultRegistry::size_type tot{};
registry.assign<int>(registry.create());
registry.create();
registry.assign<int>(registry.create());
registry.create();
registry.assign<double>(entt::tag_t{}, registry.create());
registry.orphans([&](auto) { ++tot; });
ASSERT_EQ(tot, 2u);
tot = 0u;
registry.each([&](auto entity) { registry.reset<int>(entity); });
registry.orphans([&](auto) { ++tot; });
ASSERT_EQ(tot, 4u);
registry.reset();
tot = 0u;
registry.orphans([&](auto) { ++tot; });
ASSERT_EQ(tot, 0u);
}
TEST(DefaultRegistry, CreateDestroyEntities) {
entt::DefaultRegistry registry;
entt::DefaultRegistry::entity_type pre{}, post{};
for(int i = 0; i < 10; ++i) {
const auto entity = registry.create();
registry.assign<double>(entity);
}
registry.reset();
for(int i = 0; i < 7; ++i) {
const auto entity = registry.create();
registry.assign<int>(entity);
if(i == 3) { pre = entity; }
}
registry.reset();
for(int i = 0; i < 5; ++i) {
const auto entity = registry.create();
if(i == 3) { post = entity; }
}
ASSERT_FALSE(registry.valid(pre));
ASSERT_TRUE(registry.valid(post));
ASSERT_NE(registry.version(pre), registry.version(post));
ASSERT_EQ(registry.version(pre) + 1, registry.version(post));
ASSERT_EQ(registry.current(pre), registry.current(post));
}
TEST(DefaultRegistry, AttachSetRemoveTags) {
entt::DefaultRegistry registry;
const auto &cregistry = registry;
ASSERT_FALSE(registry.has<int>());
const auto entity = registry.create();
registry.assign<int>(entt::tag_t{}, entity, 42);
ASSERT_TRUE(registry.has<int>());
ASSERT_TRUE(registry.has<int>(entt::tag_t{}, entity));
ASSERT_EQ(registry.get<int>(), 42);
ASSERT_EQ(cregistry.get<int>(), 42);
ASSERT_EQ(registry.attachee<int>(), entity);
registry.replace<int>(entt::tag_t{}, 3);
ASSERT_TRUE(registry.has<int>());
ASSERT_TRUE(registry.has<int>(entt::tag_t{}, entity));
ASSERT_EQ(registry.get<int>(), 3);
ASSERT_EQ(cregistry.get<int>(), 3);
ASSERT_EQ(registry.attachee<int>(), entity);
const auto other = registry.create();
registry.move<int>(other);
ASSERT_TRUE(registry.has<int>());
ASSERT_FALSE(registry.has<int>(entt::tag_t{}, entity));
ASSERT_TRUE(registry.has<int>(entt::tag_t{}, other));
ASSERT_EQ(registry.get<int>(), 3);
ASSERT_EQ(cregistry.get<int>(), 3);
ASSERT_EQ(registry.attachee<int>(), other);
registry.remove<int>();
ASSERT_FALSE(registry.has<int>());
ASSERT_FALSE(registry.has<int>(entt::tag_t{}, entity));
ASSERT_FALSE(registry.has<int>(entt::tag_t{}, other));
registry.assign<int>(entt::tag_t{}, entity, 42);
registry.destroy(entity);
ASSERT_FALSE(registry.has<int>());
ASSERT_FALSE(registry.has<int>(entt::tag_t{}, entity));
ASSERT_FALSE(registry.has<int>(entt::tag_t{}, other));
}
TEST(DefaultRegistry, StandardView) {
entt::DefaultRegistry registry;
auto mview = registry.view<int, char>();
auto iview = registry.view<int>();
auto cview = registry.view<char>();
const auto e0 = registry.create();
registry.assign<int>(e0, 0);
registry.assign<char>(e0, 'c');
const auto e1 = registry.create();
registry.assign<int>(e1, 0);
const auto e2 = registry.create();
registry.assign<int>(e2, 0);
registry.assign<char>(e2, 'c');
ASSERT_EQ(iview.size(), decltype(iview)::size_type{3});
ASSERT_EQ(cview.size(), decltype(cview)::size_type{2});
decltype(mview)::size_type cnt{0};
mview.each([&cnt](auto...) { ++cnt; });
ASSERT_EQ(cnt, decltype(mview)::size_type{2});
}
TEST(DefaultRegistry, PersistentView) {
entt::DefaultRegistry registry;
auto view = registry.view<int, char>(entt::persistent_t{});
ASSERT_TRUE((registry.contains<int, char>()));
ASSERT_FALSE((registry.contains<int, double>()));
registry.prepare<int, double>();
ASSERT_TRUE((registry.contains<int, double>()));
registry.discard<int, double>();
ASSERT_FALSE((registry.contains<int, double>()));
const auto e0 = registry.create();
registry.assign<int>(e0, 0);
registry.assign<char>(e0, 'c');
const auto e1 = registry.create();
registry.assign<int>(e1, 0);
const auto e2 = registry.create();
registry.assign<int>(e2, 0);
registry.assign<char>(e2, 'c');
decltype(view)::size_type cnt{0};
view.each([&cnt](auto...) { ++cnt; });
ASSERT_EQ(cnt, decltype(view)::size_type{2});
}
TEST(DefaultRegistry, RawView) {
entt::DefaultRegistry registry;
auto view = registry.view<int>(entt::raw_t{});
const auto e0 = registry.create();
registry.assign<int>(e0, 0);
registry.assign<char>(e0, 'c');
const auto e1 = registry.create();
registry.assign<int>(e1, 0);
registry.assign<char>(e1, 'c');
decltype(view)::size_type cnt{0};
view.each([&cnt](auto &...) { ++cnt; });
ASSERT_EQ(cnt, decltype(view)::size_type{2});
}
TEST(DefaultRegistry, CleanStandardViewAfterReset) {
entt::DefaultRegistry registry;
auto view = registry.view<int>();
registry.assign<int>(registry.create(), 0);
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{1});
registry.reset();
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{0});
}
TEST(DefaultRegistry, CleanPersistentViewAfterReset) {
entt::DefaultRegistry registry;
auto view = registry.view<int, char>(entt::persistent_t{});
const auto entity = registry.create();
registry.assign<int>(entity, 0);
registry.assign<char>(entity, 'c');
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{1});
registry.reset();
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{0});
}
TEST(DefaultRegistry, CleanRawViewAfterReset) {
entt::DefaultRegistry registry;
auto view = registry.view<int>(entt::raw_t{});
registry.assign<int>(registry.create(), 0);
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{1});
registry.reset();
ASSERT_EQ(view.size(), entt::DefaultRegistry::size_type{0});
}
TEST(DefaultRegistry, CleanTagsAfterReset) {
entt::DefaultRegistry registry;
const auto entity = registry.create();
registry.assign<int>(entt::tag_t{}, entity);
ASSERT_TRUE(registry.has<int>());
registry.reset();
ASSERT_FALSE(registry.has<int>());
}
TEST(DefaultRegistry, SortSingle) {
entt::DefaultRegistry registry;
int val = 0;
registry.assign<int>(registry.create(), val++);
registry.assign<int>(registry.create(), val++);
registry.assign<int>(registry.create(), val++);
for(auto entity: registry.view<int>()) {
ASSERT_EQ(registry.get<int>(entity), --val);
}
registry.sort<int>(std::less<int>{});
for(auto entity: registry.view<int>()) {
ASSERT_EQ(registry.get<int>(entity), val++);
}
}
TEST(DefaultRegistry, SortMulti) {
entt::DefaultRegistry registry;
unsigned int uval = 0u;
int ival = 0;
for(auto i = 0; i < 3; ++i) {
const auto entity = registry.create();
registry.assign<unsigned int>(entity, uval++);
registry.assign<int>(entity, ival++);
}
for(auto entity: registry.view<unsigned int>()) {
ASSERT_EQ(registry.get<unsigned int>(entity), --uval);
}
for(auto entity: registry.view<int>()) {
ASSERT_EQ(registry.get<int>(entity), --ival);
}
registry.sort<unsigned int>(std::less<unsigned int>{});
registry.sort<int, unsigned int>();
for(auto entity: registry.view<unsigned int>()) {
ASSERT_EQ(registry.get<unsigned int>(entity), uval++);
}
for(auto entity: registry.view<int>()) {
ASSERT_EQ(registry.get<int>(entity), ival++);
}
}
TEST(DefaultRegistry, ComponentsWithTypesFromStandardTemplateLibrary) {
// see #37 - the test shouldn't crash, that's all
entt::DefaultRegistry registry;
const auto entity = registry.create();
registry.assign<std::unordered_set<int>>(entity).insert(42);
registry.destroy(entity);
}
TEST(DefaultRegistry, ConstructWithComponents) {
// it should compile, that's all
entt::DefaultRegistry registry;
const auto value = 0;
registry.assign<int>(registry.create(), value);
}
TEST(DefaultRegistry, MergeTwoRegistries) {
using entity_type = entt::DefaultRegistry::entity_type;
entt::DefaultRegistry src;
entt::DefaultRegistry dst;
std::unordered_map<entity_type, entity_type> ref;
auto merge = [&ref](const auto &view, auto &dst) {
view.each([&](auto entity, const auto &component) {
if(ref.find(entity) == ref.cend()) {
const auto other = dst.create();
dst.template assign<std::decay_t<decltype(component)>>(other, component);
ref.emplace(entity, other);
} else {
using component_type = std::decay_t<decltype(component)>;
dst.template assign<component_type>(ref[entity], component);
}
});
};
auto e0 = src.create();
src.assign<int>(e0);
src.assign<float>(e0);
src.assign<double>(e0);
auto e1 = src.create();
src.assign<char>(e1);
src.assign<float>(e1);
src.assign<int>(e1);
auto e2 = dst.create();
dst.assign<int>(e2);
dst.assign<char>(e2);
dst.assign<double>(e2);
auto e3 = dst.create();
dst.assign<float>(e3);
dst.assign<int>(e3);
auto eq = [](auto begin, auto end) { ASSERT_EQ(begin, end); };
auto ne = [](auto begin, auto end) { ASSERT_NE(begin, end); };
eq(dst.view<int, float, double>().begin(), dst.view<int, float, double>().end());
eq(dst.view<char, float, int>().begin(), dst.view<char, float, int>().end());
merge(src.view<int>(), dst);
merge(src.view<char>(), dst);
merge(src.view<double>(), dst);
merge(src.view<float>(), dst);
ne(dst.view<int, float, double>().begin(), dst.view<int, float, double>().end());
ne(dst.view<char, float, int>().begin(), dst.view<char, float, int>().end());
}
TEST(DefaultRegistry, ComponentSignals) {
entt::DefaultRegistry registry;
Listener listener;
registry.construction<int>().connect<Listener, &Listener::incrComponent<int>>(&listener);
registry.destruction<int>().connect<Listener, &Listener::decrComponent<int>>(&listener);
auto e0 = registry.create();
auto e1 = registry.create();
registry.assign<int>(e0);
registry.assign<int>(e1);
ASSERT_EQ(listener.counter, 2);
ASSERT_EQ(listener.last, e1);
registry.remove<int>(e0);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e0);
registry.destruction<int>().disconnect<Listener, &Listener::decrComponent<int>>(&listener);
registry.remove<int>(e1);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e0);
registry.construction<int>().disconnect<Listener, &Listener::incrComponent<int>>(&listener);
registry.assign<int>(e1);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e0);
registry.construction<int>().connect<Listener, &Listener::incrComponent<int>>(&listener);
registry.destruction<int>().connect<Listener, &Listener::decrComponent<int>>(&listener);
registry.assign<int>(e0);
registry.reset<int>(e1);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e1);
registry.reset<int>();
ASSERT_EQ(listener.counter, 0);
ASSERT_EQ(listener.last, e0);
registry.assign<int>(e0);
registry.assign<int>(e1);
registry.destroy(e1);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e1);
}
TEST(DefaultRegistry, TagSignals) {
entt::DefaultRegistry registry;
Listener listener;
registry.construction<int>(entt::tag_t{}).connect<Listener, &Listener::incrTag<int>>(&listener);
registry.destruction<int>(entt::tag_t{}).connect<Listener, &Listener::decrTag<int>>(&listener);
auto e0 = registry.create();
registry.assign<int>(entt::tag_t{}, e0);
ASSERT_EQ(listener.counter, 1);
ASSERT_EQ(listener.last, e0);
auto e1 = registry.create();
registry.move<int>(e1);
registry.remove<int>();
ASSERT_EQ(listener.counter, 0);
ASSERT_EQ(listener.last, e1);
registry.construction<int>(entt::tag_t{}).disconnect<Listener, &Listener::incrTag<int>>(&listener);
registry.destruction<int>(entt::tag_t{}).disconnect<Listener, &Listener::decrTag<int>>(&listener);
registry.assign<int>(entt::tag_t{}, e0);
registry.remove<int>();
ASSERT_EQ(listener.counter, 0);
ASSERT_EQ(listener.last, e1);
registry.construction<int>(entt::tag_t{}).connect<Listener, &Listener::incrTag<int>>(&listener);
registry.destruction<int>(entt::tag_t{}).connect<Listener, &Listener::decrTag<int>>(&listener);
registry.assign<int>(entt::tag_t{}, e0);
registry.destroy(e0);
ASSERT_EQ(listener.counter, 0);
ASSERT_EQ(listener.last, e0);
}
TEST(DefaultRegistry, DestroyByTagAndComponents) {
entt::DefaultRegistry registry;
const auto e0 = registry.create();
const auto e1 = registry.create();
const auto e2 = registry.create();
const auto e3 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
registry.assign<double>(e0);
registry.assign<int>(e1);
registry.assign<char>(e1);
registry.assign<int>(e2);
registry.assign<float>(entt::tag_t{}, e3);
ASSERT_TRUE(registry.valid(e0));
ASSERT_TRUE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
registry.destroy<int, char, double>(entt::persistent_t{});
ASSERT_FALSE(registry.valid(e0));
ASSERT_TRUE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
registry.destroy<int, char>();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
registry.destroy<int>();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
registry.destroy<int>(entt::tag_t{});
registry.destroy<char>(entt::tag_t{});
registry.destroy<double>(entt::tag_t{});
registry.destroy<float>(entt::tag_t{});
}

View File

@@ -0,0 +1,575 @@
#include <tuple>
#include <queue>
#include <vector>
#include <gtest/gtest.h>
#include <entt/entity/registry.hpp>
template<typename Storage>
struct OutputArchive {
OutputArchive(Storage &storage)
: storage{storage}
{}
template<typename... Value>
void operator()(const Value &... value) {
using accumulator_type = int[];
accumulator_type accumulator = { (std::get<std::queue<Value>>(storage).push(value), 0)... };
(void)accumulator;
}
private:
Storage &storage;
};
template<typename Storage>
struct InputArchive {
InputArchive(Storage &storage)
: storage{storage}
{}
template<typename... Value>
void operator()(Value &... value) {
auto assign = [this](auto &value) {
auto &queue = std::get<std::queue<std::decay_t<decltype(value)>>>(storage);
value = queue.front();
queue.pop();
};
using accumulator_type = int[];
accumulator_type accumulator = { (assign(value), 0)... };
(void)accumulator;
}
private:
Storage &storage;
};
struct AComponent {};
struct AnotherComponent {
int key;
int value;
};
struct WhatAComponent {
entt::DefaultRegistry::entity_type bar;
std::vector<entt::DefaultRegistry::entity_type> quux;
};
TEST(Snapshot, Dump) {
entt::DefaultRegistry registry;
const auto e0 = registry.create();
registry.assign<int>(e0, 42);
registry.assign<char>(e0, 'c');
registry.assign<double>(e0, .1);
const auto e1 = registry.create();
const auto e2 = registry.create();
registry.assign<int>(e2, 3);
const auto e3 = registry.create();
registry.assign<char>(e3, '0');
registry.assign<float>(entt::tag_t{}, e3, .3f);
const auto e4 = registry.create();
registry.assign<AComponent>(entt::tag_t{}, e4);
registry.destroy(e1);
auto v1 = registry.current(e1);
using storage_type = std::tuple<
std::queue<entt::DefaultRegistry::entity_type>,
std::queue<int>,
std::queue<char>,
std::queue<double>,
std::queue<float>,
std::queue<bool>,
std::queue<AComponent>,
std::queue<AnotherComponent>,
std::queue<WhatAComponent>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
registry.snapshot()
.entities(output)
.destroyed(output)
.component<int, char, AnotherComponent, double>(output)
.tag<float, bool, AComponent>(output);
registry.reset();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_FALSE(registry.valid(e3));
ASSERT_FALSE(registry.valid(e4));
registry.restore()
.entities(input)
.destroyed(input)
.component<int, char, AnotherComponent, double>(input)
.tag<float, bool, AComponent>(input)
.orphans();
ASSERT_TRUE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
ASSERT_TRUE(registry.valid(e4));
ASSERT_FALSE(registry.orphan(e0));
ASSERT_FALSE(registry.orphan(e2));
ASSERT_FALSE(registry.orphan(e3));
ASSERT_FALSE(registry.orphan(e4));
ASSERT_EQ(registry.get<int>(e0), 42);
ASSERT_EQ(registry.get<char>(e0), 'c');
ASSERT_EQ(registry.get<double>(e0), .1);
ASSERT_EQ(registry.current(e1), v1);
ASSERT_EQ(registry.get<int>(e2), 3);
ASSERT_EQ(registry.get<char>(e3), '0');
ASSERT_TRUE(registry.has<float>());
ASSERT_EQ(registry.attachee<float>(), e3);
ASSERT_EQ(registry.get<float>(), .3f);
ASSERT_TRUE(registry.has<AComponent>());
ASSERT_EQ(registry.attachee<AComponent>(), e4);
ASSERT_TRUE(registry.empty<AnotherComponent>());
ASSERT_FALSE(registry.has<long int>());
}
TEST(Snapshot, Partial) {
entt::DefaultRegistry registry;
const auto e0 = registry.create();
registry.assign<int>(e0, 42);
registry.assign<char>(e0, 'c');
registry.assign<double>(e0, .1);
const auto e1 = registry.create();
const auto e2 = registry.create();
registry.assign<int>(e2, 3);
const auto e3 = registry.create();
registry.assign<char>(e3, '0');
registry.assign<float>(entt::tag_t{}, e3, .3f);
const auto e4 = registry.create();
registry.assign<AComponent>(entt::tag_t{}, e4);
registry.destroy(e1);
auto v1 = registry.current(e1);
using storage_type = std::tuple<
std::queue<entt::DefaultRegistry::entity_type>,
std::queue<int>,
std::queue<char>,
std::queue<double>,
std::queue<float>,
std::queue<bool>,
std::queue<AComponent>,
std::queue<WhatAComponent>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
registry.snapshot()
.entities(output)
.destroyed(output)
.component<char, int>(output)
.tag<bool, float>(output);
registry.reset();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_FALSE(registry.valid(e3));
ASSERT_FALSE(registry.valid(e4));
registry.restore()
.entities(input)
.destroyed(input)
.component<char, int>(input)
.tag<bool, float>(input);
ASSERT_TRUE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
ASSERT_TRUE(registry.valid(e4));
ASSERT_EQ(registry.get<int>(e0), 42);
ASSERT_EQ(registry.get<char>(e0), 'c');
ASSERT_FALSE(registry.has<double>(e0));
ASSERT_EQ(registry.current(e1), v1);
ASSERT_EQ(registry.get<int>(e2), 3);
ASSERT_EQ(registry.get<char>(e3), '0');
ASSERT_TRUE(registry.orphan(e4));
ASSERT_TRUE(registry.has<float>());
ASSERT_EQ(registry.attachee<float>(), e3);
ASSERT_EQ(registry.get<float>(), .3f);
ASSERT_FALSE(registry.has<long int>());
registry.snapshot()
.tag<float>(output)
.destroyed(output)
.entities(output);
registry.reset();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_FALSE(registry.valid(e3));
ASSERT_FALSE(registry.valid(e4));
registry.restore()
.tag<float>(input)
.destroyed(input)
.entities(input)
.orphans();
ASSERT_FALSE(registry.valid(e0));
ASSERT_FALSE(registry.valid(e1));
ASSERT_FALSE(registry.valid(e2));
ASSERT_TRUE(registry.valid(e3));
ASSERT_FALSE(registry.valid(e4));
}
TEST(Snapshot, Iterator) {
entt::DefaultRegistry registry;
for(auto i = 0; i < 50; ++i) {
const auto entity = registry.create();
registry.assign<AnotherComponent>(entity, i, i);
if(i % 2) {
registry.assign<AComponent>(entity);
}
}
using storage_type = std::tuple<
std::queue<entt::DefaultRegistry::entity_type>,
std::queue<AnotherComponent>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
const auto view = registry.view<AComponent>();
const auto size = view.size();
registry.snapshot().component<AnotherComponent>(output, view.cbegin(), view.cend());
registry.reset();
registry.restore().component<AnotherComponent>(input);
ASSERT_EQ(registry.view<AnotherComponent>().size(), size);
registry.view<AnotherComponent>().each([](const auto entity, auto &&...) {
ASSERT_TRUE(entity % 2);
});
}
TEST(Snapshot, Continuous) {
using entity_type = entt::DefaultRegistry::entity_type;
entt::DefaultRegistry src;
entt::DefaultRegistry dst;
entt::ContinuousLoader<entity_type> loader{dst};
std::vector<entity_type> entities;
entity_type entity;
using storage_type = std::tuple<
std::queue<entity_type>,
std::queue<AComponent>,
std::queue<AnotherComponent>,
std::queue<WhatAComponent>,
std::queue<double>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
for(int i = 0; i < 10; ++i) {
src.create();
}
src.reset();
for(int i = 0; i < 5; ++i) {
entity = src.create();
entities.push_back(entity);
src.assign<AComponent>(entity);
src.assign<AnotherComponent>(entity, i, i);
if(i % 2) {
src.assign<WhatAComponent>(entity, entity);
} else if(i == 2) {
src.assign<double>(entt::tag_t{}, entity, .3);
}
}
src.view<WhatAComponent>().each([&entities](auto, auto &whatAComponent) {
whatAComponent.quux.insert(whatAComponent.quux.begin(), entities.begin(), entities.end());
});
entity = dst.create();
dst.assign<AComponent>(entity);
dst.assign<AnotherComponent>(entity, -1, -1);
src.snapshot()
.entities(output)
.destroyed(output)
.component<AComponent, AnotherComponent, WhatAComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<AComponent, AnotherComponent, WhatAComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans();
decltype(dst.size()) aComponentCnt{};
decltype(dst.size()) anotherComponentCnt{};
decltype(dst.size()) whatAComponentCnt{};
dst.each([&dst, &aComponentCnt](auto entity) {
ASSERT_TRUE(dst.has<AComponent>(entity));
++aComponentCnt;
});
dst.view<AnotherComponent>().each([&anotherComponentCnt](auto, const auto &component) {
ASSERT_EQ(component.value, component.key < 0 ? -1 : component.key);
++anotherComponentCnt;
});
dst.view<WhatAComponent>().each([&dst, &whatAComponentCnt](auto entity, const auto &component) {
ASSERT_EQ(entity, component.bar);
for(auto entity: component.quux) {
ASSERT_TRUE(dst.valid(entity));
}
++whatAComponentCnt;
});
ASSERT_TRUE(dst.has<double>());
ASSERT_EQ(dst.get<double>(), .3);
src.view<AnotherComponent>().each([](auto, auto &component) {
component.value = 2 * component.key;
});
auto size = dst.size();
src.snapshot()
.entities(output)
.destroyed(output)
.component<AComponent, WhatAComponent, AnotherComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<AComponent, WhatAComponent, AnotherComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans();
ASSERT_EQ(size, dst.size());
ASSERT_EQ(dst.size<AComponent>(), aComponentCnt);
ASSERT_EQ(dst.size<AnotherComponent>(), anotherComponentCnt);
ASSERT_EQ(dst.size<WhatAComponent>(), whatAComponentCnt);
ASSERT_TRUE(dst.has<double>());
dst.view<AnotherComponent>().each([](auto, auto &component) {
ASSERT_EQ(component.value, component.key < 0 ? -1 : (2 * component.key));
});
entity = src.create();
src.view<WhatAComponent>().each([entity](auto, auto &component) {
component.bar = entity;
});
src.snapshot()
.entities(output)
.destroyed(output)
.component<WhatAComponent, AComponent, AnotherComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<WhatAComponent, AComponent, AnotherComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans();
dst.view<WhatAComponent>().each([&loader, entity](auto, auto &component) {
ASSERT_EQ(component.bar, loader.map(entity));
});
entities.clear();
for(auto entity: src.view<AComponent>()) {
entities.push_back(entity);
}
src.destroy(entity);
loader.shrink();
src.snapshot()
.entities(output)
.destroyed(output)
.component<AComponent, AnotherComponent, WhatAComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<AComponent, AnotherComponent, WhatAComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans()
.shrink();
dst.view<WhatAComponent>().each([&dst](auto, auto &component) {
ASSERT_FALSE(dst.valid(component.bar));
});
ASSERT_FALSE(loader.has(entity));
entity = src.create();
src.view<WhatAComponent>().each([entity](auto, auto &component) {
component.bar = entity;
});
dst.reset<AComponent>();
aComponentCnt = src.size<AComponent>();
src.snapshot()
.entities(output)
.destroyed(output)
.component<AComponent, WhatAComponent, AnotherComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<AComponent, WhatAComponent, AnotherComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans();
ASSERT_EQ(dst.size<AComponent>(), aComponentCnt);
ASSERT_TRUE(dst.has<double>());
src.reset<AComponent>();
src.remove<double>();
aComponentCnt = {};
src.snapshot()
.entities(output)
.destroyed(output)
.component<WhatAComponent, AComponent, AnotherComponent>(output)
.tag<double>(output);
loader.entities(input)
.destroyed(input)
.component<WhatAComponent, AComponent, AnotherComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<double>(input)
.orphans();
ASSERT_EQ(dst.size<AComponent>(), aComponentCnt);
ASSERT_FALSE(dst.has<double>());
}
TEST(Snapshot, ContinuousMoreOnShrink) {
using entity_type = entt::DefaultRegistry::entity_type;
entt::DefaultRegistry src;
entt::DefaultRegistry dst;
entt::ContinuousLoader<entity_type> loader{dst};
using storage_type = std::tuple<
std::queue<entity_type>,
std::queue<AComponent>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
auto entity = src.create();
src.snapshot().entities(output);
loader.entities(input).shrink();
ASSERT_TRUE(dst.valid(entity));
loader.shrink();
ASSERT_FALSE(dst.valid(entity));
}
TEST(Snapshot, SyncDataMembers) {
using entity_type = entt::DefaultRegistry::entity_type;
entt::DefaultRegistry src;
entt::DefaultRegistry dst;
entt::ContinuousLoader<entity_type> loader{dst};
using storage_type = std::tuple<
std::queue<entity_type>,
std::queue<WhatAComponent>
>;
storage_type storage;
OutputArchive<storage_type> output{storage};
InputArchive<storage_type> input{storage};
src.create();
src.create();
src.reset();
auto parent = src.create();
auto child = src.create();
src.assign<WhatAComponent>(entt::tag_t{}, child, parent).quux.push_back(parent);
src.assign<WhatAComponent>(child, child).quux.push_back(child);
src.snapshot().entities(output)
.component<WhatAComponent>(output)
.tag<WhatAComponent>(output);
loader.entities(input)
.component<WhatAComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux)
.tag<WhatAComponent>(input, &WhatAComponent::bar, &WhatAComponent::quux);
ASSERT_FALSE(dst.valid(parent));
ASSERT_FALSE(dst.valid(child));
ASSERT_TRUE(dst.has<WhatAComponent>());
ASSERT_EQ(dst.attachee<WhatAComponent>(), loader.map(child));
ASSERT_EQ(dst.get<WhatAComponent>().bar, loader.map(parent));
ASSERT_EQ(dst.get<WhatAComponent>().quux[0], loader.map(parent));
ASSERT_TRUE(dst.has<WhatAComponent>(loader.map(child)));
const auto &component = dst.get<WhatAComponent>(loader.map(child));
ASSERT_EQ(component.bar, loader.map(child));
ASSERT_EQ(component.quux[0], loader.map(child));
}

View File

@@ -0,0 +1,901 @@
#include <unordered_set>
#include <gtest/gtest.h>
#include <entt/entity/sparse_set.hpp>
TEST(SparseSetNoType, Functionalities) {
entt::SparseSet<std::uint64_t> set;
const auto &cset = set;
set.reserve(42);
ASSERT_EQ(set.capacity(), 42);
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
set.construct(42);
ASSERT_EQ(set.get(42), 0u);
ASSERT_FALSE(set.empty());
ASSERT_EQ(set.size(), 1u);
ASSERT_NE(cset.begin(), cset.end());
ASSERT_NE(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_TRUE(set.has(42));
ASSERT_TRUE(set.fast(42));
ASSERT_EQ(set.get(42), 0u);
set.destroy(42);
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
set.construct(42);
ASSERT_EQ(set.get(42), 0u);
set.reset();
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
(void)entt::SparseSet<std::uint64_t>{std::move(set)};
entt::SparseSet<std::uint64_t> other;
other = std::move(set);
}
TEST(SparseSetNoType, ElementAccess) {
entt::SparseSet<std::uint64_t> set;
const auto &cset = set;
set.construct(42);
set.construct(3);
for(typename entt::SparseSet<std::uint64_t>::size_type i{}; i < set.size(); ++i) {
ASSERT_EQ(set[i], i ? 42 : 3);
ASSERT_EQ(cset[i], i ? 42 : 3);
}
}
TEST(SparseSetNoType, Iterator) {
using iterator_type = typename entt::SparseSet<std::uint64_t>::iterator_type;
entt::SparseSet<std::uint64_t> set;
set.construct(3);
iterator_type end{set.begin()};
iterator_type begin{};
begin = set.end();
std::swap(begin, end);
ASSERT_EQ(begin, set.begin());
ASSERT_EQ(end, set.end());
ASSERT_NE(begin, end);
ASSERT_EQ(begin++, set.begin());
ASSERT_EQ(begin--, set.end());
ASSERT_EQ(begin+1, set.end());
ASSERT_EQ(end-1, set.begin());
ASSERT_EQ(++begin, set.end());
ASSERT_EQ(--begin, set.begin());
ASSERT_EQ(begin += 1, set.end());
ASSERT_EQ(begin -= 1, set.begin());
ASSERT_EQ(begin + (end - begin), set.end());
ASSERT_EQ(begin - (begin - end), set.end());
ASSERT_EQ(end - (end - begin), set.begin());
ASSERT_EQ(end + (begin - end), set.begin());
ASSERT_EQ(begin[0], *set.begin());
ASSERT_LT(begin, end);
ASSERT_LE(begin, set.begin());
ASSERT_GT(end, begin);
ASSERT_GE(end, set.end());
ASSERT_EQ(*begin, 3);
ASSERT_EQ(*begin.operator->(), 3);
}
TEST(SparseSetNoType, ConstIterator) {
using iterator_type = typename entt::SparseSet<std::uint64_t>::const_iterator_type;
entt::SparseSet<std::uint64_t> set;
set.construct(3);
iterator_type cend{set.cbegin()};
iterator_type cbegin{};
cbegin = set.cend();
std::swap(cbegin, cend);
ASSERT_EQ(cbegin, set.cbegin());
ASSERT_EQ(cend, set.cend());
ASSERT_NE(cbegin, cend);
ASSERT_EQ(cbegin++, set.cbegin());
ASSERT_EQ(cbegin--, set.cend());
ASSERT_EQ(cbegin+1, set.cend());
ASSERT_EQ(cend-1, set.cbegin());
ASSERT_EQ(++cbegin, set.cend());
ASSERT_EQ(--cbegin, set.cbegin());
ASSERT_EQ(cbegin += 1, set.cend());
ASSERT_EQ(cbegin -= 1, set.cbegin());
ASSERT_EQ(cbegin + (cend - cbegin), set.cend());
ASSERT_EQ(cbegin - (cbegin - cend), set.cend());
ASSERT_EQ(cend - (cend - cbegin), set.cbegin());
ASSERT_EQ(cend + (cbegin - cend), set.cbegin());
ASSERT_EQ(cbegin[0], *set.cbegin());
ASSERT_LT(cbegin, cend);
ASSERT_LE(cbegin, set.cbegin());
ASSERT_GT(cend, cbegin);
ASSERT_GE(cend, set.cend());
ASSERT_EQ(*cbegin, 3);
ASSERT_EQ(*cbegin.operator->(), 3);
}
TEST(SparseSetNoType, Data) {
entt::SparseSet<std::uint64_t> set;
set.construct(3);
set.construct(12);
set.construct(42);
ASSERT_EQ(set.get(3), 0u);
ASSERT_EQ(set.get(12), 1u);
ASSERT_EQ(set.get(42), 2u);
ASSERT_EQ(*(set.data() + 0u), 3u);
ASSERT_EQ(*(set.data() + 1u), 12u);
ASSERT_EQ(*(set.data() + 2u), 42u);
}
TEST(SparseSetNoType, RespectDisjoint) {
entt::SparseSet<std::uint64_t> lhs;
entt::SparseSet<std::uint64_t> rhs;
const auto &clhs = lhs;
lhs.construct(3);
lhs.construct(12);
lhs.construct(42);
ASSERT_EQ(lhs.get(3), 0u);
ASSERT_EQ(lhs.get(12), 1u);
ASSERT_EQ(lhs.get(42), 2u);
lhs.respect(rhs);
ASSERT_EQ(clhs.get(3), 0u);
ASSERT_EQ(clhs.get(12), 1u);
ASSERT_EQ(clhs.get(42), 2u);
}
TEST(SparseSetNoType, RespectOverlap) {
entt::SparseSet<std::uint64_t> lhs;
entt::SparseSet<std::uint64_t> rhs;
const auto &clhs = lhs;
lhs.construct(3);
lhs.construct(12);
lhs.construct(42);
rhs.construct(12);
ASSERT_EQ(lhs.get(3), 0u);
ASSERT_EQ(lhs.get(12), 1u);
ASSERT_EQ(lhs.get(42), 2u);
lhs.respect(rhs);
ASSERT_EQ(clhs.get(3), 0u);
ASSERT_EQ(clhs.get(12), 2u);
ASSERT_EQ(clhs.get(42), 1u);
}
TEST(SparseSetNoType, RespectOrdered) {
entt::SparseSet<std::uint64_t> lhs;
entt::SparseSet<std::uint64_t> rhs;
lhs.construct(1);
lhs.construct(2);
lhs.construct(3);
lhs.construct(4);
lhs.construct(5);
ASSERT_EQ(lhs.get(1), 0u);
ASSERT_EQ(lhs.get(2), 1u);
ASSERT_EQ(lhs.get(3), 2u);
ASSERT_EQ(lhs.get(4), 3u);
ASSERT_EQ(lhs.get(5), 4u);
rhs.construct(6);
rhs.construct(1);
rhs.construct(2);
rhs.construct(3);
rhs.construct(4);
rhs.construct(5);
ASSERT_EQ(rhs.get(6), 0u);
ASSERT_EQ(rhs.get(1), 1u);
ASSERT_EQ(rhs.get(2), 2u);
ASSERT_EQ(rhs.get(3), 3u);
ASSERT_EQ(rhs.get(4), 4u);
ASSERT_EQ(rhs.get(5), 5u);
rhs.respect(lhs);
ASSERT_EQ(rhs.get(6), 0u);
ASSERT_EQ(rhs.get(1), 1u);
ASSERT_EQ(rhs.get(2), 2u);
ASSERT_EQ(rhs.get(3), 3u);
ASSERT_EQ(rhs.get(4), 4u);
ASSERT_EQ(rhs.get(5), 5u);
}
TEST(SparseSetNoType, RespectReverse) {
entt::SparseSet<std::uint64_t> lhs;
entt::SparseSet<std::uint64_t> rhs;
lhs.construct(1);
lhs.construct(2);
lhs.construct(3);
lhs.construct(4);
lhs.construct(5);
ASSERT_EQ(lhs.get(1), 0u);
ASSERT_EQ(lhs.get(2), 1u);
ASSERT_EQ(lhs.get(3), 2u);
ASSERT_EQ(lhs.get(4), 3u);
ASSERT_EQ(lhs.get(5), 4u);
rhs.construct(5);
rhs.construct(4);
rhs.construct(3);
rhs.construct(2);
rhs.construct(1);
rhs.construct(6);
ASSERT_EQ(rhs.get(5), 0u);
ASSERT_EQ(rhs.get(4), 1u);
ASSERT_EQ(rhs.get(3), 2u);
ASSERT_EQ(rhs.get(2), 3u);
ASSERT_EQ(rhs.get(1), 4u);
ASSERT_EQ(rhs.get(6), 5u);
rhs.respect(lhs);
ASSERT_EQ(rhs.get(6), 0u);
ASSERT_EQ(rhs.get(1), 1u);
ASSERT_EQ(rhs.get(2), 2u);
ASSERT_EQ(rhs.get(3), 3u);
ASSERT_EQ(rhs.get(4), 4u);
ASSERT_EQ(rhs.get(5), 5u);
}
TEST(SparseSetNoType, RespectUnordered) {
entt::SparseSet<std::uint64_t> lhs;
entt::SparseSet<std::uint64_t> rhs;
lhs.construct(1);
lhs.construct(2);
lhs.construct(3);
lhs.construct(4);
lhs.construct(5);
ASSERT_EQ(lhs.get(1), 0u);
ASSERT_EQ(lhs.get(2), 1u);
ASSERT_EQ(lhs.get(3), 2u);
ASSERT_EQ(lhs.get(4), 3u);
ASSERT_EQ(lhs.get(5), 4u);
rhs.construct(3);
rhs.construct(2);
rhs.construct(6);
rhs.construct(1);
rhs.construct(4);
rhs.construct(5);
ASSERT_EQ(rhs.get(3), 0u);
ASSERT_EQ(rhs.get(2), 1u);
ASSERT_EQ(rhs.get(6), 2u);
ASSERT_EQ(rhs.get(1), 3u);
ASSERT_EQ(rhs.get(4), 4u);
ASSERT_EQ(rhs.get(5), 5u);
rhs.respect(lhs);
ASSERT_EQ(rhs.get(6), 0u);
ASSERT_EQ(rhs.get(1), 1u);
ASSERT_EQ(rhs.get(2), 2u);
ASSERT_EQ(rhs.get(3), 3u);
ASSERT_EQ(rhs.get(4), 4u);
ASSERT_EQ(rhs.get(5), 5u);
}
TEST(SparseSetNoType, CanModifyDuringIteration) {
entt::SparseSet<std::uint64_t> set;
set.construct(0);
ASSERT_EQ(set.capacity(), entt::SparseSet<std::uint64_t>::size_type{1});
const auto it = set.cbegin();
set.reserve(entt::SparseSet<std::uint64_t>::size_type{2});
ASSERT_EQ(set.capacity(), entt::SparseSet<std::uint64_t>::size_type{2});
// this should crash with asan enabled if we break the constraint
const auto entity = *it;
(void)entity;
}
TEST(SparseSetWithType, Functionalities) {
entt::SparseSet<std::uint64_t, int> set;
const auto &cset = set;
set.reserve(42);
ASSERT_EQ(set.capacity(), 42);
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
set.construct(42, 3);
ASSERT_FALSE(set.empty());
ASSERT_EQ(set.size(), 1u);
ASSERT_NE(cset.begin(), cset.end());
ASSERT_NE(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_TRUE(set.has(42));
ASSERT_TRUE(set.fast(42));
ASSERT_EQ(set.get(42), 3);
set.destroy(42);
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
set.construct(42, 12);
ASSERT_EQ(set.get(42), 12);
set.reset();
ASSERT_TRUE(set.empty());
ASSERT_EQ(set.size(), 0u);
ASSERT_EQ(cset.begin(), cset.end());
ASSERT_EQ(set.begin(), set.end());
ASSERT_FALSE(set.has(0));
ASSERT_FALSE(set.has(42));
(void)entt::SparseSet<std::uint64_t>{std::move(set)};
entt::SparseSet<std::uint64_t> other;
other = std::move(set);
}
TEST(SparseSetWithType, ElementAccess) {
entt::SparseSet<std::uint64_t, int> set;
const auto &cset = set;
set.construct(42, 1);
set.construct(3, 0);
for(typename entt::SparseSet<std::uint64_t, int>::size_type i{}; i < set.size(); ++i) {
ASSERT_EQ(set[i], i);
ASSERT_EQ(cset[i], i);
}
}
TEST(SparseSetWithType, AggregatesMustWork) {
struct AggregateType { int value; };
// the goal of this test is to enforce the requirements for aggregate types
entt::SparseSet<std::uint64_t, AggregateType>{}.construct(0, 42);
}
TEST(SparseSetWithType, TypesFromStandardTemplateLibraryMustWork) {
// see #37 - this test shouldn't crash, that's all
entt::SparseSet<std::uint64_t, std::unordered_set<int>> set;
set.construct(0).insert(42);
set.destroy(0);
}
TEST(SparseSetWithType, Iterator) {
struct InternalType { int value; };
using iterator_type = typename entt::SparseSet<std::uint64_t, InternalType>::iterator_type;
entt::SparseSet<std::uint64_t, InternalType> set;
set.construct(3, 42);
iterator_type end{set.begin()};
iterator_type begin{};
begin = set.end();
std::swap(begin, end);
ASSERT_EQ(begin, set.begin());
ASSERT_EQ(end, set.end());
ASSERT_NE(begin, end);
ASSERT_EQ(begin++, set.begin());
ASSERT_EQ(begin--, set.end());
ASSERT_EQ(begin+1, set.end());
ASSERT_EQ(end-1, set.begin());
ASSERT_EQ(++begin, set.end());
ASSERT_EQ(--begin, set.begin());
ASSERT_EQ(begin += 1, set.end());
ASSERT_EQ(begin -= 1, set.begin());
ASSERT_EQ(begin + (end - begin), set.end());
ASSERT_EQ(begin - (begin - end), set.end());
ASSERT_EQ(end - (end - begin), set.begin());
ASSERT_EQ(end + (begin - end), set.begin());
ASSERT_EQ(begin[0].value, set.begin()->value);
ASSERT_LT(begin, end);
ASSERT_LE(begin, set.begin());
ASSERT_GT(end, begin);
ASSERT_GE(end, set.end());
}
TEST(SparseSetWithType, ConstIterator) {
struct InternalType { int value; };
using iterator_type = typename entt::SparseSet<std::uint64_t, InternalType>::const_iterator_type;
entt::SparseSet<std::uint64_t, InternalType> set;
set.construct(3, 42);
iterator_type cend{set.cbegin()};
iterator_type cbegin{};
cbegin = set.cend();
std::swap(cbegin, cend);
ASSERT_EQ(cbegin, set.cbegin());
ASSERT_EQ(cend, set.cend());
ASSERT_NE(cbegin, cend);
ASSERT_EQ(cbegin++, set.cbegin());
ASSERT_EQ(cbegin--, set.cend());
ASSERT_EQ(cbegin+1, set.cend());
ASSERT_EQ(cend-1, set.cbegin());
ASSERT_EQ(++cbegin, set.cend());
ASSERT_EQ(--cbegin, set.cbegin());
ASSERT_EQ(cbegin += 1, set.cend());
ASSERT_EQ(cbegin -= 1, set.cbegin());
ASSERT_EQ(cbegin + (cend - cbegin), set.cend());
ASSERT_EQ(cbegin - (cbegin - cend), set.cend());
ASSERT_EQ(cend - (cend - cbegin), set.cbegin());
ASSERT_EQ(cend + (cbegin - cend), set.cbegin());
ASSERT_EQ(cbegin[0].value, set.cbegin()->value);
ASSERT_LT(cbegin, cend);
ASSERT_LE(cbegin, set.cbegin());
ASSERT_GT(cend, cbegin);
ASSERT_GE(cend, set.cend());
}
TEST(SparseSetWithType, Raw) {
entt::SparseSet<std::uint64_t, int> set;
set.construct(3, 3);
set.construct(12, 6);
set.construct(42, 9);
ASSERT_EQ(set.get(3), 3);
ASSERT_EQ(set.get(12), 6);
ASSERT_EQ(set.get(42), 9);
ASSERT_EQ(*(set.raw() + 0u), 3);
ASSERT_EQ(*(set.raw() + 1u), 6);
ASSERT_EQ(*(set.raw() + 2u), 9);
}
TEST(SparseSetWithType, SortOrdered) {
entt::SparseSet<std::uint64_t, int> set;
set.construct(12, 12);
set.construct(42, 9);
set.construct(7, 6);
set.construct(3, 3);
set.construct(9, 1);
ASSERT_EQ(set.get(12), 12);
ASSERT_EQ(set.get(42), 9);
ASSERT_EQ(set.get(7), 6);
ASSERT_EQ(set.get(3), 3);
ASSERT_EQ(set.get(9), 1);
set.sort([](auto lhs, auto rhs) {
return lhs < rhs;
});
ASSERT_EQ(*(set.raw() + 0u), 12);
ASSERT_EQ(*(set.raw() + 1u), 9);
ASSERT_EQ(*(set.raw() + 2u), 6);
ASSERT_EQ(*(set.raw() + 3u), 3);
ASSERT_EQ(*(set.raw() + 4u), 1);
auto begin = set.begin();
auto end = set.end();
ASSERT_EQ(*(begin++), 1);
ASSERT_EQ(*(begin++), 3);
ASSERT_EQ(*(begin++), 6);
ASSERT_EQ(*(begin++), 9);
ASSERT_EQ(*(begin++), 12);
ASSERT_EQ(begin, end);
}
TEST(SparseSetWithType, SortReverse) {
entt::SparseSet<std::uint64_t, int> set;
set.construct(12, 1);
set.construct(42, 3);
set.construct(7, 6);
set.construct(3, 9);
set.construct(9, 12);
ASSERT_EQ(set.get(12), 1);
ASSERT_EQ(set.get(42), 3);
ASSERT_EQ(set.get(7), 6);
ASSERT_EQ(set.get(3), 9);
ASSERT_EQ(set.get(9), 12);
set.sort([](auto lhs, auto rhs) {
return lhs < rhs;
});
ASSERT_EQ(*(set.raw() + 0u), 12);
ASSERT_EQ(*(set.raw() + 1u), 9);
ASSERT_EQ(*(set.raw() + 2u), 6);
ASSERT_EQ(*(set.raw() + 3u), 3);
ASSERT_EQ(*(set.raw() + 4u), 1);
auto begin = set.begin();
auto end = set.end();
ASSERT_EQ(*(begin++), 1);
ASSERT_EQ(*(begin++), 3);
ASSERT_EQ(*(begin++), 6);
ASSERT_EQ(*(begin++), 9);
ASSERT_EQ(*(begin++), 12);
ASSERT_EQ(begin, end);
}
TEST(SparseSetWithType, SortUnordered) {
entt::SparseSet<std::uint64_t, int> set;
set.construct(12, 6);
set.construct(42, 3);
set.construct(7, 1);
set.construct(3, 9);
set.construct(9, 12);
ASSERT_EQ(set.get(12), 6);
ASSERT_EQ(set.get(42), 3);
ASSERT_EQ(set.get(7), 1);
ASSERT_EQ(set.get(3), 9);
ASSERT_EQ(set.get(9), 12);
set.sort([](auto lhs, auto rhs) {
return lhs < rhs;
});
ASSERT_EQ(*(set.raw() + 0u), 12);
ASSERT_EQ(*(set.raw() + 1u), 9);
ASSERT_EQ(*(set.raw() + 2u), 6);
ASSERT_EQ(*(set.raw() + 3u), 3);
ASSERT_EQ(*(set.raw() + 4u), 1);
auto begin = set.begin();
auto end = set.end();
ASSERT_EQ(*(begin++), 1);
ASSERT_EQ(*(begin++), 3);
ASSERT_EQ(*(begin++), 6);
ASSERT_EQ(*(begin++), 9);
ASSERT_EQ(*(begin++), 12);
ASSERT_EQ(begin, end);
}
TEST(SparseSetWithType, RespectDisjoint) {
entt::SparseSet<std::uint64_t, int> lhs;
entt::SparseSet<std::uint64_t, int> rhs;
const auto &clhs = lhs;
lhs.construct(3, 3);
lhs.construct(12, 6);
lhs.construct(42, 9);
ASSERT_EQ(clhs.get(3), 3);
ASSERT_EQ(clhs.get(12), 6);
ASSERT_EQ(clhs.get(42), 9);
lhs.respect(rhs);
ASSERT_EQ(*(clhs.raw() + 0u), 3);
ASSERT_EQ(*(clhs.raw() + 1u), 6);
ASSERT_EQ(*(clhs.raw() + 2u), 9);
auto begin = lhs.begin();
auto end = lhs.end();
ASSERT_EQ(*(begin++), 9);
ASSERT_EQ(*(begin++), 6);
ASSERT_EQ(*(begin++), 3);
ASSERT_EQ(begin, end);
}
TEST(SparseSetWithType, RespectOverlap) {
entt::SparseSet<std::uint64_t, int> lhs;
entt::SparseSet<std::uint64_t, int> rhs;
const auto &clhs = lhs;
lhs.construct(3, 3);
lhs.construct(12, 6);
lhs.construct(42, 9);
rhs.construct(12, 6);
ASSERT_EQ(clhs.get(3), 3);
ASSERT_EQ(clhs.get(12), 6);
ASSERT_EQ(clhs.get(42), 9);
ASSERT_EQ(rhs.get(12), 6);
lhs.respect(rhs);
ASSERT_EQ(*(clhs.raw() + 0u), 3);
ASSERT_EQ(*(clhs.raw() + 1u), 9);
ASSERT_EQ(*(clhs.raw() + 2u), 6);
auto begin = lhs.begin();
auto end = lhs.end();
ASSERT_EQ(*(begin++), 6);
ASSERT_EQ(*(begin++), 9);
ASSERT_EQ(*(begin++), 3);
ASSERT_EQ(begin, end);
}
TEST(SparseSetWithType, RespectOrdered) {
entt::SparseSet<std::uint64_t, int> lhs;
entt::SparseSet<std::uint64_t, int> rhs;
lhs.construct(1, 0);
lhs.construct(2, 0);
lhs.construct(3, 0);
lhs.construct(4, 0);
lhs.construct(5, 0);
ASSERT_EQ(lhs.get(1), 0);
ASSERT_EQ(lhs.get(2), 0);
ASSERT_EQ(lhs.get(3), 0);
ASSERT_EQ(lhs.get(4), 0);
ASSERT_EQ(lhs.get(5), 0);
rhs.construct(6, 0);
rhs.construct(1, 0);
rhs.construct(2, 0);
rhs.construct(3, 0);
rhs.construct(4, 0);
rhs.construct(5, 0);
ASSERT_EQ(rhs.get(6), 0);
ASSERT_EQ(rhs.get(1), 0);
ASSERT_EQ(rhs.get(2), 0);
ASSERT_EQ(rhs.get(3), 0);
ASSERT_EQ(rhs.get(4), 0);
ASSERT_EQ(rhs.get(5), 0);
rhs.respect(lhs);
ASSERT_EQ(*(lhs.data() + 0u), 1u);
ASSERT_EQ(*(lhs.data() + 1u), 2u);
ASSERT_EQ(*(lhs.data() + 2u), 3u);
ASSERT_EQ(*(lhs.data() + 3u), 4u);
ASSERT_EQ(*(lhs.data() + 4u), 5u);
ASSERT_EQ(*(rhs.data() + 0u), 6u);
ASSERT_EQ(*(rhs.data() + 1u), 1u);
ASSERT_EQ(*(rhs.data() + 2u), 2u);
ASSERT_EQ(*(rhs.data() + 3u), 3u);
ASSERT_EQ(*(rhs.data() + 4u), 4u);
ASSERT_EQ(*(rhs.data() + 5u), 5u);
}
TEST(SparseSetWithType, RespectReverse) {
entt::SparseSet<std::uint64_t, int> lhs;
entt::SparseSet<std::uint64_t, int> rhs;
lhs.construct(1, 0);
lhs.construct(2, 0);
lhs.construct(3, 0);
lhs.construct(4, 0);
lhs.construct(5, 0);
ASSERT_EQ(lhs.get(1), 0);
ASSERT_EQ(lhs.get(2), 0);
ASSERT_EQ(lhs.get(3), 0);
ASSERT_EQ(lhs.get(4), 0);
ASSERT_EQ(lhs.get(5), 0);
rhs.construct(5, 0);
rhs.construct(4, 0);
rhs.construct(3, 0);
rhs.construct(2, 0);
rhs.construct(1, 0);
rhs.construct(6, 0);
ASSERT_EQ(rhs.get(5), 0);
ASSERT_EQ(rhs.get(4), 0);
ASSERT_EQ(rhs.get(3), 0);
ASSERT_EQ(rhs.get(2), 0);
ASSERT_EQ(rhs.get(1), 0);
ASSERT_EQ(rhs.get(6), 0);
rhs.respect(lhs);
ASSERT_EQ(*(lhs.data() + 0u), 1u);
ASSERT_EQ(*(lhs.data() + 1u), 2u);
ASSERT_EQ(*(lhs.data() + 2u), 3u);
ASSERT_EQ(*(lhs.data() + 3u), 4u);
ASSERT_EQ(*(lhs.data() + 4u), 5u);
ASSERT_EQ(*(rhs.data() + 0u), 6u);
ASSERT_EQ(*(rhs.data() + 1u), 1u);
ASSERT_EQ(*(rhs.data() + 2u), 2u);
ASSERT_EQ(*(rhs.data() + 3u), 3u);
ASSERT_EQ(*(rhs.data() + 4u), 4u);
ASSERT_EQ(*(rhs.data() + 5u), 5u);
}
TEST(SparseSetWithType, RespectUnordered) {
entt::SparseSet<std::uint64_t, int> lhs;
entt::SparseSet<std::uint64_t, int> rhs;
lhs.construct(1, 0);
lhs.construct(2, 0);
lhs.construct(3, 0);
lhs.construct(4, 0);
lhs.construct(5, 0);
ASSERT_EQ(lhs.get(1), 0);
ASSERT_EQ(lhs.get(2), 0);
ASSERT_EQ(lhs.get(3), 0);
ASSERT_EQ(lhs.get(4), 0);
ASSERT_EQ(lhs.get(5), 0);
rhs.construct(3, 0);
rhs.construct(2, 0);
rhs.construct(6, 0);
rhs.construct(1, 0);
rhs.construct(4, 0);
rhs.construct(5, 0);
ASSERT_EQ(rhs.get(3), 0);
ASSERT_EQ(rhs.get(2), 0);
ASSERT_EQ(rhs.get(6), 0);
ASSERT_EQ(rhs.get(1), 0);
ASSERT_EQ(rhs.get(4), 0);
ASSERT_EQ(rhs.get(5), 0);
rhs.respect(lhs);
ASSERT_EQ(*(lhs.data() + 0u), 1u);
ASSERT_EQ(*(lhs.data() + 1u), 2u);
ASSERT_EQ(*(lhs.data() + 2u), 3u);
ASSERT_EQ(*(lhs.data() + 3u), 4u);
ASSERT_EQ(*(lhs.data() + 4u), 5u);
ASSERT_EQ(*(rhs.data() + 0u), 6u);
ASSERT_EQ(*(rhs.data() + 1u), 1u);
ASSERT_EQ(*(rhs.data() + 2u), 2u);
ASSERT_EQ(*(rhs.data() + 3u), 3u);
ASSERT_EQ(*(rhs.data() + 4u), 4u);
ASSERT_EQ(*(rhs.data() + 5u), 5u);
}
TEST(SparseSetWithType, CanModifyDuringIteration) {
entt::SparseSet<std::uint64_t, int> set;
set.construct(0, 42);
ASSERT_EQ(set.capacity(), entt::SparseSet<std::uint64_t>::size_type{1});
const auto it = set.cbegin();
set.reserve(entt::SparseSet<std::uint64_t>::size_type{2});
ASSERT_EQ(set.capacity(), entt::SparseSet<std::uint64_t>::size_type{2});
// this should crash with asan enabled if we break the constraint
const auto entity = *it;
(void)entity;
}
TEST(SparseSetWithType, ReferencesGuaranteed) {
struct InternalType { int value; };
entt::SparseSet<std::uint64_t, InternalType> set;
set.construct(0, 0);
set.construct(1, 1);
ASSERT_EQ(set.get(0).value, 0);
ASSERT_EQ(set.get(1).value, 1);
for(auto &&type: set) {
if(type.value) {
type.value = 42;
}
}
ASSERT_EQ(set.get(0).value, 0);
ASSERT_EQ(set.get(1).value, 42);
auto begin = set.begin();
while(begin != set.end()) {
(begin++)->value = 3;
}
ASSERT_EQ(set.get(0).value, 3);
ASSERT_EQ(set.get(1).value, 3);
}
TEST(SparseSetWithType, MoveOnlyComponent) {
struct MoveOnlyComponent {
MoveOnlyComponent() = default;
~MoveOnlyComponent() = default;
MoveOnlyComponent(const MoveOnlyComponent &) = delete;
MoveOnlyComponent(MoveOnlyComponent &&) = default;
MoveOnlyComponent & operator=(const MoveOnlyComponent &) = delete;
MoveOnlyComponent & operator=(MoveOnlyComponent &&) = default;
};
// it's purpose is to ensure that move only components are always accepted
entt::SparseSet<std::uint64_t, MoveOnlyComponent> set;
(void)set;
}

862
test/entt/entity/view.cpp Normal file
View File

@@ -0,0 +1,862 @@
#include <utility>
#include <iterator>
#include <gtest/gtest.h>
#include <entt/entity/registry.hpp>
#include <entt/entity/view.hpp>
TEST(PersistentView, Prepare) {
entt::Registry<std::uint64_t> registry;
registry.prepare<int, char>();
auto view = registry.view<int, char>(entt::persistent_t{});
const auto &cview = view;
ASSERT_TRUE(view.empty());
const auto e0 = registry.create();
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
ASSERT_FALSE(view.empty());
ASSERT_NO_THROW((registry.view<int, char>(entt::persistent_t{}).begin()++));
ASSERT_NO_THROW((++registry.view<int, char>(entt::persistent_t{}).begin()));
ASSERT_NE(view.begin(), view.end());
ASSERT_NE(cview.begin(), cview.end());
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
registry.assign<int>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{2});
registry.remove<int>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
registry.get<char>(e0) = '1';
registry.get<char>(e1) = '2';
registry.get<int>(e1) = 42;
for(auto entity: view) {
const auto &cview = static_cast<const decltype(view) &>(view);
ASSERT_EQ(std::get<0>(cview.get<int, char>(entity)), 42);
ASSERT_EQ(std::get<1>(view.get<int, char>(entity)), '2');
ASSERT_EQ(cview.get<char>(entity), '2');
}
ASSERT_EQ(*(view.data() + 0), e1);
registry.remove<char>(e0);
registry.remove<char>(e1);
ASSERT_EQ(view.begin(), view.end());
ASSERT_EQ(view.cbegin(), view.cend());
ASSERT_TRUE(view.empty());
}
TEST(PersistentView, NoPrepare) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<int, char>(entt::persistent_t{});
ASSERT_TRUE(view.empty());
const auto e0 = registry.create();
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
ASSERT_FALSE(view.empty());
ASSERT_NO_THROW((registry.view<int, char>(entt::persistent_t{}).begin()++));
ASSERT_NO_THROW((++registry.view<int, char>(entt::persistent_t{}).begin()));
ASSERT_NE(view.begin(), view.end());
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
registry.assign<int>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{2});
registry.remove<int>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
registry.get<char>(e0) = '1';
registry.get<char>(e1) = '2';
registry.get<int>(e1) = 42;
for(auto entity: view) {
const auto &cview = static_cast<const decltype(view) &>(view);
ASSERT_EQ(std::get<0>(cview.get<int, char>(entity)), 42);
ASSERT_EQ(std::get<1>(view.get<int, char>(entity)), '2');
ASSERT_EQ(cview.get<char>(entity), '2');
}
ASSERT_EQ(*(view.data() + 0), e1);
registry.remove<char>(e0);
registry.remove<char>(e1);
ASSERT_EQ(view.begin(), view.end());
ASSERT_EQ(view.cbegin(), view.cend());
ASSERT_TRUE(view.empty());
}
TEST(PersistentView, ElementAccess) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<int, char>(entt::persistent_t{});
const auto &cview = view;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
for(typename decltype(view)::size_type i{}; i < view.size(); ++i) {
ASSERT_EQ(view[i], i ? e0 : e1);
ASSERT_EQ(cview[i], i ? e0 : e1);
}
}
TEST(PersistentView, Contains) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
registry.destroy(e0);
auto view = registry.view<int, char>(entt::persistent_t{});
ASSERT_FALSE(view.contains(e0));
ASSERT_TRUE(view.contains(e1));
}
TEST(PersistentView, Empty) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<double>(e0);
registry.assign<int>(e0);
registry.assign<float>(e0);
const auto e1 = registry.create();
registry.assign<char>(e1);
registry.assign<float>(e1);
for(auto entity: registry.view<char, int, float>(entt::persistent_t{})) {
(void)entity;
FAIL();
}
for(auto entity: registry.view<double, char, int, float>(entt::persistent_t{})) {
(void)entity;
FAIL();
}
}
TEST(PersistentView, Each) {
entt::Registry<std::uint64_t> registry;
registry.prepare<int, char>();
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
auto view = registry.view<int, char>(entt::persistent_t{});
const auto &cview = static_cast<const decltype(view) &>(view);
std::size_t cnt = 0;
view.each([&cnt](auto, int &, char &) { ++cnt; });
ASSERT_EQ(cnt, std::size_t{2});
cview.each([&cnt](auto, const int &, const char &) { --cnt; });
ASSERT_EQ(cnt, std::size_t{0});
}
TEST(PersistentView, Sort) {
entt::Registry<std::uint64_t> registry;
registry.prepare<int, unsigned int>();
const auto e0 = registry.create();
const auto e1 = registry.create();
const auto e2 = registry.create();
auto uval = 0u;
auto ival = 0;
registry.assign<unsigned int>(e0, uval++);
registry.assign<unsigned int>(e1, uval++);
registry.assign<unsigned int>(e2, uval++);
registry.assign<int>(e0, ival++);
registry.assign<int>(e1, ival++);
registry.assign<int>(e2, ival++);
auto view = registry.view<int, unsigned int>(entt::persistent_t{});
for(auto entity: view) {
ASSERT_EQ(view.get<unsigned int>(entity), --uval);
ASSERT_EQ(view.get<int>(entity), --ival);
}
registry.sort<unsigned int>(std::less<unsigned int>{});
view.sort<unsigned int>();
for(auto entity: view) {
ASSERT_EQ(view.get<unsigned int>(entity), uval++);
ASSERT_EQ(view.get<int>(entity), ival++);
}
}
TEST(SingleComponentView, Functionalities) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<char>();
const auto &cview = view;
const auto e0 = registry.create();
const auto e1 = registry.create();
ASSERT_TRUE(view.empty());
registry.assign<int>(e1);
registry.assign<char>(e1);
ASSERT_NO_THROW(registry.view<char>().begin()++);
ASSERT_NO_THROW(++registry.view<char>().begin());
ASSERT_NE(view.begin(), view.end());
ASSERT_NE(cview.begin(), cview.end());
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
ASSERT_FALSE(view.empty());
registry.assign<char>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{2});
view.get(e0) = '1';
view.get(e1) = '2';
for(auto entity: view) {
const auto &cview = static_cast<const decltype(view) &>(view);
ASSERT_TRUE(cview.get(entity) == '1' || cview.get(entity) == '2');
}
ASSERT_EQ(*(view.data() + 0), e1);
ASSERT_EQ(*(view.data() + 1), e0);
ASSERT_EQ(*(view.raw() + 0), '2');
ASSERT_EQ(*(static_cast<const decltype(view) &>(view).raw() + 1), '1');
registry.remove<char>(e0);
registry.remove<char>(e1);
ASSERT_EQ(view.begin(), view.end());
ASSERT_EQ(view.cbegin(), view.cend());
ASSERT_TRUE(view.empty());
}
TEST(SingleComponentView, ElementAccess) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<int>();
const auto &cview = view;
const auto e0 = registry.create();
registry.assign<int>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
for(typename decltype(view)::size_type i{}; i < view.size(); ++i) {
ASSERT_EQ(view[i], i ? e0 : e1);
ASSERT_EQ(cview[i], i ? e0 : e1);
}
}
TEST(SingleComponentView, Contains) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<int>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.destroy(e0);
auto view = registry.view<int>();
ASSERT_FALSE(view.contains(e0));
ASSERT_TRUE(view.contains(e1));
}
TEST(SingleComponentView, Empty) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<char>(e0);
registry.assign<double>(e0);
const auto e1 = registry.create();
registry.assign<char>(e1);
auto view = registry.view<int>();
ASSERT_EQ(view.size(), entt::Registry<std::uint64_t>::size_type{0});
for(auto entity: view) {
(void)entity;
FAIL();
}
}
TEST(SingleComponentView, Each) {
entt::Registry<std::uint64_t> registry;
registry.assign<int>(registry.create());
registry.assign<int>(registry.create());
auto view = registry.view<int>();
const auto &cview = static_cast<const decltype(view) &>(view);
std::size_t cnt = 0;
view.each([&cnt](auto, int &) { ++cnt; });
ASSERT_EQ(cnt, std::size_t{2});
cview.each([&cnt](auto, const int &) { --cnt; });
ASSERT_EQ(cnt, std::size_t{0});
}
TEST(MultipleComponentView, Functionalities) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<int, char>();
const auto &cview = view;
ASSERT_TRUE(view.empty());
const auto e0 = registry.create();
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
ASSERT_FALSE(view.empty());
registry.assign<char>(e1);
auto it = registry.view<int, char>().begin();
ASSERT_EQ(*it, e1);
ASSERT_EQ(++it, (registry.view<int, char>().end()));
ASSERT_NO_THROW((registry.view<int, char>().begin()++));
ASSERT_NO_THROW((++registry.view<int, char>().begin()));
ASSERT_NE(view.begin(), view.end());
ASSERT_NE(cview.begin(), cview.end());
ASSERT_EQ(view.size(), decltype(view.size()){1});
registry.get<char>(e0) = '1';
registry.get<char>(e1) = '2';
registry.get<int>(e1) = 42;
for(auto entity: view) {
const auto &cview = static_cast<const decltype(view) &>(view);
ASSERT_EQ(std::get<0>(cview.get<int, char>(entity)), 42);
ASSERT_EQ(std::get<1>(view.get<int, char>(entity)), '2');
ASSERT_EQ(cview.get<char>(entity), '2');
}
}
TEST(MultipleComponentView, Iterator) {
entt::Registry<std::uint64_t> registry;
const auto entity = registry.create();
registry.assign<int>(entity);
registry.assign<char>(entity);
const auto view = registry.view<int, char>();
using iterator_type = typename decltype(view)::iterator_type;
iterator_type end{view.begin()};
iterator_type begin{};
begin = view.end();
std::swap(begin, end);
ASSERT_EQ(begin, view.begin());
ASSERT_EQ(end, view.end());
ASSERT_NE(begin, end);
ASSERT_EQ(view.begin()++, view.begin());
ASSERT_EQ(++view.begin(), view.end());
}
TEST(MultipleComponentView, ConstIterator) {
entt::Registry<std::uint64_t> registry;
const auto entity = registry.create();
registry.assign<int>(entity);
registry.assign<char>(entity);
const auto view = registry.view<int, char>();
using iterator_type = typename decltype(view)::iterator_type;
iterator_type cend{view.cbegin()};
iterator_type cbegin{};
cbegin = view.cend();
std::swap(cbegin, cend);
ASSERT_EQ(cbegin, view.cbegin());
ASSERT_EQ(cend, view.cend());
ASSERT_NE(cbegin, cend);
ASSERT_EQ(view.cbegin()++, view.cbegin());
ASSERT_EQ(++view.cbegin(), view.cend());
}
TEST(MultipleComponentView, Contains) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
registry.destroy(e0);
auto view = registry.view<int, char>();
ASSERT_FALSE(view.contains(e0));
ASSERT_TRUE(view.contains(e1));
}
TEST(MultipleComponentView, Empty) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<double>(e0);
registry.assign<int>(e0);
registry.assign<float>(e0);
const auto e1 = registry.create();
registry.assign<char>(e1);
registry.assign<float>(e1);
auto view = registry.view<char, int, float>();
for(auto entity: view) {
(void)entity;
FAIL();
}
}
TEST(MultipleComponentView, Each) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
auto view = registry.view<int, char>();
const auto &cview = static_cast<const decltype(view) &>(view);
std::size_t cnt = 0;
view.each([&cnt](auto, int &, char &) { ++cnt; });
ASSERT_EQ(cnt, std::size_t{2});
cview.each([&cnt](auto, const int &, const char &) { --cnt; });
ASSERT_EQ(cnt, std::size_t{0});
}
TEST(MultipleComponentView, EachWithHoles) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
const auto e1 = registry.create();
const auto e2 = registry.create();
registry.assign<char>(e0, '0');
registry.assign<char>(e1, '1');
registry.assign<int>(e0, 0);
registry.assign<int>(e2, 2);
auto view = registry.view<char, int>();
view.each([e0](auto entity, const char &c, const int &i) {
if(e0 == entity) {
ASSERT_EQ(c, '0');
ASSERT_EQ(i, 0);
} else {
FAIL();
}
});
}
TEST(RawView, Functionalities) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<char>(entt::raw_t{});
const auto &cview = view;
ASSERT_TRUE(view.empty());
const auto e0 = registry.create();
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
ASSERT_FALSE(view.empty());
ASSERT_NO_THROW(registry.view<char>(entt::raw_t{}).begin()++);
ASSERT_NO_THROW(++registry.view<char>(entt::raw_t{}).begin());
ASSERT_NE(view.begin(), view.end());
ASSERT_NE(cview.begin(), cview.end());
ASSERT_EQ(view.size(), typename decltype(view)::size_type{1});
registry.assign<char>(e0);
ASSERT_EQ(view.size(), typename decltype(view)::size_type{2});
registry.get<char>(e0) = '1';
registry.get<char>(e1) = '2';
for(auto &&component: view) {
ASSERT_TRUE(component == '1' || component == '2');
}
ASSERT_EQ(*(view.data() + 0), e1);
ASSERT_EQ(*(view.data() + 1), e0);
ASSERT_EQ(*(view.raw() + 0), '2');
ASSERT_EQ(*(static_cast<const decltype(view) &>(view).raw() + 1), '1');
for(auto &&component: view) {
// verifies that iterators return references to components
component = '0';
}
for(auto &&component: view) {
ASSERT_TRUE(component == '0');
}
registry.remove<char>(e0);
registry.remove<char>(e1);
ASSERT_EQ(view.begin(), view.end());
ASSERT_EQ(view.cbegin(), view.cend());
ASSERT_TRUE(view.empty());
}
TEST(RawView, ElementAccess) {
entt::Registry<std::uint64_t> registry;
auto view = registry.view<int>(entt::raw_t{});
const auto &cview = view;
const auto e0 = registry.create();
registry.assign<int>(e0, 42);
const auto e1 = registry.create();
registry.assign<int>(e1, 3);
for(typename decltype(view)::size_type i{}; i < view.size(); ++i) {
ASSERT_EQ(view[i], i ? 42 : 3);
ASSERT_EQ(cview[i], i ? 42 : 3);
}
}
TEST(RawView, Empty) {
entt::Registry<std::uint64_t> registry;
const auto e0 = registry.create();
registry.assign<char>(e0);
registry.assign<double>(e0);
const auto e1 = registry.create();
registry.assign<char>(e1);
auto view = registry.view<int>(entt::raw_t{});
ASSERT_EQ(view.size(), entt::Registry<std::uint64_t>::size_type{0});
for(auto &&component: view) {
(void)component;
FAIL();
}
}
TEST(RawView, Each) {
entt::Registry<std::uint64_t> registry;
registry.assign<int>(registry.create(), 1);
registry.assign<int>(registry.create(), 3);
auto view = registry.view<int>(entt::raw_t{});
const auto &cview = static_cast<const decltype(view) &>(view);
std::size_t cnt = 0;
view.each([&cnt](int &v) { cnt += (v % 2); });
ASSERT_EQ(cnt, std::size_t{2});
cview.each([&cnt](const int &v) { cnt -= (v % 2); });
ASSERT_EQ(cnt, std::size_t{0});
}
TEST(RuntimeView, Functionalities) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
// forces the creation of the pools
registry.reserve<int>(0);
registry.reserve<char>(0);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
const auto &cview = view;
ASSERT_TRUE(view.empty());
const auto e0 = registry.create();
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
ASSERT_FALSE(view.empty());
registry.assign<char>(e1);
auto it = registry.view(std::begin(types), std::end(types)).begin();
ASSERT_EQ(*it, e1);
ASSERT_EQ(++it, (registry.view(std::begin(types), std::end(types)).end()));
ASSERT_NO_THROW((registry.view(std::begin(types), std::end(types)).begin()++));
ASSERT_NO_THROW((++registry.view(std::begin(types), std::end(types)).begin()));
ASSERT_NE(view.begin(), view.end());
ASSERT_NE(cview.begin(), cview.end());
ASSERT_EQ(view.size(), decltype(view.size()){1});
registry.get<char>(e0) = '1';
registry.get<char>(e1) = '2';
registry.get<int>(e1) = 42;
for(auto entity: view) {
ASSERT_EQ(registry.get<int>(entity), 42);
ASSERT_EQ(registry.get<char>(entity), '2');
}
}
TEST(RuntimeView, Iterator) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto entity = registry.create();
registry.assign<int>(entity);
registry.assign<char>(entity);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
using iterator_type = typename decltype(view)::iterator_type;
iterator_type end{view.begin()};
iterator_type begin{};
begin = view.end();
std::swap(begin, end);
ASSERT_EQ(begin, view.begin());
ASSERT_EQ(end, view.end());
ASSERT_NE(begin, end);
ASSERT_EQ(view.begin()++, view.begin());
ASSERT_EQ(++view.begin(), view.end());
}
TEST(RuntimeView, ConstIterator) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto entity = registry.create();
registry.assign<int>(entity);
registry.assign<char>(entity);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
using iterator_type = typename decltype(view)::iterator_type;
iterator_type cend{view.cbegin()};
iterator_type cbegin{};
cbegin = view.cend();
std::swap(cbegin, cend);
ASSERT_EQ(cbegin, view.cbegin());
ASSERT_EQ(cend, view.cend());
ASSERT_NE(cbegin, cend);
ASSERT_EQ(view.cbegin()++, view.cbegin());
ASSERT_EQ(++view.cbegin(), view.cend());
}
TEST(RuntimeView, Contains) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
registry.destroy(e0);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
ASSERT_FALSE(view.contains(e0));
ASSERT_TRUE(view.contains(e1));
}
TEST(RuntimeView, Empty) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
registry.assign<double>(e0);
registry.assign<int>(e0);
registry.assign<float>(e0);
const auto e1 = registry.create();
registry.assign<char>(e1);
registry.assign<float>(e1);
component_type types[] = { registry.type<char>(), registry.type<int>(), registry.type<float>() };
auto view = registry.view(std::begin(types), std::end(types));
for(auto entity: view) {
(void)entity;
FAIL();
}
}
TEST(RuntimeView, Each) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
registry.assign<int>(e0);
registry.assign<char>(e0);
const auto e1 = registry.create();
registry.assign<int>(e1);
registry.assign<char>(e1);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
std::size_t cnt = 0;
view.each([&cnt](auto) { ++cnt; });
ASSERT_EQ(cnt, std::size_t{2});
}
TEST(RuntimeView, EachWithHoles) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
const auto e1 = registry.create();
const auto e2 = registry.create();
registry.assign<char>(e0, '0');
registry.assign<char>(e1, '1');
registry.assign<int>(e0, 0);
registry.assign<int>(e2, 2);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
view.each([e0](auto entity) {
ASSERT_EQ(e0, entity);
});
}
TEST(RuntimeView, MissingPool) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
registry.assign<int>(e0);
component_type types[] = { registry.type<int>(), registry.type<char>() };
auto view = registry.view(std::begin(types), std::end(types));
ASSERT_TRUE(view.empty());
ASSERT_EQ(view.size(), decltype(view.size()){0});
registry.assign<char>(e0);
ASSERT_TRUE(view.empty());
ASSERT_EQ(view.size(), decltype(view.size()){0});
ASSERT_FALSE(view.contains(e0));
view.each([](auto) { FAIL(); });
for(auto entity: view) {
(void)entity;
FAIL();
}
}
TEST(RuntimeView, EmptyRange) {
entt::Registry<std::uint64_t> registry;
using component_type = typename decltype(registry)::component_type;
const auto e0 = registry.create();
registry.assign<int>(e0);
const component_type *ptr = nullptr;
auto view = registry.view(ptr, ptr);
ASSERT_TRUE(view.empty());
ASSERT_EQ(view.size(), decltype(view.size()){0});
ASSERT_FALSE(view.contains(e0));
view.each([](auto) { FAIL(); });
for(auto entity: view) {
(void)entity;
FAIL();
}
}

View File

@@ -0,0 +1,50 @@
#include <gtest/gtest.h>
#include <entt/locator/locator.hpp>
struct AService {};
struct AnotherService {
virtual ~AnotherService() = default;
virtual void f(bool) = 0;
bool check{false};
};
struct DerivedService: AnotherService {
DerivedService(int): AnotherService{} {}
void f(bool b) override { check = b; }
};
TEST(ServiceLocator, Functionalities) {
using entt::ServiceLocator;
ASSERT_TRUE(ServiceLocator<AService>::empty());
ASSERT_TRUE(ServiceLocator<AnotherService>::empty());
ServiceLocator<AService>::set();
ASSERT_FALSE(ServiceLocator<AService>::empty());
ASSERT_TRUE(ServiceLocator<AnotherService>::empty());
ServiceLocator<AService>::reset();
ASSERT_TRUE(ServiceLocator<AService>::empty());
ASSERT_TRUE(ServiceLocator<AnotherService>::empty());
ServiceLocator<AService>::set(std::make_shared<AService>());
ASSERT_FALSE(ServiceLocator<AService>::empty());
ASSERT_TRUE(ServiceLocator<AnotherService>::empty());
ServiceLocator<AnotherService>::set<DerivedService>(42);
ASSERT_FALSE(ServiceLocator<AService>::empty());
ASSERT_FALSE(ServiceLocator<AnotherService>::empty());
ServiceLocator<AnotherService>::get().lock()->f(!ServiceLocator<AnotherService>::get().lock()->check);
ASSERT_TRUE(ServiceLocator<AnotherService>::get().lock()->check);
ServiceLocator<AnotherService>::ref().f(!ServiceLocator<AnotherService>::get().lock()->check);
ASSERT_FALSE(ServiceLocator<AnotherService>::get().lock()->check);
}

View File

@@ -0,0 +1,206 @@
#include <gtest/gtest.h>
#include <cstdint>
#include <entt/process/process.hpp>
struct FakeProcess: entt::Process<FakeProcess, int> {
using process_type = entt::Process<FakeProcess, int>;
void succeed() noexcept { process_type::succeed(); }
void fail() noexcept { process_type::fail(); }
void pause() noexcept { process_type::pause(); }
void unpause() noexcept { process_type::unpause(); }
void init(void *) { initInvoked = true; }
void succeeded() { succeededInvoked = true; }
void failed() { failedInvoked = true; }
void aborted() { abortedInvoked = true; }
void update(delta_type, void *data) {
if(data) {
(*static_cast<int *>(data))++;
}
updateInvoked = true;
}
bool initInvoked{false};
bool updateInvoked{false};
bool succeededInvoked{false};
bool failedInvoked{false};
bool abortedInvoked{false};
};
TEST(Process, Basics) {
FakeProcess process;
ASSERT_FALSE(process.alive());
ASSERT_FALSE(process.dead());
ASSERT_FALSE(process.paused());
process.succeed();
process.fail();
process.abort();
process.pause();
process.unpause();
ASSERT_FALSE(process.alive());
ASSERT_FALSE(process.dead());
ASSERT_FALSE(process.paused());
process.tick(0);
ASSERT_TRUE(process.alive());
ASSERT_FALSE(process.dead());
ASSERT_FALSE(process.paused());
process.pause();
ASSERT_TRUE(process.alive());
ASSERT_FALSE(process.dead());
ASSERT_TRUE(process.paused());
process.unpause();
ASSERT_TRUE(process.alive());
ASSERT_FALSE(process.dead());
ASSERT_FALSE(process.paused());
}
TEST(Process, Succeeded) {
FakeProcess process;
process.tick(0);
process.succeed();
process.tick(0);
ASSERT_FALSE(process.alive());
ASSERT_TRUE(process.dead());
ASSERT_FALSE(process.paused());
ASSERT_TRUE(process.initInvoked);
ASSERT_TRUE(process.updateInvoked);
ASSERT_TRUE(process.succeededInvoked);
ASSERT_FALSE(process.failedInvoked);
ASSERT_FALSE(process.abortedInvoked);
}
TEST(Process, Fail) {
FakeProcess process;
process.tick(0);
process.fail();
process.tick(0);
ASSERT_FALSE(process.alive());
ASSERT_TRUE(process.dead());
ASSERT_FALSE(process.paused());
ASSERT_TRUE(process.initInvoked);
ASSERT_TRUE(process.updateInvoked);
ASSERT_FALSE(process.succeededInvoked);
ASSERT_TRUE(process.failedInvoked);
ASSERT_FALSE(process.abortedInvoked);
}
TEST(Process, Data) {
FakeProcess process;
int value = 0;
process.tick(0, &value);
process.succeed();
process.tick(0, &value);
ASSERT_FALSE(process.alive());
ASSERT_TRUE(process.dead());
ASSERT_FALSE(process.paused());
ASSERT_EQ(value, 1);
ASSERT_TRUE(process.initInvoked);
ASSERT_TRUE(process.updateInvoked);
ASSERT_TRUE(process.succeededInvoked);
ASSERT_FALSE(process.failedInvoked);
ASSERT_FALSE(process.abortedInvoked);
}
TEST(Process, AbortNextTick) {
FakeProcess process;
process.tick(0);
process.abort();
process.tick(0);
ASSERT_FALSE(process.alive());
ASSERT_TRUE(process.dead());
ASSERT_FALSE(process.paused());
ASSERT_TRUE(process.initInvoked);
ASSERT_TRUE(process.updateInvoked);
ASSERT_FALSE(process.succeededInvoked);
ASSERT_FALSE(process.failedInvoked);
ASSERT_TRUE(process.abortedInvoked);
}
TEST(Process, AbortImmediately) {
FakeProcess process;
process.tick(0);
process.abort(true);
ASSERT_FALSE(process.alive());
ASSERT_TRUE(process.dead());
ASSERT_FALSE(process.paused());
ASSERT_TRUE(process.initInvoked);
ASSERT_TRUE(process.updateInvoked);
ASSERT_FALSE(process.succeededInvoked);
ASSERT_FALSE(process.failedInvoked);
ASSERT_TRUE(process.abortedInvoked);
}
TEST(ProcessAdaptor, Resolved) {
bool updated = false;
auto lambda = [&updated](std::uint64_t, void *, auto resolve, auto) {
ASSERT_FALSE(updated);
updated = true;
resolve();
};
auto process = entt::ProcessAdaptor<decltype(lambda), std::uint64_t>{lambda};
process.tick(0);
ASSERT_TRUE(process.dead());
ASSERT_TRUE(updated);
}
TEST(ProcessAdaptor, Rejected) {
bool updated = false;
auto lambda = [&updated](std::uint64_t, void *, auto, auto rejected) {
ASSERT_FALSE(updated);
updated = true;
rejected();
};
auto process = entt::ProcessAdaptor<decltype(lambda), std::uint64_t>{lambda};
process.tick(0);
ASSERT_TRUE(process.rejected());
ASSERT_TRUE(updated);
}
TEST(ProcessAdaptor, Data) {
int value = 0;
auto lambda = [](std::uint64_t, void *data, auto resolve, auto) {
*static_cast<int *>(data) = 42;
resolve();
};
auto process = entt::ProcessAdaptor<decltype(lambda), std::uint64_t>{lambda};
process.tick(0, &value);
ASSERT_TRUE(process.dead());
ASSERT_EQ(value, 42);
}

View File

@@ -0,0 +1,113 @@
#include <functional>
#include <gtest/gtest.h>
#include <entt/process/scheduler.hpp>
#include <entt/process/process.hpp>
struct FooProcess: entt::Process<FooProcess, int> {
FooProcess(std::function<void()> onUpdate, std::function<void()> onAborted)
: onUpdate{onUpdate}, onAborted{onAborted}
{}
void update(delta_type, void *) { onUpdate(); }
void aborted() { onAborted(); }
std::function<void()> onUpdate;
std::function<void()> onAborted;
};
struct SucceededProcess: entt::Process<SucceededProcess, int> {
void update(delta_type, void *) {
ASSERT_FALSE(updated);
updated = true;
++invoked;
succeed();
}
static unsigned int invoked;
bool updated = false;
};
unsigned int SucceededProcess::invoked = 0;
struct FailedProcess: entt::Process<FailedProcess, int> {
void update(delta_type, void *) {
ASSERT_FALSE(updated);
updated = true;
fail();
}
bool updated = false;
};
TEST(Scheduler, Functionalities) {
entt::Scheduler<int> scheduler{};
bool updated = false;
bool aborted = false;
ASSERT_EQ(scheduler.size(), entt::Scheduler<int>::size_type{});
ASSERT_TRUE(scheduler.empty());
scheduler.attach<FooProcess>(
[&updated](){ updated = true; },
[&aborted](){ aborted = true; }
);
ASSERT_NE(scheduler.size(), entt::Scheduler<int>::size_type{});
ASSERT_FALSE(scheduler.empty());
scheduler.update(0);
scheduler.abort(true);
ASSERT_TRUE(updated);
ASSERT_TRUE(aborted);
ASSERT_NE(scheduler.size(), entt::Scheduler<int>::size_type{});
ASSERT_FALSE(scheduler.empty());
scheduler.clear();
ASSERT_EQ(scheduler.size(), entt::Scheduler<int>::size_type{});
ASSERT_TRUE(scheduler.empty());
}
TEST(Scheduler, Then) {
entt::Scheduler<int> scheduler;
scheduler.attach<SucceededProcess>()
.then<SucceededProcess>()
.then<FailedProcess>()
.then<SucceededProcess>();
for(auto i = 0; i < 8; ++i) {
scheduler.update(0);
}
ASSERT_EQ(SucceededProcess::invoked, 2u);
}
TEST(Scheduler, Functor) {
entt::Scheduler<int> scheduler;
bool firstFunctor = false;
bool secondFunctor = false;
scheduler.attach([&firstFunctor](auto, void *, auto resolve, auto){
ASSERT_FALSE(firstFunctor);
firstFunctor = true;
resolve();
}).then([&secondFunctor](auto, void *, auto, auto reject){
ASSERT_FALSE(secondFunctor);
secondFunctor = true;
reject();
}).then([](auto...){
FAIL();
});
for(auto i = 0; i < 8; ++i) {
scheduler.update(0);
}
ASSERT_TRUE(firstFunctor);
ASSERT_TRUE(secondFunctor);
}

View File

@@ -0,0 +1,85 @@
#include <gtest/gtest.h>
#include <entt/resource/cache.hpp>
struct Resource { const int value; };
struct Loader: entt::ResourceLoader<Loader, Resource> {
std::shared_ptr<Resource> load(int value) const {
return std::shared_ptr<Resource>(new Resource{ value });
}
};
struct BrokenLoader: entt::ResourceLoader<BrokenLoader, Resource> {
std::shared_ptr<Resource> load(int) const {
return nullptr;
}
};
TEST(ResourceCache, Functionalities) {
entt::ResourceCache<Resource> cache;
constexpr auto hs1 = entt::HashedString{"res1"};
constexpr auto hs2 = entt::HashedString{"res2"};
ASSERT_EQ(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_TRUE(cache.empty());
ASSERT_FALSE(cache.contains(hs1));
ASSERT_FALSE(cache.contains(hs2));
ASSERT_FALSE(cache.load<BrokenLoader>(hs1, 42));
ASSERT_FALSE(cache.reload<BrokenLoader>(hs1, 42));
ASSERT_EQ(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_TRUE(cache.empty());
ASSERT_FALSE(cache.contains(hs1));
ASSERT_FALSE(cache.contains(hs2));
ASSERT_TRUE(cache.load<Loader>(hs1, 42));
ASSERT_TRUE(cache.reload<Loader>(hs1, 42));
ASSERT_NE(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_FALSE(cache.empty());
ASSERT_TRUE(cache.contains(hs1));
ASSERT_FALSE(cache.contains(hs2));
ASSERT_EQ((*cache.handle(hs1)).value, 42);
ASSERT_TRUE(cache.load<Loader>(hs2, 42));
ASSERT_NE(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_FALSE(cache.empty());
ASSERT_TRUE(cache.contains(hs1));
ASSERT_TRUE(cache.contains(hs2));
ASSERT_EQ((*cache.handle(hs1)).value, 42);
ASSERT_EQ(cache.handle(hs2)->value, 42);
ASSERT_NO_THROW(cache.discard(hs1));
ASSERT_FALSE(cache.contains(hs1));
ASSERT_TRUE(cache.contains(hs2));
ASSERT_EQ(cache.handle(hs2)->value, 42);
ASSERT_TRUE(cache.load<Loader>(hs1, 42));
ASSERT_NO_THROW(cache.clear());
ASSERT_EQ(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_TRUE(cache.empty());
ASSERT_FALSE(cache.contains(hs1));
ASSERT_FALSE(cache.contains(hs2));
ASSERT_TRUE(cache.load<Loader>(hs1, 42));
ASSERT_NE(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_FALSE(cache.empty());
ASSERT_TRUE(cache.handle(hs1));
ASSERT_FALSE(cache.handle(hs2));
ASSERT_TRUE(cache.handle(hs1));
ASSERT_EQ(&cache.handle(hs1).get(), &static_cast<const Resource &>(cache.handle(hs1)));
ASSERT_NO_THROW(cache.clear());
ASSERT_EQ(cache.size(), entt::ResourceCache<Resource>::size_type{});
ASSERT_TRUE(cache.empty());
ASSERT_TRUE(cache.temp<Loader>(42));
ASSERT_TRUE(cache.empty());
}

View File

@@ -0,0 +1,48 @@
#include <gtest/gtest.h>
#include <entt/signal/delegate.hpp>
int delegateFunction(int i) {
return i*i;
}
struct DelegateFunctor {
int operator()(int i) {
return i+i;
}
};
TEST(Delegate, Functionalities) {
entt::Delegate<int(int)> ffdel;
entt::Delegate<int(int)> mfdel;
DelegateFunctor functor;
ASSERT_TRUE(ffdel.empty());
ASSERT_TRUE(mfdel.empty());
ffdel.connect<&delegateFunction>();
mfdel.connect<DelegateFunctor, &DelegateFunctor::operator()>(&functor);
ASSERT_FALSE(ffdel.empty());
ASSERT_FALSE(mfdel.empty());
ASSERT_EQ(ffdel(3), 9);
ASSERT_EQ(mfdel(3), 6);
ffdel.reset();
mfdel.reset();
ASSERT_TRUE(ffdel.empty());
ASSERT_TRUE(mfdel.empty());
}
TEST(Delegate, Comparison) {
entt::Delegate<int(int)> delegate;
entt::Delegate<int(int)> def;
delegate.connect<&delegateFunction>();
ASSERT_EQ(def, entt::Delegate<int(int)>{});
ASSERT_NE(def, delegate);
ASSERT_TRUE(def == entt::Delegate<int(int)>{});
ASSERT_TRUE (def != delegate);
}

View File

@@ -0,0 +1,40 @@
#include <memory>
#include <gtest/gtest.h>
#include <entt/signal/dispatcher.hpp>
struct AnEvent {};
struct AnotherEvent {};
struct Receiver {
void receive(const AnEvent &) { ++cnt; }
void reset() { cnt = 0; }
int cnt{0};
};
TEST(Dispatcher, Functionalities) {
entt::Dispatcher dispatcher;
Receiver receiver;
dispatcher.template sink<AnEvent>().connect(&receiver);
dispatcher.template trigger<AnEvent>();
dispatcher.template enqueue<AnEvent>();
dispatcher.template enqueue<AnotherEvent>();
dispatcher.update<AnotherEvent>();
ASSERT_EQ(receiver.cnt, 1);
dispatcher.update<AnEvent>();
dispatcher.template trigger<AnEvent>();
ASSERT_EQ(receiver.cnt, 3);
receiver.reset();
dispatcher.template sink<AnEvent>().disconnect(&receiver);
dispatcher.template trigger<AnEvent>();
dispatcher.template enqueue<AnEvent>();
dispatcher.update();
dispatcher.template trigger<AnEvent>();
ASSERT_EQ(receiver.cnt, 0);
}

View File

@@ -0,0 +1,117 @@
#include <gtest/gtest.h>
#include <entt/signal/emitter.hpp>
struct TestEmitter: entt::Emitter<TestEmitter> {};
struct FooEvent { int i; char c; };
struct BarEvent {};
TEST(Emitter, Clear) {
TestEmitter emitter;
ASSERT_TRUE(emitter.empty());
emitter.on<FooEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
ASSERT_TRUE(emitter.empty<BarEvent>());
emitter.clear<BarEvent>();
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
ASSERT_TRUE(emitter.empty<BarEvent>());
emitter.clear<FooEvent>();
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(emitter.empty<FooEvent>());
ASSERT_TRUE(emitter.empty<BarEvent>());
emitter.on<FooEvent>([](const auto &, const auto &){});
emitter.on<BarEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
ASSERT_FALSE(emitter.empty<BarEvent>());
emitter.clear();
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(emitter.empty<FooEvent>());
ASSERT_TRUE(emitter.empty<BarEvent>());
}
TEST(Emitter, ClearPublishing) {
TestEmitter emitter;
bool invoked = false;
ASSERT_TRUE(emitter.empty());
emitter.on<BarEvent>([&invoked](const auto &, auto &em){
invoked = true;
em.clear();
});
emitter.publish<BarEvent>();
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(invoked);
}
TEST(Emitter, On) {
TestEmitter emitter;
emitter.on<FooEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
emitter.publish<FooEvent>(0, 'c');
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
}
TEST(Emitter, Once) {
TestEmitter emitter;
emitter.once<BarEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<BarEvent>());
emitter.publish<BarEvent>();
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(emitter.empty<BarEvent>());
}
TEST(Emitter, OnceAndErase) {
TestEmitter emitter;
auto conn = emitter.once<FooEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<FooEvent>());
emitter.erase(conn);
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(emitter.empty<FooEvent>());
}
TEST(Emitter, OnAndErase) {
TestEmitter emitter;
auto conn = emitter.on<BarEvent>([](const auto &, const auto &){});
ASSERT_FALSE(emitter.empty());
ASSERT_FALSE(emitter.empty<BarEvent>());
emitter.erase(conn);
ASSERT_TRUE(emitter.empty());
ASSERT_TRUE(emitter.empty<BarEvent>());
}

222
test/entt/signal/sigh.cpp Normal file
View File

@@ -0,0 +1,222 @@
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include <entt/signal/sigh.hpp>
struct SigHListener {
static void f(int &v) { v = 42; }
bool g(int) { k = !k; return true; }
bool h(int) { return k; }
void i() {}
void l() {}
bool k{false};
};
template<typename Ret>
struct TestCollectAll {
std::vector<Ret> vec{};
static int f() { return 42; }
static int g() { return 42; }
bool operator()(Ret r) noexcept {
vec.push_back(r);
return true;
}
};
template<>
struct TestCollectAll<void> {
std::vector<int> vec{};
static void h() {}
bool operator()() noexcept {
return true;
}
};
template<typename Ret>
struct TestCollectFirst {
std::vector<Ret> vec{};
static int f() { return 42; }
bool operator()(Ret r) noexcept {
vec.push_back(r);
return false;
}
};
TEST(SigH, Lifetime) {
using signal = entt::SigH<void(void)>;
ASSERT_NO_THROW(signal{});
signal src{}, other{};
ASSERT_NO_THROW(signal{src});
ASSERT_NO_THROW(signal{std::move(other)});
ASSERT_NO_THROW(src = other);
ASSERT_NO_THROW(src = std::move(other));
ASSERT_NO_THROW(delete new signal{});
}
TEST(SigH, Comparison) {
entt::SigH<void()> sig1;
entt::SigH<void()> sig2;
SigHListener s1;
SigHListener s2;
sig1.sink().connect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::i>(&s2);
ASSERT_FALSE(sig1 == sig2);
ASSERT_TRUE(sig1 != sig2);
sig1.sink().disconnect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().disconnect<SigHListener, &SigHListener::i>(&s2);
sig1.sink().connect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::l>(&s1);
ASSERT_FALSE(sig1 == sig2);
ASSERT_TRUE(sig1 != sig2);
sig1.sink().disconnect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().disconnect<SigHListener, &SigHListener::l>(&s1);
ASSERT_TRUE(sig1 == sig2);
ASSERT_FALSE(sig1 != sig2);
sig1.sink().connect<SigHListener, &SigHListener::i>(&s1);
sig1.sink().connect<SigHListener, &SigHListener::l>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::l>(&s1);
ASSERT_TRUE(sig1 == sig2);
sig1.sink().disconnect<SigHListener, &SigHListener::i>(&s1);
sig1.sink().disconnect<SigHListener, &SigHListener::l>(&s1);
sig2.sink().disconnect<SigHListener, &SigHListener::i>(&s1);
sig2.sink().disconnect<SigHListener, &SigHListener::l>(&s1);
sig1.sink().connect<SigHListener, &SigHListener::i>(&s1);
sig1.sink().connect<SigHListener, &SigHListener::l>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::l>(&s1);
sig2.sink().connect<SigHListener, &SigHListener::i>(&s1);
ASSERT_FALSE(sig1 == sig2);
}
TEST(SigH, Clear) {
entt::SigH<void(int &)> sigh;
sigh.sink().connect<&SigHListener::f>();
ASSERT_FALSE(sigh.empty());
sigh.sink().disconnect();
ASSERT_TRUE(sigh.empty());
}
TEST(SigH, Swap) {
entt::SigH<void(int &)> sigh1;
entt::SigH<void(int &)> sigh2;
sigh1.sink().connect<&SigHListener::f>();
ASSERT_FALSE(sigh1.empty());
ASSERT_TRUE(sigh2.empty());
std::swap(sigh1, sigh2);
ASSERT_TRUE(sigh1.empty());
ASSERT_FALSE(sigh2.empty());
}
TEST(SigH, Functions) {
entt::SigH<void(int &)> sigh;
int v = 0;
sigh.sink().connect<&SigHListener::f>();
sigh.publish(v);
ASSERT_FALSE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(1), sigh.size());
ASSERT_EQ(42, v);
v = 0;
sigh.sink().disconnect<&SigHListener::f>();
sigh.publish(v);
ASSERT_TRUE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(0), sigh.size());
ASSERT_EQ(0, v);
sigh.sink().connect<&SigHListener::f>();
}
TEST(SigH, Members) {
SigHListener s;
SigHListener *ptr = &s;
entt::SigH<bool(int)> sigh;
sigh.sink().connect<SigHListener, &SigHListener::g>(ptr);
sigh.publish(42);
ASSERT_TRUE(s.k);
ASSERT_FALSE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(1), sigh.size());
sigh.sink().disconnect<SigHListener, &SigHListener::g>(ptr);
sigh.publish(42);
ASSERT_TRUE(s.k);
ASSERT_TRUE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(0), sigh.size());
sigh.sink().connect<SigHListener, &SigHListener::g>(ptr);
sigh.sink().connect<SigHListener, &SigHListener::h>(ptr);
ASSERT_FALSE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(2), sigh.size());
sigh.sink().disconnect(ptr);
ASSERT_TRUE(sigh.empty());
ASSERT_EQ(static_cast<entt::SigH<bool(int)>::size_type>(0), sigh.size());
}
TEST(SigH, Collector) {
entt::SigH<void(), TestCollectAll<void>> sigh_void;
sigh_void.sink().connect<&TestCollectAll<void>::h>();
auto collector_void = sigh_void.collect();
ASSERT_FALSE(sigh_void.empty());
ASSERT_TRUE(collector_void.vec.empty());
entt::SigH<int(), TestCollectAll<int>> sigh_all;
sigh_all.sink().connect<&TestCollectAll<int>::f>();
sigh_all.sink().connect<&TestCollectAll<int>::f>();
sigh_all.sink().connect<&TestCollectAll<int>::g>();
auto collector_all = sigh_all.collect();
ASSERT_FALSE(sigh_all.empty());
ASSERT_FALSE(collector_all.vec.empty());
ASSERT_EQ(static_cast<std::vector<int>::size_type>(2), collector_all.vec.size());
ASSERT_EQ(42, collector_all.vec[0]);
ASSERT_EQ(42, collector_all.vec[1]);
entt::SigH<int(), TestCollectFirst<int>> sigh_first;
sigh_first.sink().connect<&TestCollectFirst<int>::f>();
sigh_first.sink().connect<&TestCollectFirst<int>::f>();
auto collector_first = sigh_first.collect();
ASSERT_FALSE(sigh_first.empty());
ASSERT_FALSE(collector_first.vec.empty());
ASSERT_EQ(static_cast<std::vector<int>::size_type>(1), collector_first.vec.size());
ASSERT_EQ(42, collector_first.vec[0]);
}

436
test/mod/mod.cpp Normal file
View File

@@ -0,0 +1,436 @@
#include <gtest/gtest.h>
#include <cassert>
#include <map>
#include <string>
#include <duktape.h>
#include <entt/entity/registry.hpp>
template<typename Type>
struct tag { using type = Type; };
struct Position {
double x;
double y;
};
struct Renderable {};
struct DuktapeRuntime {
std::map<duk_uint_t, std::string> components;
};
template<typename Comp>
duk_ret_t set(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
registry.accommodate<Comp>(entity);
return 0;
}
template<>
duk_ret_t set<Position>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
const auto x = duk_require_number(ctx, 2);
const auto y = duk_require_number(ctx, 3);
registry.accommodate<Position>(entity, x, y);
return 0;
}
template<>
duk_ret_t set<DuktapeRuntime>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
const auto type = duk_require_uint(ctx, 1);
duk_dup(ctx, 2);
if(!registry.has<DuktapeRuntime>(entity)) {
registry.assign<DuktapeRuntime>(entity).components[type] = duk_json_encode(ctx, -1);
} else {
registry.get<DuktapeRuntime>(entity).components[type] = duk_json_encode(ctx, -1);
}
duk_pop(ctx);
return 0;
}
template<typename Comp>
duk_ret_t unset(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
registry.remove<Comp>(entity);
return 0;
}
template<>
duk_ret_t unset<DuktapeRuntime>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
const auto type = duk_require_uint(ctx, 1);
auto &components = registry.get<DuktapeRuntime>(entity).components;
assert(components.find(type) != components.cend());
components.erase(type);
if(components.empty()) {
registry.remove<DuktapeRuntime>(entity);
}
return 0;
}
template<typename Comp>
duk_ret_t has(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
duk_push_boolean(ctx, registry.has<Comp>(entity));
return 1;
}
template<>
duk_ret_t has<DuktapeRuntime>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
duk_push_boolean(ctx, registry.has<DuktapeRuntime>(entity));
if(registry.has<DuktapeRuntime>(entity)) {
const auto type = duk_require_uint(ctx, 1);
const auto &components = registry.get<DuktapeRuntime>(entity).components;
duk_push_boolean(ctx, components.find(type) != components.cend());
} else {
duk_push_false(ctx);
}
return 1;
}
template<typename Comp>
duk_ret_t get(duk_context *ctx, entt::DefaultRegistry &registry) {
assert(registry.has<Comp>(duk_require_uint(ctx, 0)));
duk_push_object(ctx);
return 1;
}
template<>
duk_ret_t get<Position>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
const auto &position = registry.get<Position>(entity);
const auto idx = duk_push_object(ctx);
duk_push_string(ctx, "x");
duk_push_number(ctx, position.x);
duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE);
duk_push_string(ctx, "y");
duk_push_number(ctx, position.y);
duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE);
return 1;
}
template<>
duk_ret_t get<DuktapeRuntime>(duk_context *ctx, entt::DefaultRegistry &registry) {
const auto entity = duk_require_uint(ctx, 0);
const auto type = duk_require_uint(ctx, 1);
auto &runtime = registry.get<DuktapeRuntime>(entity);
assert(runtime.components.find(type) != runtime.components.cend());
duk_push_string(ctx, runtime.components[type].c_str());
duk_json_decode(ctx, -1);
return 1;
}
class DuktapeRegistry {
// I'm pretty sure I won't have more than 99 components in the example
static constexpr entt::DefaultRegistry::component_type udef = 100;
struct Func {
using func_type = duk_ret_t(*)(duk_context *, entt::DefaultRegistry &);
using test_type = bool(entt::DefaultRegistry:: *)(entt::DefaultRegistry::entity_type) const;
func_type set;
func_type unset;
func_type has;
func_type get;
test_type test;
};
template<typename... Comp>
void reg() {
using accumulator_type = int[];
accumulator_type acc = { (func[registry.type<Comp>()] = {
&::set<Comp>,
&::unset<Comp>,
&::has<Comp>,
&::get<Comp>,
&entt::DefaultRegistry::has<Comp>
}, 0)... };
(void)acc;
}
static DuktapeRegistry & instance(duk_context *ctx) {
duk_push_this(ctx);
duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg"));
duk_get_prop(ctx, -2);
auto &dreg = *static_cast<DuktapeRegistry *>(duk_require_pointer(ctx, -1));
duk_pop_2(ctx);
return dreg;
}
template<Func::func_type Func::*Op>
static duk_ret_t invoke(duk_context *ctx) {
auto &dreg = instance(ctx);
auto &func = dreg.func;
auto &registry = dreg.registry;
auto type = duk_require_uint(ctx, 1);
if(type >= udef) {
type = registry.type<DuktapeRuntime>();
}
assert(func.find(type) != func.cend());
return (func[type].*Op)(ctx, registry);
}
public:
DuktapeRegistry(entt::DefaultRegistry &registry)
: registry{registry}
{
reg<Position, Renderable, DuktapeRuntime>();
}
static duk_ret_t identifier(duk_context *ctx) {
static auto next = udef;
duk_push_uint(ctx, next++);
return 1;
}
static duk_ret_t create(duk_context *ctx) {
auto &dreg = instance(ctx);
duk_push_uint(ctx, dreg.registry.create());
return 1;
}
static duk_ret_t set(duk_context *ctx) {
return invoke<&Func::set>(ctx);
}
static duk_ret_t unset(duk_context *ctx) {
return invoke<&Func::unset>(ctx);
}
static duk_ret_t has(duk_context *ctx) {
return invoke<&Func::has>(ctx);
}
static duk_ret_t get(duk_context *ctx) {
return invoke<&Func::get>(ctx);
}
static duk_ret_t entities(duk_context *ctx) {
const duk_idx_t nargs = duk_get_top(ctx);
auto &dreg = instance(ctx);
duk_uarridx_t pos = 0;
duk_push_array(ctx);
std::vector<typename entt::DefaultRegistry::component_type> components;
std::vector<typename entt::DefaultRegistry::component_type> runtime;
for(duk_idx_t arg = 0; arg < nargs; arg++) {
auto type = duk_require_uint(ctx, arg);
if(type < udef) {
components.push_back(type);
} else {
if(runtime.empty()) {
components.push_back(dreg.registry.type<DuktapeRuntime>());
}
runtime.push_back(type);
}
}
auto view = dreg.registry.view(components.cbegin(), components.cend());
for(const auto entity: view) {
if(runtime.empty()) {
duk_push_uint(ctx, entity);
duk_put_prop_index(ctx, -2, pos++);
} else {
const auto &components = dreg.registry.get<DuktapeRuntime>(entity).components;
const auto match = std::all_of(runtime.cbegin(), runtime.cend(), [&components](const auto type) {
return components.find(type) != components.cend();
});
if(match) {
duk_push_uint(ctx, entity);
duk_put_prop_index(ctx, -2, pos++);
}
}
}
return 1;
}
private:
std::map<duk_uint_t, Func> func;
entt::DefaultRegistry &registry;
};
const duk_function_list_entry js_DuktapeRegistry_methods[] = {
{ "identifier", &DuktapeRegistry::identifier, 0 },
{ "create", &DuktapeRegistry::create, 0 },
{ "set", &DuktapeRegistry::set, DUK_VARARGS },
{ "unset", &DuktapeRegistry::unset, 2 },
{ "has", &DuktapeRegistry::has, 2 },
{ "get", &DuktapeRegistry::get, 2 },
{ "entities", &DuktapeRegistry::entities, DUK_VARARGS },
{ nullptr, nullptr, 0 }
};
void exportTypes(duk_context *ctx, entt::DefaultRegistry &registry) {
auto exportType = [](auto *ctx, auto &registry, auto idx, auto type, const auto *name) {
duk_push_string(ctx, name);
duk_push_uint(ctx, registry.template type<typename decltype(type)::type>());
duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_CLEAR_WRITABLE);
};
auto idx = duk_push_object(ctx);
exportType(ctx, registry, idx, tag<Position>{}, "POSITION");
exportType(ctx, registry, idx, tag<Renderable>{}, "RENDERABLE");
duk_put_global_string(ctx, "Types");
}
void exportDuktapeRegistry(duk_context *ctx, DuktapeRegistry &dreg) {
auto idx = duk_push_object(ctx);
duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg"));
duk_push_pointer(ctx, &dreg);
duk_put_prop(ctx, idx);
duk_put_function_list(ctx, idx, js_DuktapeRegistry_methods);
duk_put_global_string(ctx, "Registry");
}
TEST(Mod, Duktape) {
entt::DefaultRegistry registry;
DuktapeRegistry dreg{registry};
duk_context *ctx = duk_create_heap_default();
if(!ctx) {
FAIL();
}
exportTypes(ctx, registry);
exportDuktapeRegistry(ctx, dreg);
const char *s0 = ""
"Types[\"PLAYING_CHARACTER\"] = Registry.identifier();"
"Types[\"VELOCITY\"] = Registry.identifier();"
"";
if(duk_peval_string(ctx, s0)) {
FAIL();
}
const auto e0 = registry.create();
registry.assign<Position>(e0, 0., 0.);
registry.assign<Renderable>(e0);
const auto e1 = registry.create();
registry.assign<Position>(e1, 0., 0.);
const char *s1 = ""
"Registry.entities(Types.POSITION, Types.RENDERABLE).forEach(function(entity) {"
"Registry.set(entity, Types.POSITION, 100., 100.);"
"});"
"var entity = Registry.create();"
"Registry.set(entity, Types.POSITION, 100., 100.);"
"Registry.set(entity, Types.RENDERABLE);"
"";
if(duk_peval_string(ctx, s1)) {
FAIL();
}
ASSERT_EQ(registry.view<DuktapeRuntime>().size(), 0u);
ASSERT_EQ(registry.view<Position>().size(), 3u);
ASSERT_EQ(registry.view<Renderable>().size(), 2u);
registry.view<Position>().each([&registry](auto entity, const auto &position) {
ASSERT_FALSE(registry.has<DuktapeRuntime>(entity));
if(registry.has<Renderable>(entity)) {
ASSERT_EQ(position.x, 100.);
ASSERT_EQ(position.y, 100.);
} else {
ASSERT_EQ(position.x, 0.);
ASSERT_EQ(position.y, 0.);
}
});
const char *s2 = ""
"Registry.entities(Types.POSITION).forEach(function(entity) {"
"if(!Registry.has(entity, Types.RENDERABLE)) {"
"Registry.set(entity, Types.VELOCITY, { \"dx\": -100., \"dy\": -100. });"
"Registry.set(entity, Types.PLAYING_CHARACTER, {});"
"}"
"});"
"";
if(duk_peval_string(ctx, s2)) {
FAIL();
}
ASSERT_EQ(registry.view<DuktapeRuntime>().size(), 1u);
ASSERT_EQ(registry.view<Position>().size(), 3u);
ASSERT_EQ(registry.view<Renderable>().size(), 2u);
registry.view<DuktapeRuntime>().each([](auto, const DuktapeRuntime &runtime) {
ASSERT_EQ(runtime.components.size(), 2u);
});
const char *s3 = ""
"Registry.entities(Types.POSITION, Types.RENDERABLE, Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {"
"var velocity = Registry.get(entity, Types.VELOCITY);"
"Registry.set(entity, Types.POSITION, velocity.dx, velocity.dy)"
"});"
"";
if(duk_peval_string(ctx, s3)) {
FAIL();
}
ASSERT_EQ(registry.view<DuktapeRuntime>().size(), 1u);
ASSERT_EQ(registry.view<Position>().size(), 3u);
ASSERT_EQ(registry.view<Renderable>().size(), 2u);
registry.view<Position, Renderable, DuktapeRuntime>().each([](auto, const Position &position, const auto &...) {
ASSERT_EQ(position.x, -100.);
ASSERT_EQ(position.y, -100.);
});
const char *s4 = ""
"Registry.entities(Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {"
"Registry.unset(entity, Types.VELOCITY);"
"Registry.unset(entity, Types.PLAYING_CHARACTER);"
"});"
"Registry.entities(Types.POSITION).forEach(function(entity) {"
"Registry.unset(entity, Types.POSITION);"
"});"
"";
if(duk_peval_string(ctx, s4)) {
FAIL();
}
ASSERT_EQ(registry.view<DuktapeRuntime>().size(), 0u);
ASSERT_EQ(registry.view<Position>().size(), 0u);
ASSERT_EQ(registry.view<Renderable>().size(), 2u);
duk_destroy_heap(ctx);
}

1
test/odr.cpp Normal file
View File

@@ -0,0 +1 @@
#include <entt/entt.hpp>

View File

@@ -1,233 +0,0 @@
#include <gtest/gtest.h>
#include <registry.hpp>
TEST(DefaultRegistry, Functionalities) {
using registry_type = entt::DefaultRegistry<int, char>;
registry_type registry;
ASSERT_EQ(registry.size(), registry_type::size_type{0});
ASSERT_EQ(registry.capacity(), registry_type::size_type{0});
ASSERT_TRUE(registry.empty());
ASSERT_TRUE(registry.empty<int>());
ASSERT_TRUE(registry.empty<char>());
registry_type::entity_type e1 = registry.create();
registry_type::entity_type e2 = registry.create<int, char>();
ASSERT_FALSE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NE(e1, e2);
ASSERT_FALSE(registry.has<int>(e1));
ASSERT_TRUE(registry.has<int>(e2));
ASSERT_FALSE(registry.has<char>(e1));
ASSERT_TRUE(registry.has<char>(e2));
ASSERT_TRUE((registry.has<int, char>(e2)));
ASSERT_FALSE((registry.has<int, char>(e1)));
ASSERT_EQ(registry.assign<int>(e1, 42), 42);
ASSERT_EQ(registry.assign<char>(e1, 'c'), 'c');
ASSERT_NO_THROW(registry.remove<int>(e2));
ASSERT_NO_THROW(registry.remove<char>(e2));
ASSERT_TRUE(registry.has<int>(e1));
ASSERT_FALSE(registry.has<int>(e2));
ASSERT_TRUE(registry.has<char>(e1));
ASSERT_FALSE(registry.has<char>(e2));
ASSERT_TRUE((registry.has<int, char>(e1)));
ASSERT_FALSE((registry.has<int, char>(e2)));
registry_type::entity_type e3 = registry.clone(e1);
ASSERT_TRUE(registry.has<int>(e3));
ASSERT_TRUE(registry.has<char>(e3));
ASSERT_EQ(registry.get<int>(e1), 42);
ASSERT_EQ(registry.get<char>(e1), 'c');
ASSERT_EQ(registry.get<int>(e1), registry.get<int>(e3));
ASSERT_EQ(registry.get<char>(e1), registry.get<char>(e3));
ASSERT_NE(&registry.get<int>(e1), &registry.get<int>(e3));
ASSERT_NE(&registry.get<char>(e1), &registry.get<char>(e3));
ASSERT_NO_THROW(registry.copy(e2, e1));
ASSERT_TRUE(registry.has<int>(e2));
ASSERT_TRUE(registry.has<char>(e2));
ASSERT_EQ(registry.get<int>(e1), 42);
ASSERT_EQ(registry.get<char>(e1), 'c');
ASSERT_EQ(registry.get<int>(e1), registry.get<int>(e2));
ASSERT_EQ(registry.get<char>(e1), registry.get<char>(e2));
ASSERT_NE(&registry.get<int>(e1), &registry.get<int>(e2));
ASSERT_NE(&registry.get<char>(e1), &registry.get<char>(e2));
ASSERT_NO_THROW(registry.replace<int>(e1, 0));
ASSERT_EQ(registry.get<int>(e1), 0);
ASSERT_NO_THROW(registry.copy<int>(e2, e1));
ASSERT_EQ(registry.get<int>(e2), 0);
ASSERT_NE(&registry.get<int>(e1), &registry.get<int>(e2));
ASSERT_NO_THROW(registry.remove<int>(e2));
ASSERT_NO_THROW(registry.accomodate<int>(e1, 1));
ASSERT_NO_THROW(registry.accomodate<int>(e2, 1));
ASSERT_EQ(static_cast<const registry_type &>(registry).get<int>(e1), 1);
ASSERT_EQ(static_cast<const registry_type &>(registry).get<int>(e2), 1);
ASSERT_EQ(registry.size(), registry_type::size_type{3});
ASSERT_EQ(registry.capacity(), registry_type::size_type{3});
ASSERT_FALSE(registry.empty());
ASSERT_NO_THROW(registry.destroy(e3));
ASSERT_TRUE(registry.valid(e1));
ASSERT_TRUE(registry.valid(e2));
ASSERT_FALSE(registry.valid(e3));
ASSERT_EQ(registry.size(), registry_type::size_type{2});
ASSERT_EQ(registry.capacity(), registry_type::size_type{3});
ASSERT_FALSE(registry.empty());
ASSERT_NO_THROW(registry.reset());
ASSERT_EQ(registry.size(), registry_type::size_type{0});
ASSERT_EQ(registry.capacity(), registry_type::size_type{0});
ASSERT_TRUE(registry.empty());
registry.create<int, char>();
ASSERT_FALSE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NO_THROW(registry.reset<int>());
ASSERT_TRUE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_NO_THROW(registry.reset());
ASSERT_TRUE(registry.empty<int>());
ASSERT_TRUE(registry.empty<char>());
e1 = registry.create<int>();
e2 = registry.create();
ASSERT_NO_THROW(registry.reset<int>(e1));
ASSERT_NO_THROW(registry.reset<int>(e2));
ASSERT_TRUE(registry.empty<int>());
}
TEST(DefaultRegistry, Copy) {
using registry_type = entt::DefaultRegistry<int, char, double>;
registry_type registry;
registry_type::entity_type e1 = registry.create<int, char>();
registry_type::entity_type e2 = registry.create<int, double>();
ASSERT_TRUE(registry.has<int>(e1));
ASSERT_TRUE(registry.has<char>(e1));
ASSERT_FALSE(registry.has<double>(e1));
ASSERT_TRUE(registry.has<int>(e2));
ASSERT_FALSE(registry.has<char>(e2));
ASSERT_TRUE(registry.has<double>(e2));
ASSERT_NO_THROW(registry.copy(e2, e1));
ASSERT_TRUE(registry.has<int>(e1));
ASSERT_TRUE(registry.has<char>(e1));
ASSERT_FALSE(registry.has<double>(e1));
ASSERT_TRUE(registry.has<int>(e2));
ASSERT_TRUE(registry.has<char>(e2));
ASSERT_FALSE(registry.has<double>(e2));
ASSERT_FALSE(registry.empty<int>());
ASSERT_FALSE(registry.empty<char>());
ASSERT_TRUE(registry.empty<double>());
registry.reset();
}
TEST(DefaultRegistry, ViewSingleComponent) {
using registry_type = entt::DefaultRegistry<int, char>;
registry_type registry;
registry_type::entity_type e1 = registry.create();
registry_type::entity_type e2 = registry.create<int, char>();
ASSERT_NO_THROW(registry.view<char>().begin()++);
ASSERT_NO_THROW(++registry.view<char>().begin());
auto view = registry.view<char>();
ASSERT_NE(view.begin(), view.end());
ASSERT_EQ(view.size(), typename registry_type::view_type<char>::size_type{1});
registry.assign<char>(e1);
ASSERT_EQ(view.size(), typename registry_type::view_type<char>::size_type{2});
registry.remove<char>(e1);
registry.remove<char>(e2);
ASSERT_EQ(view.begin(), view.end());
ASSERT_NO_THROW(registry.reset());
}
TEST(DefaultRegistry, ViewMultipleComponent) {
using registry_type = entt::DefaultRegistry<int, char>;
registry_type registry;
registry_type::entity_type e1 = registry.create<char>();
registry_type::entity_type e2 = registry.create<int, char>();
ASSERT_NO_THROW((registry.view<int, char>().begin()++));
ASSERT_NO_THROW((++registry.view<int, char>().begin()));
auto view = registry.view<int, char>();
ASSERT_NE(view.begin(), view.end());
registry.remove<char>(e1);
registry.remove<char>(e2);
view.reset();
ASSERT_EQ(view.begin(), view.end());
ASSERT_NO_THROW(registry.reset());
}
TEST(DefaultRegistry, EmptyViewSingleComponent) {
using registry_type = entt::DefaultRegistry<char, int, double>;
registry_type registry;
registry.create<char, double>();
registry.create<char>();
auto view = registry.view<int>();
ASSERT_EQ(view.size(), registry_type::size_type{0});
registry.reset();
}
TEST(DefaultRegistry, EmptyViewMultipleComponent) {
using registry_type = entt::DefaultRegistry<char, int, float, double>;
registry_type registry;
registry.create<double, int, float>();
registry.create<char, float>();
auto view = registry.view<char, int, float>();
for(auto entity: view) {
(void)entity;
FAIL();
}
registry.reset();
}

181
test/snapshot/snapshot.cpp Normal file
View File

@@ -0,0 +1,181 @@
#include <gtest/gtest.h>
#include <sstream>
#include <vector>
#include <cereal/archives/json.hpp>
#include <entt/entity/registry.hpp>
struct Position {
float x;
float y;
};
struct Timer {
int duration;
int elapsed{0};
};
struct Relationship {
entt::DefaultRegistry::entity_type parent;
};
template<typename Archive>
void serialize(Archive &archive, Position &position) {
archive(position.x, position.y);
}
template<typename Archive>
void serialize(Archive &archive, Timer &timer) {
archive(timer.duration);
}
template<typename Archive>
void serialize(Archive &archive, Relationship &relationship) {
archive(relationship.parent);
}
TEST(Snapshot, Full) {
std::stringstream storage;
entt::DefaultRegistry source;
entt::DefaultRegistry destination;
auto e0 = source.create();
source.assign<Position>(e0, 16.f, 16.f);
source.destroy(source.create());
auto e1 = source.create();
source.assign<Position>(e1, .8f, .0f);
source.assign<Relationship>(e1, e0);
auto e2 = source.create();
auto e3 = source.create();
source.assign<Timer>(e3, 1000, 100);
source.destroy(e2);
auto v2 = source.current(e2);
{
// output finishes flushing its contents when it goes out of scope
cereal::JSONOutputArchive output{storage};
source.snapshot().entities(output).destroyed(output)
.component<Position, Timer, Relationship>(output);
}
cereal::JSONInputArchive input{storage};
destination.restore().entities(input).destroyed(input)
.component<Position, Timer, Relationship>(input);
ASSERT_TRUE(destination.valid(e0));
ASSERT_TRUE(destination.has<Position>(e0));
ASSERT_EQ(destination.get<Position>(e0).x, 16.f);
ASSERT_EQ(destination.get<Position>(e0).y, 16.f);
ASSERT_TRUE(destination.valid(e1));
ASSERT_TRUE(destination.has<Position>(e1));
ASSERT_EQ(destination.get<Position>(e1).x, .8f);
ASSERT_EQ(destination.get<Position>(e1).y, .0f);
ASSERT_TRUE(destination.has<Relationship>(e1));
ASSERT_EQ(destination.get<Relationship>(e1).parent, e0);
ASSERT_FALSE(destination.valid(e2));
ASSERT_EQ(destination.current(e2), v2);
ASSERT_TRUE(destination.valid(e3));
ASSERT_TRUE(destination.has<Timer>(e3));
ASSERT_EQ(destination.get<Timer>(e3).duration, 1000);
ASSERT_EQ(destination.get<Timer>(e3).elapsed, 0);
}
TEST(Snapshot, Continuous) {
std::stringstream storage;
entt::DefaultRegistry source;
entt::DefaultRegistry destination;
std::vector<entt::DefaultRegistry::entity_type> entities;
for(auto i = 0; i < 10; ++i) {
entities.push_back(source.create());
}
for(auto entity: entities) {
source.destroy(entity);
}
auto e0 = source.create();
source.assign<Position>(e0, 0.f, 0.f);
source.assign<Relationship>(e0, e0);
auto e1 = source.create();
source.assign<Position>(e1, 1.f, 1.f);
source.assign<Relationship>(e1, e0);
auto e2 = source.create();
source.assign<Position>(e2, .2f, .2f);
source.assign<Relationship>(e2, e0);
auto e3 = source.create();
source.assign<Timer>(e3, 1000, 1000);
source.assign<Relationship>(e3, e2);
{
// output finishes flushing its contents when it goes out of scope
cereal::JSONOutputArchive output{storage};
source.snapshot().entities(output).component<Position, Relationship, Timer>(output);
}
cereal::JSONInputArchive input{storage};
entt::ContinuousLoader<entt::DefaultRegistry::entity_type> loader{destination};
loader.entities(input)
.component<Position, Relationship>(input, &Relationship::parent)
.component<Timer>(input);
ASSERT_FALSE(destination.valid(e0));
ASSERT_TRUE(loader.has(e0));
auto l0 = loader.map(e0);
ASSERT_TRUE(destination.valid(l0));
ASSERT_TRUE(destination.has<Position>(l0));
ASSERT_EQ(destination.get<Position>(l0).x, 0.f);
ASSERT_EQ(destination.get<Position>(l0).y, 0.f);
ASSERT_TRUE(destination.has<Relationship>(l0));
ASSERT_EQ(destination.get<Relationship>(l0).parent, l0);
ASSERT_FALSE(destination.valid(e1));
ASSERT_TRUE(loader.has(e1));
auto l1 = loader.map(e1);
ASSERT_TRUE(destination.valid(l1));
ASSERT_TRUE(destination.has<Position>(l1));
ASSERT_EQ(destination.get<Position>(l1).x, 1.f);
ASSERT_EQ(destination.get<Position>(l1).y, 1.f);
ASSERT_TRUE(destination.has<Relationship>(l1));
ASSERT_EQ(destination.get<Relationship>(l1).parent, l0);
ASSERT_FALSE(destination.valid(e2));
ASSERT_TRUE(loader.has(e2));
auto l2 = loader.map(e2);
ASSERT_TRUE(destination.valid(l2));
ASSERT_TRUE(destination.has<Position>(l2));
ASSERT_EQ(destination.get<Position>(l2).x, .2f);
ASSERT_EQ(destination.get<Position>(l2).y, .2f);
ASSERT_TRUE(destination.has<Relationship>(l2));
ASSERT_EQ(destination.get<Relationship>(l2).parent, l0);
ASSERT_FALSE(destination.valid(e3));
ASSERT_TRUE(loader.has(e3));
auto l3 = loader.map(e3);
ASSERT_TRUE(destination.valid(l3));
ASSERT_TRUE(destination.has<Timer>(l3));
ASSERT_EQ(destination.get<Timer>(l3).duration, 1000);
ASSERT_EQ(destination.get<Timer>(l3).elapsed, 0);
ASSERT_TRUE(destination.has<Relationship>(l3));
ASSERT_EQ(destination.get<Relationship>(l3).parent, l2);
}