custom_modules_in_cpp.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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, dozens of modules are enabled, 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. 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 be 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 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 to Godot.
  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 :ref:`download the source code of Godot
  29. and compile it <toc-devel-compiling>`.
  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" (``godot/modules/summator``).
  34. Inside we will create a summator class:
  35. .. code-block:: cpp
  36. /* summator.h */
  37. #ifndef SUMMATOR_H
  38. #define SUMMATOR_H
  39. #include "core/object/ref_counted.h"
  40. class Summator : public RefCounted {
  41. GDCLASS(Summator, RefCounted);
  42. int count;
  43. protected:
  44. static void _bind_methods();
  45. public:
  46. void add(int p_value);
  47. void reset();
  48. int get_total() const;
  49. Summator();
  50. };
  51. #endif // SUMMATOR_H
  52. And then the cpp file.
  53. .. code-block:: cpp
  54. /* summator.cpp */
  55. #include "summator.h"
  56. void Summator::add(int p_value) {
  57. count += p_value;
  58. }
  59. void Summator::reset() {
  60. count = 0;
  61. }
  62. int Summator::get_total() const {
  63. return count;
  64. }
  65. void Summator::_bind_methods() {
  66. ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add);
  67. ClassDB::bind_method(D_METHOD("reset"), &Summator::reset);
  68. ClassDB::bind_method(D_METHOD("get_total"), &Summator::get_total);
  69. }
  70. Summator::Summator() {
  71. count = 0;
  72. }
  73. Then, the new class needs to be registered somehow, so two more files
  74. need to be created:
  75. .. code-block:: none
  76. register_types.h
  77. register_types.cpp
  78. .. important::
  79. These files must be in the top-level folder of your module (next to your
  80. ``SCsub`` and ``config.py`` files) for the module to be registered properly.
  81. These files should contain the following:
  82. .. code-block:: cpp
  83. /* register_types.h */
  84. #include "modules/register_module_types.h"
  85. void initialize_summator_module(ModuleInitializationLevel p_level);
  86. void uninitialize_summator_module(ModuleInitializationLevel p_level);
  87. /* yes, the word in the middle must be the same as the module folder name */
  88. .. code-block:: cpp
  89. /* register_types.cpp */
  90. #include "register_types.h"
  91. #include "core/object/class_db.h"
  92. #include "summator.h"
  93. void initialize_summator_module(ModuleInitializationLevel p_level) {
  94. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  95. return;
  96. }
  97. ClassDB::register_class<Summator>();
  98. }
  99. void uninitialize_summator_module(ModuleInitializationLevel p_level) {
  100. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  101. return;
  102. }
  103. // Nothing to do here in this example.
  104. }
  105. Next, we need to create a ``SCsub`` file so the build system compiles
  106. this module:
  107. .. code-block:: python
  108. # SCsub
  109. Import('env')
  110. env.add_source_files(env.modules_sources, "*.cpp") # Add all cpp files to the build
  111. With multiple sources, you can also add each file individually to a Python
  112. string list:
  113. .. code-block:: python
  114. src_list = ["summator.cpp", "other.cpp", "etc.cpp"]
  115. env.add_source_files(env.modules_sources, src_list)
  116. This allows for powerful possibilities using Python to construct the file list
  117. using loops and logic statements. Look at some modules that ship with Godot by
  118. default for examples.
  119. To add include directories for the compiler to look at you can append it to the
  120. environment's paths:
  121. .. code-block:: python
  122. env.Append(CPPPATH=["mylib/include"]) # this is a relative path
  123. env.Append(CPPPATH=["#myotherlib/include"]) # this is an 'absolute' path
  124. If you want to add custom compiler flags when building your module, you need to clone
  125. ``env`` first, so it won't add those flags to whole Godot build (which can cause errors).
  126. Example ``SCsub`` with custom flags:
  127. .. code-block:: python
  128. # SCsub
  129. Import('env')
  130. module_env = env.Clone()
  131. module_env.add_source_files(env.modules_sources, "*.cpp")
  132. # Append CCFLAGS flags for both C and C++ code.
  133. module_env.Append(CCFLAGS=['-O2'])
  134. # If you need to, you can:
  135. # - Append CFLAGS for C code only.
  136. # - Append CXXFLAGS for C++ code only.
  137. And finally, the configuration file for the module, this is a
  138. Python script that must be named ``config.py``:
  139. .. code-block:: python
  140. # config.py
  141. def can_build(env, platform):
  142. return True
  143. def configure(env):
  144. pass
  145. The module is asked if it's OK to build for the specific platform (in
  146. this case, ``True`` means it will build for every platform).
  147. And that's it. Hope it was not too complex! Your module should look like
  148. this:
  149. .. code-block:: none
  150. godot/modules/summator/config.py
  151. godot/modules/summator/summator.h
  152. godot/modules/summator/summator.cpp
  153. godot/modules/summator/register_types.h
  154. godot/modules/summator/register_types.cpp
  155. godot/modules/summator/SCsub
  156. You can then zip it and share the module with everyone else. When
  157. building for every platform (instructions in the previous sections),
  158. your module will be included.
  159. .. note:: There is a parameter limit of 5 in C++ modules for things such
  160. as subclasses. This can be raised to 13 by including the header
  161. file ``core/method_bind_ext.gen.inc``.
  162. Using the module
  163. ----------------
  164. You can now use your newly created module from any script:
  165. .. tabs::
  166. .. code-tab:: gdscript GDScript
  167. var s = Summator.new()
  168. s.add(10)
  169. s.add(20)
  170. s.add(30)
  171. print(s.get_total())
  172. s.reset()
  173. The output will be ``60``.
  174. .. seealso:: The previous Summator example is great for small, custom modules,
  175. but what if you want to use a larger, external library? Refer to
  176. :ref:`doc_binding_to_external_libraries` for details about binding to
  177. external libraries.
  178. .. warning:: If your module is meant to be accessed from the running project
  179. (not just from the editor), you must also recompile every export
  180. template you plan to use, then specify the path to the custom
  181. template in each export preset. Otherwise, you'll get errors when
  182. running the project as the module isn't compiled in the export
  183. template. See the :ref:`Compiling <toc-devel-compiling>` pages
  184. for more information.
  185. Compiling a module externally
  186. -----------------------------
  187. Compiling a module involves moving the module's sources directly under the
  188. engine's ``modules/`` directory. While this is the most straightforward way to
  189. compile a module, there are a couple of reasons as to why this might not be a
  190. practical thing to do:
  191. 1. Having to manually copy modules sources every time you want to compile the
  192. engine with or without the module, or taking additional steps needed to
  193. manually disable a module during compilation with a build option similar to
  194. ``module_summator_enabled=no``. Creating symbolic links may also be a solution,
  195. but you may additionally need to overcome OS restrictions like needing the
  196. symbolic link privilege if doing this via script.
  197. 2. Depending on whether you have to work with the engine's source code, the
  198. module files added directly to ``modules/`` changes the working tree to the
  199. point where using a VCS (like ``git``) proves to be cumbersome as you need to
  200. make sure that only the engine-related code is committed by filtering
  201. changes.
  202. So if you feel like the independent structure of custom modules is needed, lets
  203. take our "summator" module and move it to the engine's parent directory:
  204. .. code-block:: shell
  205. mkdir ../modules
  206. mv modules/summator ../modules
  207. Compile the engine with our module by providing ``custom_modules`` build option
  208. which accepts a comma-separated list of directory paths containing custom C++
  209. modules, similar to the following:
  210. .. code-block:: shell
  211. scons custom_modules=../modules
  212. The build system shall detect all modules under the ``../modules`` directory
  213. and compile them accordingly, including our "summator" module.
  214. .. warning::
  215. Any path passed to ``custom_modules`` will be converted to an absolute path
  216. internally as a way to distinguish between custom and built-in modules. It
  217. means that things like generating module documentation may rely on a
  218. specific path structure on your machine.
  219. .. seealso::
  220. :ref:`Introduction to the buildsystem - Custom modules build option <doc_buildsystem_custom_modules>`.
  221. Customizing module types initialization
  222. ---------------------------------------
  223. Modules can interact with other built-in engine classes during runtime and even
  224. affect the way core types are initialized. So far, we've been using
  225. ``register_summator_types`` as a way to bring in module classes to be available
  226. within the engine.
  227. A crude order of the engine setup can be summarized as a list of the following
  228. type registration methods:
  229. .. code-block:: cpp
  230. preregister_module_types();
  231. preregister_server_types();
  232. register_core_singletons();
  233. register_server_types();
  234. register_scene_types();
  235. EditorNode::register_editor_types();
  236. register_platform_apis();
  237. register_module_types();
  238. initialize_physics();
  239. initialize_navigation_server();
  240. register_server_singletons();
  241. register_driver_types();
  242. ScriptServer::init_languages();
  243. Our ``Summator`` class is initialized during the ``register_module_types()``
  244. call. Imagine that we need to satisfy some common module run-time dependency
  245. (like singletons), or allow us to override existing engine method callbacks
  246. before they can be assigned by the engine itself. In that case, we want to
  247. ensure that our module classes are registered *before* any other built-in type.
  248. This is where we can define an optional ``preregister_summator_types()``
  249. method which will be called before anything else during the
  250. ``preregister_module_types()`` engine setup stage.
  251. We now need to add this method to ``register_types`` header and source files:
  252. .. code-block:: cpp
  253. /* register_types.h */
  254. #define MODULE_SUMMATOR_HAS_PREREGISTER
  255. void preregister_summator_types();
  256. void register_summator_types();
  257. void unregister_summator_types();
  258. .. note:: Unlike other register methods, we have to explicitly define
  259. ``MODULE_SUMMATOR_HAS_PREREGISTER`` to let the build system know what
  260. relevant method calls to include at compile time. The module's name
  261. has to be converted to uppercase as well.
  262. .. code-block:: cpp
  263. /* register_types.cpp */
  264. #include "register_types.h"
  265. #include "core/object/class_db.h"
  266. #include "summator.h"
  267. void preregister_summator_types() {
  268. // Called before any other core types are registered.
  269. // Nothing to do here in this example.
  270. }
  271. void register_summator_types() {
  272. ClassDB::register_class<Summator>();
  273. }
  274. void unregister_summator_types() {
  275. // Nothing to do here in this example.
  276. }
  277. Improving the build system for development
  278. ------------------------------------------
  279. .. warning::
  280. This shared library support is not designed to support distributing a module
  281. to other users without recompiling the engine. For that purpose, use
  282. :ref:`GDNative <doc_what_is_gdnative>` instead.
  283. So far, we defined a clean SCsub that allows us to add the sources
  284. of our new module as part of the Godot binary.
  285. This static approach is fine when we want to build a release version of our
  286. game, given we want all the modules in a single binary.
  287. However, the trade-off is that every single change requires a full recompilation of the
  288. game. Even though SCons is able to detect and recompile only the file that was
  289. changed, finding such files and eventually linking the final binary takes a long time.
  290. The solution to avoid such a cost is to build our own module as a shared
  291. library that will be dynamically loaded when starting our game's binary.
  292. .. code-block:: python
  293. # SCsub
  294. Import('env')
  295. sources = [
  296. "register_types.cpp",
  297. "summator.cpp"
  298. ]
  299. # First, create a custom env for the shared library.
  300. module_env = env.Clone()
  301. # Position-independent code is required for a shared library.
  302. module_env.Append(CCFLAGS=['-fPIC'])
  303. # Don't inject Godot's dependencies into our shared library.
  304. module_env['LIBS'] = []
  305. # Define the shared library. By default, it would be built in the module's
  306. # folder, however it's better to output it into `bin` next to the
  307. # Godot binary.
  308. shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
  309. # Finally, notify the main build environment it now has our shared library
  310. # as a new dependency.
  311. # LIBPATH and LIBS need to be set on the real "env" (not the clone)
  312. # to link the specified libraries to the Godot executable.
  313. env.Append(LIBPATH=['#bin'])
  314. # SCons wants the name of the library with it custom suffixes
  315. # (e.g. ".linuxbsd.tools.64") but without the final ".so".
  316. shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
  317. env.Append(LIBS=[shared_lib_shim])
  318. Once compiled, we should end up with a ``bin`` directory containing both the
  319. ``godot*`` binary and our ``libsummator*.so``. However given the .so is not in
  320. a standard directory (like ``/usr/lib``), we have to help our binary find it
  321. during runtime with the ``LD_LIBRARY_PATH`` environment variable:
  322. .. code-block:: shell
  323. export LD_LIBRARY_PATH="$PWD/bin/"
  324. ./bin/godot*
  325. .. note::
  326. You have to ``export`` the environment variable. Otherwise,
  327. you won't be able to run your project from the editor.
  328. On top of that, it would be nice to be able to select whether to compile our
  329. module as shared library (for development) or as a part of the Godot binary
  330. (for release). To do that we can define a custom flag to be passed to SCons
  331. using the ``ARGUMENT`` command:
  332. .. code-block:: python
  333. # SCsub
  334. Import('env')
  335. sources = [
  336. "register_types.cpp",
  337. "summator.cpp"
  338. ]
  339. module_env = env.Clone()
  340. module_env.Append(CCFLAGS=['-O2'])
  341. if ARGUMENTS.get('summator_shared', 'no') == 'yes':
  342. # Shared lib compilation
  343. module_env.Append(CCFLAGS=['-fPIC'])
  344. module_env['LIBS'] = []
  345. shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
  346. shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
  347. env.Append(LIBS=[shared_lib_shim])
  348. env.Append(LIBPATH=['#bin'])
  349. else:
  350. # Static compilation
  351. module_env.add_source_files(env.modules_sources, sources)
  352. Now by default ``scons`` command will build our module as part of Godot's binary
  353. and as a shared library when passing ``summator_shared=yes``.
  354. Finally, you can even speed up the build further by explicitly specifying your
  355. shared module as target in the SCons command:
  356. .. code-block:: shell
  357. scons summator_shared=yes platform=linuxbsd bin/libsummator.linuxbsd.tools.64.so
  358. Writing custom documentation
  359. ----------------------------
  360. Writing documentation may seem like a boring task, but it is highly recommended
  361. to document your newly created module to make it easier for users to benefit
  362. from it. Not to mention that the code you've written one year ago may become
  363. indistinguishable from the code that was written by someone else, so be kind to
  364. your future self!
  365. There are several steps in order to setup custom docs for the module:
  366. 1. Make a new directory in the root of the module. The directory name can be
  367. anything, but we'll be using the ``doc_classes`` name throughout this section.
  368. 2. Now, we need to edit ``config.py``, add the following snippet:
  369. .. code-block:: python
  370. def get_doc_path():
  371. return "doc_classes"
  372. def get_doc_classes():
  373. return [
  374. "Summator",
  375. ]
  376. The ``get_doc_path()`` function is used by the build system to determine
  377. the location of the docs. In this case, they will be located in the
  378. ``modules/summator/doc_classes`` directory. If you don't define this,
  379. the doc path for your module will fall back to the main ``doc/classes``
  380. directory.
  381. The ``get_doc_classes()`` method is necessary for the build system to
  382. know which registered classes belong to the module. You need to list all of your
  383. classes here. The classes that you don't list will end up in the
  384. main ``doc/classes`` directory.
  385. .. tip::
  386. You can use Git to check if you have missed some of your classes by checking the
  387. untracked files with ``git status``. For example::
  388. user@host:~/godot$ git status
  389. Example output::
  390. Untracked files:
  391. (use "git add <file>..." to include in what will be committed)
  392. doc/classes/MyClass2D.xml
  393. doc/classes/MyClass4D.xml
  394. doc/classes/MyClass5D.xml
  395. doc/classes/MyClass6D.xml
  396. ...
  397. 3. Now we can generate the documentation:
  398. We can do this via running Godot's doctool i.e. ``godot --doctool <path>``,
  399. which will dump the engine API reference to the given ``<path>`` in XML format.
  400. In our case we'll point it to the root of the cloned repository. You can point it
  401. to an another folder, and just copy over the files that you need.
  402. Run command:
  403. ::
  404. user@host:~/godot$ ./bin/<godot_binary> --doctool .
  405. Now if you go to the ``godot/modules/summator/doc_classes`` folder, you will see
  406. that it contains a ``Summator.xml`` file, or any other classes, that you referenced
  407. in your ``get_doc_classes`` function.
  408. Edit the file(s) following :ref:`doc_class_reference_writing_guidelines` and recompile the engine.
  409. Once the compilation process is finished, the docs will become accessible within
  410. the engine's built-in documentation system.
  411. In order to keep documentation up-to-date, all you'll have to do is simply modify
  412. one of the XML files and recompile the engine from now on.
  413. If you change your module's API, you can also re-extract the docs, they will contain
  414. the things that you previously added. Of course if you point it to your godot
  415. folder, make sure you don't lose work by extracting older docs from an older engine build
  416. on top of the newer ones.
  417. Note that if you don't have write access rights to your supplied ``<path>``,
  418. you might encounter an error similar to the following:
  419. .. code-block:: console
  420. ERROR: Can't write doc file: docs/doc/classes/@GDScript.xml
  421. At: editor/doc/doc_data.cpp:956
  422. .. _doc_custom_module_unit_tests:
  423. Writing custom unit tests
  424. -------------------------
  425. It's possible to write self-contained unit tests as part of a C++ module. If you
  426. are not familiar with the unit testing process in Godot yet, please refer to
  427. :ref:`doc_unit_testing`.
  428. The procedure is the following:
  429. 1. Create a new directory named ``tests/`` under your module's root:
  430. .. code-block:: console
  431. cd modules/summator
  432. mkdir tests
  433. cd tests
  434. 2. Create a new test suite: ``test_summator.h``. The header must be prefixed
  435. with ``test_`` so that the build system can collect it and include it as part
  436. of the ``tests/test_main.cpp`` where the tests are run.
  437. 3. Write some test cases. Here's an example:
  438. .. code-block:: cpp
  439. // test_summator.h
  440. #ifndef TEST_SUMMATOR_H
  441. #define TEST_SUMMATOR_H
  442. #include "tests/test_macros.h"
  443. #include "modules/summator/summator.h"
  444. namespace TestSummator {
  445. TEST_CASE("[Modules][Summator] Adding numbers") {
  446. Ref<Summator> s = memnew(Summator);
  447. CHECK(s->get_total() == 0);
  448. s->add(10);
  449. CHECK(s->get_total() == 10);
  450. s->add(20);
  451. CHECK(s->get_total() == 30);
  452. s->add(30);
  453. CHECK(s->get_total() == 60);
  454. s->reset();
  455. CHECK(s->get_total() == 0);
  456. }
  457. } // namespace TestSummator
  458. #endif // TEST_SUMMATOR_H
  459. 4. Compile the engine with ``scons tests=yes``, and run the tests with the
  460. following command:
  461. .. code-block:: console
  462. ./bin/<godot_binary> --test --source-file="*test_summator*" --success
  463. You should see the passing assertions now.
  464. .. _doc_custom_module_icons:
  465. Adding custom editor icons
  466. --------------------------
  467. Similarly to how you can write self-contained documentation within a module,
  468. you can also create your own custom icons for classes to appear in the editor.
  469. For the actual process of creating editor icons to be integrated within the engine,
  470. please refer to :ref:`doc_editor_icons` first.
  471. Once you've created your icon(s), proceed with the following steps:
  472. 1. Make a new directory in the root of the module named ``icons``. This is the
  473. default path for the engine to look for module's editor icons.
  474. 2. Move your newly created ``svg`` icons (optimized or not) into that folder.
  475. 3. Recompile the engine and run the editor. Now the icon(s) will appear in
  476. editor's interface where appropriate.
  477. If you'd like to store your icons somewhere else within your module,
  478. add the following code snippet to ``config.py`` to override the default path:
  479. .. code-block:: python
  480. def get_icons_path():
  481. return "path/to/icons"
  482. Summing up
  483. ----------
  484. Remember to:
  485. - Use ``GDCLASS`` macro for inheritance, so Godot can wrap it.
  486. - Use ``_bind_methods`` to bind your functions to scripting, and to
  487. allow them to work as callbacks for signals.
  488. - **Avoid multiple inheritance for classes exposed to Godot**, as ``GDCLASS``
  489. doesn't support this. You can still use multiple inheritance in your own
  490. classes as long as they're not exposed to Godot's scripting API.
  491. But this is not all, depending what you do, you will be greeted with
  492. some (hopefully positive) surprises.
  493. - If you inherit from :ref:`class_Node` (or any derived node type, such as
  494. Sprite2D), your new class will appear in the editor, in the inheritance
  495. tree in the "Add Node" dialog.
  496. - If you inherit from :ref:`class_Resource`, it will appear in the resource
  497. list, and all the exposed properties can be serialized when
  498. saved/loaded.
  499. - By this same logic, you can extend the Editor and almost any area of
  500. the engine.