custom_godot_servers.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. .. _doc_custom_godot_servers:
  2. Custom Godot Servers
  3. ====================
  4. Introduction
  5. ------------
  6. Godot implements multi threading as servers. Servers are daemons which
  7. manages data, processes, and pushes the result. Server implements the
  8. mediator pattern which interprets resource ID and process data for the
  9. engine and other modules. In addition, the server claims ownership for
  10. its RID allocations.
  11. This guide assumes the reader knows how to create C++ modules and godot
  12. data types. If not, refer to this guide :ref:`doc_custom_modules_in_c++`.
  13. References:
  14. ~~~~~~~~~~~
  15. - `Why does Godot use Servers and RIDs? <https://godotengine.org/article/why-does-godot-use-servers-and-rids>`__
  16. - `Sigleton Pattern <https://en.wikipedia.org/wiki/Singleton_pattern>`__
  17. - `Mediator Pattern <https://en.wikipedia.org/wiki/Mediator_pattern>`__
  18. What for?
  19. ---------
  20. - Adding AI
  21. - Adding a custom asynchronous threads
  22. - Adding Input support
  23. - Adding writing threads
  24. - Adding custom VOIP protocol
  25. - etc.
  26. Creating a Godot Server
  27. -----------------------
  28. At minimum, a server must to have: a static instance, sleep timer, thread loop,
  29. initialize state, and cleanup.
  30. .. code:: cpp
  31. #ifndef HILBERT_HOTEL_H
  32. #define HILBERT_HOTEL_H
  33. #include "object.h"
  34. #include "list.h"
  35. #include "rid.h"
  36. #include "set.h"
  37. #include "variant.h"
  38. #include "os/thread.h"
  39. #include "os/mutex.h"
  40. class HilbertHotel : public Object {
  41. GDCLASS(HilbertHotel, Object);
  42. static HilbertHotel *singleton;
  43. static void thread_func(void *p_udata);
  44. private:
  45. bool thread_exited;
  46. mutable bool exit_thread;
  47. Thread *thread;
  48. Mutex *mutex;
  49. public:
  50. static HilbertHotel *get_singleton();
  51. Error init();
  52. void lock();
  53. void unlock();
  54. void finish();
  55. protected:
  56. static void _bind_methods();
  57. private:
  58. uint64_t counter;
  59. RID_Owner<InfiniteBus> bus_owner;
  60. //https://github.com/godotengine/godot/blob/master/core/rid.h#L196
  61. Set<RID> buses;
  62. void _emit_occupy_room(uint64_t room, RID rid);
  63. public:
  64. RID create_bus();
  65. Variant get_bus_info(RID id);
  66. bool empty();
  67. bool delete_bus(RID id);
  68. void clear();
  69. void register_rooms();
  70. HilbertHotel();
  71. };
  72. #endif
  73. .. code:: cpp
  74. #include "hilbert_hotel.h"
  75. #include "variant.h"
  76. #include "os/os.h"
  77. #include "list.h"
  78. #include "dictionary.h"
  79. #include "prime_225.h"
  80. oid HilbertHotel::thread_func(void *p_udata){
  81. HilbertHotel *ac = (HilbertHotel *) p_udata;
  82. uint64_t msdelay = 1000;
  83. while(!ac -> exit_thread){
  84. if(!ac -> empty()) {
  85. ac->lock();
  86. ac->register_rooms();
  87. ac->unlock();
  88. }
  89. OS::get_singleton()->delay_usec(msdelay * 1000);
  90. }
  91. }
  92. Error HilbertHotel::init(){
  93. thread_exited = false;
  94. counter = 0;
  95. mutex = Mutex::create();
  96. thread = Thread::create(HilbertHotel::thread_func, this);
  97. return OK;
  98. }
  99. HilbertHotel *HilbertHotel::singleton = NULL;
  100. HilbertHotel *HilbertHotel::get_singleton() { return singleton; }
  101. void HilbertHotel::register_rooms() {
  102. for( Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  103. auto bus = bus_owner.getornull(e->get());
  104. if(bus){
  105. uint64_t room = bus->next_room();
  106. _emit_occupy_room(room, bus->get_self());
  107. }
  108. }
  109. }
  110. void HilbertHotel::unlock() {
  111. if (!thread || !mutex)
  112. return;
  113. mutex->unlock();
  114. }
  115. void HilbertHotel::lock() {
  116. if (!thread || !mutex)
  117. return;
  118. mutex->lock();
  119. }
  120. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  121. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  122. }
  123. Variant HilbertHotel::get_bus_info(RID id){
  124. InfiniteBus * bus = bus_owner.getornull(id);
  125. if(bus){
  126. Dictionary d;
  127. d["prime"] = bus->get_bus_num();
  128. d["current_room"] = bus->get_current_room();
  129. return d;
  130. }
  131. return Variant();
  132. }
  133. void HilbertHotel::finish() {
  134. if (!thread)
  135. return;
  136. exit_thread = true;
  137. Thread::wait_to_finish(thread);
  138. memdelete(thread);
  139. if (mutex)
  140. memdelete(mutex);
  141. thread = NULL;
  142. }
  143. RID HilbertHotel::create_bus() {
  144. lock();
  145. InfiniteBus *ptr = memnew(InfiniteBus(PRIME[counter++]));
  146. RID ret = bus_owner.make_rid(ptr);
  147. ptr->set_self(ret);
  148. buses.insert(ret);
  149. unlock();
  150. return ret;
  151. }
  152. //https://github.com/godotengine/godot/blob/master/core/rid.h#L187
  153. bool HilbertHotel::delete_bus(RID id) {
  154. if (bus_owner.owns(id)) {
  155. lock();
  156. InfiniteBus *b = bus_owner.get(id);
  157. bus_owner.free(id);
  158. buses.erase(id);
  159. memdelete(b);
  160. unlock();
  161. return true;
  162. }
  163. return false;
  164. }
  165. void HilbertHotel::clear() {
  166. for( Set<RID>::Element *e = buses.front(); e; e = e->next()) {
  167. delete_bus(e->get());
  168. }
  169. }
  170. bool HilbertHotel::empty() {
  171. return buses.size() <= 0;
  172. }
  173. void HilbertHotel::_bind_methods() {
  174. }
  175. HilbertHotel::HilbertHotel() {
  176. singleton = this;
  177. }
  178. .. code:: cpp
  179. /* prime_225.h */
  180. #include "int_types.h"
  181. const uint64_t PRIME[225] = {2,3,5,7,11,13,17,19,23,
  182. 29,31,37,41,43,47,53,59,61,
  183. 67,71,73,79,83,89,97,101,103,
  184. 107,109,113,127,131,137,139,149,151,
  185. 157,163,167,173,179,181,191,193,197,
  186. 199,211,223,227,229,233,239,241,251,
  187. 257,263,269,271,277,281,283,293,307,
  188. 311,313,317,331,337,347,349,353,359,
  189. 367,373,379,383,389,397,401,409,419,
  190. 421,431,433,439,443,449,457,461,463,
  191. 467,479,487,491,499,503,509,521,523,
  192. 541,547,557,563,569,571,577,587,593,
  193. 599,601,607,613,617,619,631,641,643,
  194. 647,653,659,661,673,677,683,691,701,
  195. 709,719,727,733,739,743,751,757,761,
  196. 769,773,787,797,809,811,821,823,827,
  197. 829,839,853,857,859,863,877,881,883,
  198. 887,907,911,919,929,937,941,947,953,
  199. 967,971,977,983,991,997,1009,1013,1019,
  200. 1021,1031,1033,1039,1049,1051,1061,1063,1069,
  201. 1087,1091,1093,1097,1103,1109,1117,1123,1129,
  202. 1151,1153,1163,1171,1181,1187,1193,1201,1213,
  203. 1217,1223,1229,1231,1237,1249,1259,1277,1279,
  204. 1283,1289,1291,1297,1301,1303,1307,1319,1321,
  205. 1327,1361,1367,1373,1381,1399,1409,1423,1427};
  206. Custom Managed Resource Data
  207. ----------------------------
  208. Godot servers implement a mediator pattern. All data types inherit ``RID_Data``.
  209. `RID_Owner<MyRID_Data>`` owns the object when ``make_rid`` is called. Only during debug mode,
  210. RID_Owner maintains a list of RID. In practice, RID is similar to writing
  211. object oriented C code.
  212. .. code:: cpp
  213. class InfiniteBus : public RID_Data {
  214. RID self;
  215. private:
  216. uint64_t prime_num;
  217. uint64_t num;
  218. public:
  219. uint64_t next_room() {
  220. return prime_num * num++;
  221. }
  222. uint64_t get_bus_num() const {
  223. return prime_num;
  224. }
  225. uint64_t get_current_room() const {
  226. return prime_num * num;
  227. }
  228. _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
  229. _FORCE_INLINE_ RID get_self() const { return self; }
  230. InfiniteBus(uint64_t prime) : prime_num(prime), num(1) {};
  231. ~InfiniteBus() {};
  232. }
  233. References:
  234. ~~~~~~~~~~~
  235. - :ref:`RID<class_rid>`
  236. - `core/rid.h <https://github.com/godotengine/godot/blob/master/core/rid.h>`__
  237. Registering the class to GDScript
  238. ---------------------------------
  239. Server are allocated in ``register_types.cpp``. The constructor sets the static
  240. instance and init creates the managed thread. ``unregister_types.cpp``
  241. cleans up the server
  242. Since Godot Server class creates an instance and binds it to a static singleton,
  243. binding the class might not reference the correct instance. Therefore, a dummy
  244. class must be created to reference the proper Godot Server.
  245. In ``register_godotserver_types()``, ``Engine::get_singleton()->add_singleton`` is used to register the dummy class to GDScript.
  246. .. code:: cpp
  247. /* register_types.cpp */
  248. #include "register_types.h"
  249. #include "class_db.h"
  250. #include "hilbert_hotel.h"
  251. #include "engine.h"
  252. static HilbertHotel *hilbert_hotel = NULL;
  253. static _HilbertHotel *_hilbert_hotel = NULL;
  254. void register_hilbert_hotel_types() {
  255. hilbert_hotel = memnew(HilbertHotel);
  256. hilbert_hotel->init();
  257. _hilbert_hotel = memnew(_HilbertHotel);
  258. ClassDB::register_class<_HilbertHotel>();
  259. Engine::get_singleton()->add_singleton(Engine::Singleton("HilbertHotel", _HilbertHotel::get_singleton()));
  260. }
  261. void unregister_hilbert_hotel_types() {
  262. if(hilbert_hotel){
  263. hilbert_hotel->finish();
  264. memdelete(hilbert_hotel);
  265. }
  266. if(_hilbert_hotel) {
  267. memdelete(_hilbert_hotel);
  268. }
  269. }
  270. .. code:: cpp
  271. /* register_types.h */
  272. void register_hilbert_hotel_types();
  273. void unregister_hilbert_hotel_types();
  274. /* yes, the word in the middle must be the same as the module folder name */
  275. - `servers/register_server_types.cpp <https://github.com/godotengine/godot/blob/master/servers/register_server_types.cpp>`__
  276. Bind methods
  277. ~~~~~~~~~~~~
  278. The dummy class binds singleton methods to gdscript. In most cases, the dummy class methods wraps around.
  279. .. code:: cpp
  280. Variant _HilbertHotel::get_bus_info(RID id) {
  281. return HilbertHotel::get_singleton()->get_bus_info(id);
  282. }
  283. Binding Signals
  284. It is possible to emit signals to gdscript but calling the GDScript dummy object.
  285. .. code:: cpp
  286. void HilbertHotel::_emit_occupy_room(uint64_t room, RID rid) {
  287. _HilbertHotel::get_singleton()->_occupy_room(room, rid);
  288. }
  289. .. code:: cpp
  290. class _HilbertHotel : public Object {
  291. GDCLASS(_HilbertHotel, Object);
  292. friend class HilbertHotel;
  293. static _HilbertHotel *singleton;
  294. protected:
  295. static void _bind_methods();
  296. private:
  297. void _occupy_room(int room_number, RID bus);
  298. public:
  299. RID create_bus();
  300. void connect_singals();
  301. bool delete_bus(RID id);
  302. static _HilbertHotel *get_singleton();
  303. Variant get_bus_info(RID id);
  304. _HilbertHotel();
  305. ~_HilbertHotel();
  306. };
  307. #endif
  308. .. code:: cpp
  309. _HilbertHotel *_HilbertHotel::singleton = NULL;
  310. _HilbertHotel *_HilbertHotel::get_singleton() { return singleton; }
  311. RID _HilbertHotel::create_bus() {
  312. return HilbertHotel::get_singleton()->create_bus();
  313. }
  314. bool _HilbertHotel::delete_bus(RID rid) {
  315. return HilbertHotel::get_singleton()->delete_bus(rid);
  316. }
  317. void _HilbertHotel::_occupy_room(int room_number, RID bus){
  318. emit_signal("occupy_room", room_number, bus);
  319. }
  320. Variant _HilbertHotel::get_bus_info(RID id) {
  321. return HilbertHotel::get_singleton()->get_bus_info(id);
  322. }
  323. void _HilbertHotel::_bind_methods() {
  324. ClassDB::bind_method(D_METHOD("get_bus_info", "r_id"), &_HilbertHotel::get_bus_info);
  325. ClassDB::bind_method(D_METHOD("create_bus"), &_HilbertHotel::create_bus);
  326. ClassDB::bind_method(D_METHOD("delete_bus"), &_HilbertHotel::delete_bus);
  327. ADD_SIGNAL(MethodInfo("occupy_room", PropertyInfo(Variant::INT, "room_number"), PropertyInfo(Variant::_RID, "r_id")));
  328. }
  329. void _HilbertHotel::connect_singals() {
  330. HilbertHotel::get_singleton()->connect("occupy_room", _HilbertHotel::get_singleton(), "_occupy_room");
  331. }
  332. _HilbertHotel::_HilbertHotel() {
  333. singleton = this;
  334. }
  335. _HilbertHotel::~_HilbertHotel() {
  336. }
  337. MessageQueue
  338. ------------
  339. In order to send commands into scenetree, MessageQueue is a thread safe buffer
  340. to queue set and call methods for other threads. To queue a command, obtain
  341. the target object RID and use either push_call, push_set, or push_notification
  342. to execute the desired behavior. Queue will be flushed whenever either
  343. ``SceneTree::idle`` or ``SceneTree::iteration`` are executed.
  344. References:
  345. ~~~~~~~~~~~
  346. - `core/message_queue.cpp <https://github.com/godotengine/godot/blob/master/core/message_queue.cpp>`__
  347. Summing it up
  348. -------------
  349. Here is the GDScript sample code
  350. .. code::
  351. extends Node
  352. # class member variables go here, for example:
  353. # var a = 2
  354. # var b = "textvar"
  355. func _ready():
  356. # Called when the node is added to the scene for the first time.
  357. # Initialization here
  358. print("start Debugging")
  359. HilbertHotel.connect("occupy_room", self, "_print_occupy_room")
  360. var rid = HilbertHotel.create_bus()
  361. OS.delay_msec(2000)
  362. HilbertHotel.create_bus()
  363. OS.delay_msec(2000)
  364. HilbertHotel.create_bus()
  365. OS.delay_msec(2000)
  366. print(HilbertHotel.get_bus_info(rid))
  367. HilbertHotel.delete_bus(rid)
  368. print("ready done")
  369. pass
  370. func _print_occupy_room(room_number, r_id):
  371. print("room_num: " + str(room_number) + " rid: " + str(r_id))
  372. print(HilbertHotel.get_bus_info(r_id))
  373. Notes
  374. ~~~~~
  375. - Actual `Hilbert Hotel <https://en.wikipedia.org/wiki/Hilbert%27s_paradox_of_the_Grand_Hotel>`__ is impossible
  376. - Connecting signal example code is pretty hacky