]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/registry.qh
Merge branch 'master' into TimePath/effectinfo
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / registry.qh
1 #ifndef REGISTRY_H
2 #define REGISTRY_H
3
4 #include "oo.qh"
5
6 #define REGISTER_INIT(ns, id) [[accumulate]] void Register_##ns##_##id##_init(entity this)
7 #define REGISTER_INIT_POST(ns, id) [[accumulate]] void Register_##ns##_##id##_init_post(entity this)
8
9 /**
10  * Register a new entity with a global constructor.
11  * Must be followed by a semicolon or a function body with a `this` parameter.
12  * Wrapper macros may perform actions after user initialization like so:
13  *     #define REGISTER_FOO(id) \
14  *         REGISTER(RegisterFoos, FOO, FOOS, FOOS_COUNT, id, m_id, NEW(Foo)); \
15  *         REGISTER_INIT_POST(FOO, id) { \
16  *             print("Registering foo #", this.m_id + 1, "\n"); \
17  *         } \
18  *         REGISTER_INIT(FOO, id)
19  *
20  * Don't forget to forward declare `initfunc` and call `REGISTER_REGISTRY`:
21  *     void RegisterFoos();
22  *     REGISTER_REGISTRY(RegisterFoos)
23  *
24  * @param initfunc  The global constructor to accumulate into
25  * @param ns        Short for namespace, prefix for each global (ns##_##id)
26  * @param array     The array to add each entity to. Also requires `array##_first` and `array##_last` to be defined
27  * @param counter   Global to count number of entries
28  * @param id        The identifier of the current entity being registered
29  * @param fld       The field to store the current count into
30  * @param inst      An expression to create a new instance, invoked for every registration
31  */
32 #define REGISTER(initfunc, ns, array, counter, id, fld, inst)   \
33     entity ns##_##id;                                           \
34     REGISTER_INIT(ns, id) { }                                   \
35     REGISTER_INIT_POST(ns, id) { }                              \
36     .entity enemy; /* internal next pointer */                  \
37     void Register_##ns##_##id() {                               \
38         entity this = inst;                                     \
39         ns##_##id = this;                                       \
40         this.fld = counter;                                     \
41         array[counter++] = this;                                \
42         if (!array##_first)    array##_first = this;            \
43         if ( array##_last)     array##_last.enemy = this;       \
44         array##_last = this;                                    \
45         Register_##ns##_##id##_init(this);                      \
46         Register_##ns##_##id##_init_post(this);                 \
47     }                                                           \
48     ACCUMULATE_FUNCTION(initfunc, Register_##ns##_##id)         \
49     REGISTER_INIT(ns, id)
50
51 #endif