gdnative-cpp-example.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. .. _doc_gdnative_cpp_example:
  2. GDNative C++ example
  3. ====================
  4. Introduction
  5. ------------
  6. This tutorial builds on top of the information given in the
  7. :ref:`GDNative C example <doc_gdnative_c_example>`, so we highly
  8. recommend you read that first.
  9. The C++ bindings for GDNative are built on top of the
  10. NativeScript GDNative API and provide a nicer way to "extend" nodes
  11. in Godot using C++. This is equivalent to writing scripts in GDScript,
  12. but in C++ instead.
  13. We'll be looking at NativeScript 1.0 which is available in Godot 3.0.
  14. Godot 3.1 will see the introduction of NativeScript 1.1, which comes with a
  15. number of improvements. We'll update this tutorial once it is
  16. officially released, but the overall structure remains similar.
  17. You can download the full example we'll be creating in this tutorial
  18. `on GitHub <https://github.com/BastiaanOlij/gdnative_cpp_example>`_.
  19. Setting up the project
  20. ----------------------
  21. There are a few prerequisites you'll need:
  22. - a Godot 3.x executable,
  23. - a C++ compiler,
  24. - SCons as a build tool,
  25. - a copy of the `godot_headers repository <https://github.com/GodotNativeTools/godot_headers>`_,
  26. - a copy of the `godot-cpp repository <https://github.com/GodotNativeTools/godot-cpp>`_.
  27. See also :ref:`Compiling <toc-devel-compiling>` as the build tools are identical
  28. to the ones you need to compile Godot from source.
  29. You can download these repositories from GitHub or let Git
  30. do the work for you. If you are versioning your project using Git,
  31. it is a good idea to add them as Git submodules:
  32. .. code-block:: none
  33. mkdir gdnative_cpp_example
  34. cd gdnative_cpp_example
  35. git init
  36. git submodule add https://github.com/GodotNativeTools/godot_headers
  37. git submodule add https://github.com/GodotNativeTools/godot-cpp
  38. If you decide to just download the repositories or clone them
  39. into your project folder, make sure to keep the folder layout identical
  40. to the one described here, as much of the code we'll be showcasing here
  41. assumes the project follows this layout.
  42. If you cloned the example from the link specified in
  43. the introduction, the submodules are not automatically initialized.
  44. You will need to execute the following commands:
  45. .. code-block:: none
  46. cd gdnative_cpp_example
  47. git submodule --init update
  48. This will clone these two repositories into your project folder.
  49. Building the C++ bindings
  50. -------------------------
  51. Now that we've downloaded our prerequisites, it is time to build
  52. the C++ bindings.
  53. The repository contains a copy of the metadata for the current Godot release,
  54. but if you need to build these bindings for a newer version of Godot,
  55. simply call the Godot executable:
  56. .. code-block:: none
  57. godot --gdnative-generate-json-api godot_api.json
  58. Place the resulting ``godot_api.json`` file in the ``godot-cpp/`` folder.
  59. To generate and compile the bindings, use this command (replacing
  60. ``<platform>`` with ``windows``, ``x11`` or ``osx`` depending on your OS):
  61. .. code-block:: none
  62. cd godot-cpp
  63. scons platform=<platform> headers=../godot_headers generate_bindings=yes
  64. cd ..
  65. This step will take a while. When it is completed, you should have static
  66. libraries that can be compiled into your project stored in ``godot-cpp/bin/``.
  67. At some point in the future, compiled binaries will be available,
  68. making this step optional.
  69. Creating a simple plugin
  70. ------------------------
  71. Now it's time to build an actual plugin. We'll start by creating an
  72. empty Godot project in which we'll place a few files.
  73. Open Godot and create a new project. For this example, we will place it
  74. in a folder called ``demo`` inside our GDNative module's folder structure.
  75. In our demo project, we'll create a scene containing a Node called "Main"
  76. and we'll save it as ``main.tscn``. We'll come back to that later.
  77. Back in the top-level GDNative module folder, we're also going to create
  78. a subfolder called ``src`` in which we'll place our source files.
  79. You should now have ``demo``, ``godot-cpp``, ``godot_headers``,
  80. and ``src`` directories in your GDNative module.
  81. In the ``src`` folder, we'll start with creating our header file
  82. for the GDNative node we'll be creating. We will name it ``gdexample.h``:
  83. .. code:: C++
  84. #ifndef GDEXAMPLE_H
  85. #define GDEXAMPLE_H
  86. #include <Godot.hpp>
  87. #include <Sprite.hpp>
  88. namespace godot {
  89. class gdexample : public godot::GodotScript<Sprite> {
  90. GODOT_CLASS(gdexample)
  91. private:
  92. float time_passed;
  93. public:
  94. static void _register_methods();
  95. gdexample();
  96. ~gdexample();
  97. void _process(float delta);
  98. };
  99. }
  100. #endif
  101. There are a few things of note to the above.
  102. We're including ``Godot.hpp`` which contains all our basic definitions.
  103. After that, we include ``Sprite.hpp`` which contains bindings
  104. to the Sprite class. We'll be extending this class in our module.
  105. We're using the namespace ``godot``, since everything in GDNative
  106. is defined within this namespace.
  107. Then we have our class definition, which inherits from our Sprite
  108. through a container class. We'll see a few side effects of this later on.
  109. This is also the main bit that is going to improve in NativeScript 1.1.
  110. The ``GODOT_CLASS`` macro sets up a few internal things for us.
  111. After that, we declare a single member variable called ``time_passed``.
  112. In the next block we're defining our methods, we obviously have
  113. our constructor and destructor defined, but there are two other
  114. functions that will likely look familiar to some.
  115. The first is ``_register_methods``, which is a static function that Godot
  116. will call to find out which methods can be called on our NativeScript
  117. and which properties it exposes. The second is our ``_process`` function,
  118. which will work exactly the same as the ``_process`` function
  119. you're used to in GDScript.
  120. So, let's implement our functions by creating our ``gdexample.cpp`` file:
  121. .. code:: C++
  122. #include "gdexample.h"
  123. using namespace godot;
  124. void gdexample::_register_methods() {
  125. register_method((char *)"_process", &gdexample::_process);
  126. }
  127. gdexample::gdexample() {
  128. // Initialize any variables here
  129. time_passed = 0.0;
  130. }
  131. gdexample::~gdexample() {
  132. // Add your cleanup procedure here
  133. }
  134. void gdexample::_process(float delta) {
  135. time_passed += delta;
  136. Vector2 new_position = Vector2(10.0 + (10.0 * sin(time_passed * 2.0)), 10.0 + (10.0 * cos(time_passed * 1.5)));
  137. owner->set_position(new_position);
  138. }
  139. This one should be straightforward. We're implementing each method of
  140. our class that we defined in our header file.
  141. Note that the ``register_method`` call **must** expose the ``_process`` method,
  142. otherwise Godot will not be able to use it. However, we do not have to tell Godot
  143. about our constructor and destructor.
  144. The other method of note is our ``_process`` function, which simply keeps track
  145. of how much time has passed and calculates a new position for our sprite
  146. using a simple sine and cosine function.
  147. What stands out is calling ``owner->set_position`` to call one of the build
  148. in methods of our Sprite. This is because our class is a container class;
  149. ``owner`` points to the actual Sprite node our script relates to.
  150. In the upcoming NativeScript 1.1, ``set_position`` can be called
  151. directly on our class.
  152. There is one more C++ file we need; we'll name it ``gdlibrary.cpp``.
  153. Our GDNative plugin can contain multiple NativeScripts, each with their
  154. own header and source file like we've implemented ``gdexample`` up above.
  155. What we need now is a small bit of code that tells Godot about all the
  156. NativeScripts in our GDNative plugin.
  157. .. code:: C++
  158. #include "gdexample.h"
  159. extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
  160. godot::Godot::gdnative_init(o);
  161. }
  162. extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
  163. godot::Godot::gdnative_terminate(o);
  164. }
  165. extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
  166. godot::Godot::nativescript_init(handle);
  167. godot::register_class<godot::gdexample>();
  168. }
  169. Note that we are not using the ``godot`` namespace here, since the
  170. three functions implemented here need to be defined without a namespace.
  171. The ``godot_gdnative_init`` and ``godot_gdnative_terminate`` functions
  172. get called respectively when Godot loads our plugin and when it unloads it.
  173. All we're doing here is parse through the functions in our bindings module
  174. to initialize them, but you might have to set up more things depending
  175. on your needs.
  176. The important function is the third function called
  177. ``godot_nativescript_init``. We first call a function in our bindings
  178. library that does its usual stuff. After that, we call the function
  179. ``register_class`` for each of our classes in our library.
  180. Compiling the plugin
  181. --------------------
  182. We cannot easily write by hand a ``SConstruct`` file that SCons would
  183. use for building. For the purpose of this example, just use
  184. :download:`this hardcoded SConstruct file <files/cpp_example/SConstruct>`
  185. we've prepared. We'll cover a more customizable, detailed example on
  186. how to use these build files in a subsequent tutorial.
  187. Once you've downloaded the ``SConstruct`` file, place it in your
  188. GDNative module folder besides ``godot-cpp``, ``godot_headers``
  189. and ``demo``, then run:
  190. .. code-block:: none
  191. scons platform=<platform>
  192. You should now be able to find the module in ``demo/bin/<platform>``.
  193. **Note:** Here, we've compiled both godot-cpp and our gdexample library
  194. as debug builds. For optimized builds, you should compile them using
  195. the ``target=release`` switch.
  196. Using the GDNative module
  197. -------------------------
  198. Before we jump back into Godot, we need to create two more files
  199. in ``demo/bin/``. Both can be created using the Godot editor,
  200. but it may be faster to create them directly.
  201. The first one is a file that lets Godot know what dynamic libraries
  202. should be loaded for each platform and is called ``gdexample.gdnlib``.
  203. .. code-block:: none
  204. [general]
  205. singleton=false
  206. load_once=true
  207. symbol_prefix="godot_"
  208. [entry]
  209. X11.64="res://bin/x11/libgdexample.so"
  210. Windows.64="res://bin/win64/libgdexample.dll"
  211. OSX.64="res://bin/osx/libgdexample.dylib"
  212. [dependencies]
  213. X11.64=[]
  214. Windows.64=[]
  215. OSX.64=[]
  216. This file contains a ``general`` section that controls how the module is loaded.
  217. It also contains a prefix section which should be left on ``godot_`` for now.
  218. If you change this, you'll need to rename various functions that are
  219. used as entry points. This was added for the iPhone platform because it doesn't
  220. allow dynamic libraries to be deployed, yet GDNative modules
  221. are linked statically.
  222. The ``entry`` section is the important bit: it tells Godot the location of
  223. the dynamic library in the project's filesystem for each supported platform.
  224. It will also result in *just* that file being exported when you export the
  225. project, which means the data pack won't contain libraries that are
  226. incompatible with the target platform.
  227. Finally, the ``dependencies`` section allows you to name additional
  228. dynamic libraries that should be included as well. This is important when
  229. your GDNative plugin implements someone else's library and requires you
  230. to supply a third-party dynamic library with your project.
  231. If you double click on the ``gdexample.gdnlib`` file within Godot,
  232. you'll see there are far more options to set:
  233. .. image:: img/gdnative_library.png
  234. The second file we need to create is a file used by each NativeScript
  235. we've added to our plugin. We'll name it ``gdexample.gdns`` for our
  236. gdexample NativeScript.
  237. .. code-block:: none
  238. [gd_resource type="NativeScript" load_steps=2 format=2]
  239. [ext_resource path="res://bin/gdexample.gdnlib" type="GDNativeLibrary" id=1]
  240. [resource]
  241. resource_name = "gdexample"
  242. class_name = "gdexample"
  243. library = ExtResource( 1 )
  244. _sections_unfolded = [ "Resource" ]
  245. This is a standard Godot resource; you could just create it directly
  246. in of your scene, but saving it to a file makes it much easier to reuse it
  247. in other places. This resource points to our gdnlib file, so that Godot
  248. can know which dynamic library contains our NativeScript. It also defines
  249. the ``class_name`` which identifies the NativeScript in our plugin
  250. we want to use.
  251. Time to jump back into Godot. We load up the main scene we created way back
  252. in the beginning and now add a Sprite to our scene:
  253. .. image:: img/gdnative_cpp_nodes.png
  254. We're going to assign the Godot logo to this sprite as our texture,
  255. disable the ``centered`` property and drag our ``gdexample.gdns`` file
  256. onto the ``script`` property of the sprite:
  257. .. image:: img/gdnative_cpp_sprite.png
  258. We're finally ready to run the project:
  259. .. image:: img/gdnative_cpp_animated.gif
  260. Next steps
  261. ----------
  262. The above is only a simple example, but we hope it shows you the basics.
  263. You can build upon this example to create full-fledged scripts to control
  264. nodes in Godot using C++.
  265. You should be able to edit and recompile the plugin while the Godot editor
  266. remains open; just rerun the project after the library has finished building.