custom_modules_in_cpp.rst 10 KB

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