Custom Godot servers

Introduction

Godot implements multi-threading as servers. Servers are daemons which manage data, process it, and push the result. Servers implement the mediator pattern which interprets resource ID and process data for the engine and other modules. In addition, the server claims ownership for its RID allocations.

This guide assumes the reader knows how to create C++ modules and Godot data types. If not, refer to Custom modules in C++.

References

What for?

  • Adding artificial intelligence.

  • Adding custom asynchronous threads.

  • Adding support for a new input device.

  • Adding writing threads.

  • Adding a custom VoIP protocol.

  • And more…

Creating a Godot server

At minimum, a server must have a static instance, a sleep timer, a thread loop, an initialization state and a cleanup procedure.

  1. #ifndef HILBERT_HOTEL_H
  2. #define HILBERT_HOTEL_H
  3. #include "core/object/object.h"
  4. #include "core/os/thread.h"
  5. #include "core/os/mutex.h"
  6. #include "core/templates/list.h"
  7. #include "core/templates/rid.h"
  8. #include "core/templates/set.h"
  9. #include "core/variant/variant.h"
  10. class HilbertHotel : public Object {
  11. GDCLASS(HilbertHotel, Object);
  12. static HilbertHotel *singleton;
  13. static void thread_func(void *p_udata);
  14. private:
  15. bool thread_exited;
  16. mutable bool exit_thread;
  17. Thread *thread;
  18. Mutex *mutex;
  19. public:
  20. static HilbertHotel *get_singleton();
  21. Error init();
  22. void lock();
  23. void unlock();
  24. void finish();
  25. protected:
  26. static void _bind_methods();
  27. private:
  28. uint64_t counter;
  29. RID_Owner<InfiniteBus> bus_owner;
  30. // https://github.com/godotengine/godot/blob/master/core/templates/rid.h
  31. Set<RID> buses;
  32. void _emit_occupy_room(uint64_t room, RID rid);
  33. public:
  34. RID create_bus();
  35. Variant get_bus_info(RID id);
  36. bool empty();
  37. bool delete_bus(RID id);
  38. void clear();
  39. void register_rooms();
  40. HilbertHotel();
  41. };
  42. #endif
  1. #include "hilbert_hotel.h"
  2. #include "core/variant/dictionary.h"
  3. #include "core/os/os.h"
  4. #include "prime_225.h"
  5. void HilbertHotel::thread_func(void *p_udata) {
  6. HilbertHotel *ac = (HilbertHotel *) p_udata;
  7. uint64_t msdelay = 1000;
  8. while (!ac->exit_thread) {
  9. if (!ac->empty()) {
  10. ac->lock();
  11. ac->register_rooms();
  12. ac->unlock();
  13. }
  14. OS::get_singleton()->delay_usec(msdelay * 1000);
  15. }
  16. }
  17. Error HilbertHotel::init() {
  18. thread_exited = false;
  19. counter = 0;
  20. mutex = Mutex::create();
  21. thread = Thread::create(HilbertHotel::thread_func, this);
  22. return OK;
  23. }
  24. HilbertHotel *HilbertHotel::singleton = NULL;
  25. HilbertHotel *HilbertHotel::get_singleton() {
  26. return singleton;
  27. }
  28. void HilbertHotel::register_rooms() {
  29. for (Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  30. auto bus = bus_owner.getornull(e->get());
  31. if (bus) {
  32. uint64_t room = bus->next_room();
  33. _emit_occupy_room(room, bus->get_self());
  34. }
  35. }
  36. }
  37. void HilbertHotel::unlock() {
  38. if (!thread || !mutex) {
  39. return;
  40. }
  41. mutex->unlock();
  42. }
  43. void HilbertHotel::lock() {
  44. if (!thread || !mutex) {
  45. return;
  46. }
  47. mutex->lock();
  48. }
  49. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  50. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  51. }
  52. Variant HilbertHotel::get_bus_info(RID id) {
  53. InfiniteBus *bus = bus_owner.getornull(id);
  54. if (bus) {
  55. Dictionary d;
  56. d["prime"] = bus->get_bus_num();
  57. d["current_room"] = bus->get_current_room();
  58. return d;
  59. }
  60. return Variant();
  61. }
  62. void HilbertHotel::finish() {
  63. if (!thread) {
  64. return;
  65. }
  66. exit_thread = true;
  67. Thread::wait_to_finish(thread);
  68. memdelete(thread);
  69. if (mutex) {
  70. memdelete(mutex);
  71. }
  72. thread = NULL;
  73. }
  74. RID HilbertHotel::create_bus() {
  75. lock();
  76. InfiniteBus *ptr = memnew(InfiniteBus(PRIME[counter++]));
  77. RID ret = bus_owner.make_rid(ptr);
  78. ptr->set_self(ret);
  79. buses.insert(ret);
  80. unlock();
  81. return ret;
  82. }
  83. // https://github.com/godotengine/godot/blob/master/core/templates/rid.h
  84. bool HilbertHotel::delete_bus(RID id) {
  85. if (bus_owner.owns(id)) {
  86. lock();
  87. InfiniteBus *b = bus_owner.get(id);
  88. bus_owner.free(id);
  89. buses.erase(id);
  90. memdelete(b);
  91. unlock();
  92. return true;
  93. }
  94. return false;
  95. }
  96. void HilbertHotel::clear() {
  97. for (Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  98. delete_bus(e->get());
  99. }
  100. }
  101. bool HilbertHotel::empty() {
  102. return buses.size() <= 0;
  103. }
  104. void HilbertHotel::_bind_methods() {
  105. }
  106. HilbertHotel::HilbertHotel() {
  107. singleton = this;
  108. }
  1. /* prime_225.h */
  2. const uint64_t PRIME[225] = {
  3. 2,3,5,7,11,13,17,19,23,
  4. 29,31,37,41,43,47,53,59,61,
  5. 67,71,73,79,83,89,97,101,103,
  6. 107,109,113,127,131,137,139,149,151,
  7. 157,163,167,173,179,181,191,193,197,
  8. 199,211,223,227,229,233,239,241,251,
  9. 257,263,269,271,277,281,283,293,307,
  10. 311,313,317,331,337,347,349,353,359,
  11. 367,373,379,383,389,397,401,409,419,
  12. 421,431,433,439,443,449,457,461,463,
  13. 467,479,487,491,499,503,509,521,523,
  14. 541,547,557,563,569,571,577,587,593,
  15. 599,601,607,613,617,619,631,641,643,
  16. 647,653,659,661,673,677,683,691,701,
  17. 709,719,727,733,739,743,751,757,761,
  18. 769,773,787,797,809,811,821,823,827,
  19. 829,839,853,857,859,863,877,881,883,
  20. 887,907,911,919,929,937,941,947,953,
  21. 967,971,977,983,991,997,1009,1013,1019,
  22. 1021,1031,1033,1039,1049,1051,1061,1063,1069,
  23. 1087,1091,1093,1097,1103,1109,1117,1123,1129,
  24. 1151,1153,1163,1171,1181,1187,1193,1201,1213,
  25. 1217,1223,1229,1231,1237,1249,1259,1277,1279,
  26. 1283,1289,1291,1297,1301,1303,1307,1319,1321,
  27. 1327,1361,1367,1373,1381,1399,1409,1423,1427
  28. };

Custom managed resource data

Godot servers implement a mediator pattern. All data types inherit RID_Data. RID_Owner<MyRID_Data> owns the object when make_rid is called. During debug mode only, RID_Owner maintains a list of RIDs. In practice, RIDs are similar to writing object-oriented C code.

  1. class InfiniteBus : public RID_Data {
  2. RID self;
  3. private:
  4. uint64_t prime_num;
  5. uint64_t num;
  6. public:
  7. uint64_t next_room() {
  8. return prime_num * num++;
  9. }
  10. uint64_t get_bus_num() const {
  11. return prime_num;
  12. }
  13. uint64_t get_current_room() const {
  14. return prime_num * num;
  15. }
  16. _FORCE_INLINE_ void set_self(const RID &p_self) {
  17. self = p_self;
  18. }
  19. _FORCE_INLINE_ RID get_self() const {
  20. return self;
  21. }
  22. InfiniteBus(uint64_t prime) : prime_num(prime), num(1) {};
  23. ~InfiniteBus() {};
  24. }

References

Registering the class in GDScript

Servers are allocated in register_types.cpp. The constructor sets the static instance and init() creates the managed thread; unregister_types.cpp cleans up the server.

Since a Godot server class creates an instance and binds it to a static singleton, binding the class might not reference the correct instance. Therefore, a dummy class must be created to reference the proper Godot server.

In register_server_types(), Engine::get_singleton()->add_singleton is used to register the dummy class in GDScript.

  1. /* register_types.cpp */
  2. #include "register_types.h"
  3. #include "core/object/class_db.h"
  4. #include "core/config/engine.h"
  5. #include "hilbert_hotel.h"
  6. static HilbertHotel *hilbert_hotel = NULL;
  7. static _HilbertHotel *_hilbert_hotel = NULL;
  8. void register_hilbert_hotel_types() {
  9. hilbert_hotel = memnew(HilbertHotel);
  10. hilbert_hotel->init();
  11. _hilbert_hotel = memnew(_HilbertHotel);
  12. ClassDB::register_class<_HilbertHotel>();
  13. Engine::get_singleton()->add_singleton(Engine::Singleton("HilbertHotel", _HilbertHotel::get_singleton()));
  14. }
  15. void unregister_hilbert_hotel_types() {
  16. if (hilbert_hotel) {
  17. hilbert_hotel->finish();
  18. memdelete(hilbert_hotel);
  19. }
  20. if (_hilbert_hotel) {
  21. memdelete(_hilbert_hotel);
  22. }
  23. }
  1. /* register_types.h */
  2. /* Yes, the word in the middle must be the same as the module folder name */
  3. void register_hilbert_hotel_types();
  4. void unregister_hilbert_hotel_types();

Bind methods

The dummy class binds singleton methods to GDScript. In most cases, the dummy class methods wraps around.

  1. Variant _HilbertHotel::get_bus_info(RID id) {
  2. return HilbertHotel::get_singleton()->get_bus_info(id);
  3. }

Binding Signals

It is possible to emit signals to GDScript by calling the GDScript dummy object.

  1. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  2. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  3. }
  1. class _HilbertHotel : public Object {
  2. GDCLASS(_HilbertHotel, Object);
  3. friend class HilbertHotel;
  4. static _HilbertHotel *singleton;
  5. protected:
  6. static void _bind_methods();
  7. private:
  8. void _occupy_room(int room_number, RID bus);
  9. public:
  10. RID create_bus();
  11. void connect_signals();
  12. bool delete_bus(RID id);
  13. static _HilbertHotel *get_singleton();
  14. Variant get_bus_info(RID id);
  15. _HilbertHotel();
  16. ~_HilbertHotel();
  17. };
  18. #endif
  1. _HilbertHotel *_HilbertHotel::singleton = NULL;
  2. _HilbertHotel *_HilbertHotel::get_singleton() { return singleton; }
  3. RID _HilbertHotel::create_bus() {
  4. return HilbertHotel::get_singleton()->create_bus();
  5. }
  6. bool _HilbertHotel::delete_bus(RID rid) {
  7. return HilbertHotel::get_singleton()->delete_bus(rid);
  8. }
  9. void _HilbertHotel::_occupy_room(int room_number, RID bus) {
  10. emit_signal("occupy_room", room_number, bus);
  11. }
  12. Variant _HilbertHotel::get_bus_info(RID id) {
  13. return HilbertHotel::get_singleton()->get_bus_info(id);
  14. }
  15. void _HilbertHotel::_bind_methods() {
  16. ClassDB::bind_method(D_METHOD("get_bus_info", "r_id"), &_HilbertHotel::get_bus_info);
  17. ClassDB::bind_method(D_METHOD("create_bus"), &_HilbertHotel::create_bus);
  18. ClassDB::bind_method(D_METHOD("delete_bus"), &_HilbertHotel::delete_bus);
  19. ADD_SIGNAL(MethodInfo("occupy_room", PropertyInfo(Variant::INT, "room_number"), PropertyInfo(Variant::_RID, "r_id")));
  20. }
  21. void _HilbertHotel::connect_signals() {
  22. HilbertHotel::get_singleton()->connect("occupy_room", _HilbertHotel::get_singleton(), "_occupy_room");
  23. }
  24. _HilbertHotel::_HilbertHotel() {
  25. singleton = this;
  26. }
  27. _HilbertHotel::~_HilbertHotel() {
  28. }

MessageQueue

In order to send commands into SceneTree, MessageQueue is a thread-safe buffer to queue set and call methods for other threads. To queue a command, obtain the target object RID and use either push_call, push_set, or push_notification to execute the desired behavior. The queue will be flushed whenever either SceneTree::idle or SceneTree::iteration is executed.

References:

Summing it up

Here is the GDScript sample code:

  1. extends Node
  2. func _ready():
  3. print("Start debugging")
  4. HilbertHotel.occupy_room.connect(_print_occupy_room)
  5. var rid = HilbertHotel.create_bus()
  6. OS.delay_msec(2000)
  7. HilbertHotel.create_bus()
  8. OS.delay_msec(2000)
  9. HilbertHotel.create_bus()
  10. OS.delay_msec(2000)
  11. print(HilbertHotel.get_bus_info(rid))
  12. HilbertHotel.delete_bus(rid)
  13. print("Ready done")
  14. func _print_occupy_room(room_number, r_id):
  15. print("Room number: " + str(room_number) + ", RID: " + str(r_id))
  16. print(HilbertHotel.get_bus_info(r_id))

Notes

  • The actual Hilbert Hotel is impossible.

  • Connecting signal example code is pretty hacky.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next