custom_modules_in_cpp.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. .. _doc_custom_modules_in_c++:
  2. Custom modules in C++
  3. =====================
  4. Modules
  5. -------
  6. Godot allows extending the engine in a modular way. New modules can be
  7. created and then enabled/disabled. This allows for adding new engine
  8. functionality at every level without modifying the core, which can be
  9. split for use and reuse in different modules.
  10. Modules are located in the ``modules/`` subdirectory of the build system.
  11. By default, many different modules exist, such as GDScript (which, yes,
  12. is not part of the base engine), the Mono runtime, a regular expressions
  13. module, and others. As many new modules as desired can be
  14. created and combined, and the SCons build system will take care of it
  15. transparently.
  16. What for?
  17. ---------
  18. While it's recommended that most of a game is written in scripting (as
  19. it is an enormous time saver), it's perfectly possible to use C++
  20. instead. Adding C++ modules can be useful in the following scenarios:
  21. - Binding an external library to Godot (like Bullet, Physx, FMOD, etc).
  22. - Optimize critical parts of a game.
  23. - Adding new functionality to the engine and/or editor.
  24. - Porting an existing game.
  25. - Write a whole, new game in C++ because you can't live without C++.
  26. Creating a new module
  27. ---------------------
  28. Before creating a module, make sure to download the source code of Godot
  29. and manage to compile it. There are tutorials in the documentation for this.
  30. To create a new module, the first step is creating a directory inside
  31. ``modules/``. If you want to maintain the module separately, you can checkout
  32. a different VCS into modules and use it.
  33. The example module will be called "summator", and is placed inside the
  34. Godot source tree (``C:\godot`` refers to wherever the Godot sources are
  35. located):
  36. ::
  37. C:\godot> cd modules
  38. C:\godot\modules> mkdir summator
  39. C:\godot\modules> cd summator
  40. C:\godot\modules\summator>
  41. Inside we will create a simple summator class:
  42. .. code:: cpp
  43. /* summator.h */
  44. #ifndef SUMMATOR_H
  45. #define SUMMATOR_H
  46. #include "reference.h"
  47. class Summator : public Reference {
  48. GDCLASS(Summator, Reference);
  49. int count;
  50. protected:
  51. static void _bind_methods();
  52. public:
  53. void add(int value);
  54. void reset();
  55. int get_total() const;
  56. Summator();
  57. };
  58. #endif
  59. And then the cpp file.
  60. .. code:: cpp
  61. /* summator.cpp */
  62. #include "summator.h"
  63. void Summator::add(int value) {
  64. count += value;
  65. }
  66. void Summator::reset() {
  67. count = 0;
  68. }
  69. int Summator::get_total() const {
  70. return count;
  71. }
  72. void Summator::_bind_methods() {
  73. ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add);
  74. ClassDB::bind_method(D_METHOD("reset"), &Summator::reset);
  75. ClassDB::bind_method(D_METHOD("get_total"), &Summator::get_total);
  76. }
  77. Summator::Summator() {
  78. count = 0;
  79. }
  80. Then, the new class needs to be registered somehow, so two more files
  81. need to be created:
  82. ::
  83. register_types.h
  84. register_types.cpp
  85. With the following contents:
  86. .. code:: cpp
  87. /* register_types.h */
  88. void register_summator_types();
  89. void unregister_summator_types();
  90. /* yes, the word in the middle must be the same as the module folder name */
  91. .. code:: cpp
  92. /* register_types.cpp */
  93. #include "register_types.h"
  94. #include "class_db.h"
  95. #include "summator.h"
  96. void register_summator_types() {
  97. ClassDB::register_class<Summator>();
  98. }
  99. void unregister_summator_types() {
  100. //nothing to do here
  101. }
  102. Next, we need to create a ``SCsub`` file so the build system compiles
  103. this module:
  104. .. code:: python
  105. # SCsub
  106. Import('env')
  107. env.add_source_files(env.modules_sources,"*.cpp") # just add all cpp files to the build
  108. With multiple sources, you can also add each file individually to a Python
  109. string list:
  110. .. code:: python
  111. src_list = ["summator.cpp", "other.cpp", "etc.cpp"]
  112. env.add_source_files(env.modules_sources, src_list)
  113. This allows for powerful possibilities using Python to contruct the file list
  114. using loops and logic statements. Look at some of the other modules that ship
  115. with Godot by default for examples.
  116. To add include directories for the compiler to look at you can append it to the
  117. environment's paths:
  118. .. code:: python
  119. env.Append(CPPPATH="mylib/include") # this is a relative path
  120. env.Append(CPPPATH="#myotherlib/include") # this is an 'absolute' path
  121. If you want to add custom compiler flags when building your module, you need to clone
  122. `env` first, so it won't add those flags to whole Godot build (which can cause errors).
  123. Example `SCsub` with custom flags:
  124. .. code:: python
  125. # SCsub
  126. Import('env')
  127. module_env = env.Clone()
  128. module_env.add_source_files(env.modules_sources,"*.cpp")
  129. module_env.Append(CXXFLAGS=['-O2', '-std=c++11'])
  130. And finally, the configuration file for the module, this is a simple
  131. python script that must be named ``config.py``:
  132. .. code:: python
  133. # config.py
  134. def can_build(platform):
  135. return True
  136. def configure(env):
  137. pass
  138. The module is asked if it's ok to build for the specific platform (in
  139. this case, True means it will build for every platform).
  140. And that's it. Hope it was not too complex! Your module should look like
  141. this:
  142. ::
  143. godot/modules/summator/config.py
  144. godot/modules/summator/summator.h
  145. godot/modules/summator/summator.cpp
  146. godot/modules/summator/register_types.h
  147. godot/modules/summator/register_types.cpp
  148. godot/modules/summator/SCsub
  149. You can then zip it and share the module with everyone else. When
  150. building for every platform (instructions in the previous sections),
  151. your module will be included.
  152. Using the module
  153. ----------------
  154. Using your newly created module is very easy, from any script you can
  155. now do:
  156. ::
  157. var s = Summator.new()
  158. s.add(10)
  159. s.add(20)
  160. s.add(30)
  161. print(s.get_total())
  162. s.reset()
  163. And the output will be ``60``.
  164. Improving the build system for development
  165. ------------------------------------------
  166. So far we defined a clean and simple SCsub that allows us to add the sources
  167. of our new module as part of the Godot binary.
  168. This static approach is fine when we want to build a release version of our
  169. game given we want all the modules in a single binary.
  170. However the trade-of is every single change means a full recompilation of the
  171. game. Even if SCons is able to detect and recompile only the file that have
  172. changed, finding such files and eventually linking the final binary is a
  173. long and costly part.
  174. The solution to avoid such a cost is to build our own module as a shared
  175. library that will be dynamically loaded when starting our game's binary.
  176. .. code:: python
  177. # SCsub
  178. Import('env')
  179. sources = [
  180. "register_types.cpp",
  181. "summator.cpp"
  182. ]
  183. # First, create a custom env for the shared library.
  184. module_env = env.Clone()
  185. module_env.Append(CXXFLAGS='-fPIC') # Needed to compile shared library
  186. # We don't want godot's dependencies to be injected into our shared library.
  187. module_env['LIBS'] = []
  188. # Now define the shared library. Note that by default it would be built
  189. # into the module's folder, however it's better to output it into `bin`
  190. # next to the godot binary.
  191. shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
  192. # Finally notify the main env it has our shared lirary as a new dependency.
  193. # To do so, SCons wants the name of the lib with it custom suffixes
  194. # (e.g. ".x11.tools.64") but without the final ".so".
  195. # We pass this along with the directory of our library to the main env.
  196. shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
  197. env.Append(LIBS=[shared_lib_shim])
  198. env.Append(LIBPATH=['#bin'])
  199. Once compiled, we should end up with a ``bin`` directory containing both the
  200. ``godot*`` binary and our ``libsummator*.so``. However given the .so is not in
  201. a standard directory (like ``/usr/lib``), we have to help our binary find it
  202. during runtime with the ``LD_LIBRARY_PATH`` environ variable:
  203. ::
  204. user@host:~/godot$ export LD_LIBRARY_PATH=`pwd`/bin/
  205. user@host:~/godot$ ./bin/godot*
  206. **note**: Pay attention you have to ``export`` the environ variable otherwise
  207. you won't be able to play you project from within the editor.
  208. On top of that, it would be nice to be able to select whether to compile our
  209. module as shared library (for development) or as a part of the godot binary
  210. (for release). To do that we can define a custom flag to be passed to SCons
  211. using the `ARGUMENT` command:
  212. .. code:: python
  213. # SCsub
  214. Import('env')
  215. sources = [
  216. "register_types.cpp",
  217. "summator.cpp"
  218. ]
  219. module_env = env.Clone()
  220. module_env.Append(CXXFLAGS=['-O2', '-std=c++11'])
  221. if ARGUMENTS.get('summator_shared', 'no') == 'yes':
  222. # Shared lib compilation
  223. module_env.Append(CXXFLAGS='-fPIC')
  224. module_env['LIBS'] = []
  225. shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
  226. shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
  227. env.Append(LIBS=[shared_lib_shim])
  228. env.Append(LIBPATH=['#bin'])
  229. else:
  230. # Static compilation
  231. module_env.add_source_files(env.modules_sources, sources)
  232. Now by default ``scons`` command will build our module as part of godot's binary
  233. and as a shared library when passing ``summator_shared=yes``.
  234. Finally you can even speedup build further by explicitly specifying your
  235. shared module as target in the scons command:
  236. ::
  237. user@host:~/godot$ scons summator_shared=yes bin/summator.x11.tools.64.so
  238. Summing up
  239. ----------
  240. As you see, it's really easy to develop Godot in C++. Just write your
  241. stuff normally and remember to:
  242. - use ``OBJ_TYPE`` macro for inheritance, so Godot can wrap it
  243. - use ``_bind_methods`` to bind your functions to scripting, and to
  244. allow them to work as callbacks for signals.
  245. But this is not all, depending what you do, you will be greeted with
  246. some surprises.
  247. - If you inherit from :ref:`class_Node` (or any derived node type, such as
  248. Sprite), your new class will appear in the editor, in the inheritance
  249. tree in the "Add Node" dialog.
  250. - If you inherit from :ref:`class_Resource`, it will appear in the resource
  251. list, and all the exposed properties can be serialized when
  252. saved/loaded.
  253. - By this same logic, you can extend the Editor and almost any area of
  254. the engine.