2
0

gdnative-cpp-example.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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 recommend you
  8. read that first.
  9. The C++ bindings for GDNative are built on top of the NativeScript GDNative API
  10. and provide a nicer way to "extend" nodes in Godot using C++. This is equivalent
  11. to writing scripts in GDScript, but in C++ instead.
  12. Godot 3.1 saw the introduction of the NativeScript 1.1 additions that enabled
  13. the GDNative team to build a nicer C++ bindings library. These changes have now
  14. been merged into the master branch and will be the way we go forward. If you
  15. want to write a C++ GDNative plugin that also supports Godot 3.0 you will need
  16. to use the 3.0 branch and the NativeScript 1.0 syntax. We'll be showing them
  17. side by side in this writeup.
  18. You can download the full example we'll be creating in this tutorial `on
  19. GitHub <https://github.com/BastiaanOlij/gdnative_cpp_example>`__.
  20. Setting up the project
  21. ----------------------
  22. There are a few prerequisites you'll need:
  23. - a Godot 3.x executable,
  24. - a C++ compiler,
  25. - SCons as a build tool,
  26. - a copy of the `godot-cpp
  27. repository <https://github.com/godotengine/godot-cpp>`__.
  28. See also :ref:`Compiling <toc-devel-compiling>` as the build tools are identical
  29. to the ones you need to compile Godot from source.
  30. You can download these repositories from GitHub or let Git do the work for you.
  31. Note that these repositories now have different branches for different versions
  32. of Godot. GDNative modules written for an earlier version of Godot will work in
  33. newer versions (with the exception of one breaking change in ARVR interfaces
  34. between 3.0 and 3.1) but not vice versa so make sure you download the correct
  35. branch. Also note that the version of Godot you use to generate the ``api.json``
  36. with becomes your minimum version.
  37. If you are versioning your project using Git, it is a good idea to add them as
  38. Git submodules:
  39. .. tabs::
  40. .. code-tab:: none Godot
  41. mkdir gdnative_cpp_example
  42. cd gdnative_cpp_example
  43. git init
  44. git submodule add https://github.com/godotengine/godot-cpp
  45. cd godot-cpp
  46. git submodule update --init
  47. .. code-tab:: none Godot 3.0
  48. mkdir gdnative_cpp_example
  49. cd gdnative_cpp_example
  50. git init
  51. git submodule add -b 3.0 https://github.com/godotengine/godot-cpp
  52. cd godot-cpp
  53. git submodule update --init
  54. If you decide to just download the repositories or clone them into your project
  55. folder, make sure to keep the folder layout identical to the one described here,
  56. as much of the code we'll be showcasing here assumes the project follows this
  57. layout.
  58. Do make sure you clone recursive to pull in both repositories:
  59. .. tabs::
  60. .. code-tab:: none Godot
  61. mkdir gdnative_cpp_example
  62. cd gdnative_cpp_example
  63. git clone --recursive https://github.com/godotengine/godot-cpp
  64. .. code-tab:: none Godot 3.0
  65. mkdir gdnative_cpp_example
  66. cd gdnative_cpp_example
  67. git clone --recursive -b 3.0 https://github.com/godotengine/godot-cpp
  68. .. note::
  69. ``godot-cpp`` now includes ``godot_headers`` as a nested submodule, if you've
  70. manually downloaded them please make sure to place ``godot_headers`` inside
  71. of the ``godot-cpp`` folder.
  72. You don't have to do it this way but we've found it easiest to manage. If you
  73. decide to just download the repositories or just clone them into your folder,
  74. make sure to keep the folder layout the same as we've setup here as much of
  75. the code we'll be showcasing here assumes the project has this layout.
  76. If you cloned the example from the link specified in the introduction, the
  77. submodules are not automatically initialized. You will need to execute the
  78. following commands:
  79. .. code-block:: none
  80. cd gdnative_cpp_example
  81. git submodule update --init --recursive
  82. This will clone these two repositories into your project folder.
  83. Building the C++ bindings
  84. -------------------------
  85. Now that we've downloaded our prerequisites, it is time to build the C++
  86. bindings.
  87. The repository contains a copy of the metadata for the current Godot release,
  88. but if you need to build these bindings for a newer version of Godot, simply
  89. call the Godot executable:
  90. .. code-block:: none
  91. godot --gdnative-generate-json-api api.json
  92. Place the resulting ``api.json`` file in the project folder and add
  93. ``use_custom_api_file=yes custom_api_file=../api.json`` to the scons command
  94. below.
  95. To generate and compile the bindings, use this command (replacing ``<platform>``
  96. with ``windows``, ``linux`` or ``osx`` depending on your OS):
  97. To speed up compilation, add `-jN` at the end of the SCons command line where `N` is the number of CPU threads you have on your system. The example below uses 4 threads.
  98. .. code-block:: none
  99. cd godot-cpp
  100. scons platform=<platform> generate_bindings=yes -j4
  101. cd ..
  102. This step will take a while. When it is completed, you should have static
  103. libraries that can be compiled into your project stored in ``godot-cpp/bin/``.
  104. At some point in the future, compiled binaries will be available, making this
  105. step optional.
  106. .. note::
  107. You may need to add ``bits=64`` to the command on Windows or Linux. We're
  108. still working on better auto detection.
  109. Creating a simple plugin
  110. ------------------------
  111. Now it's time to build an actual plugin. We'll start by creating an empty Godot
  112. project in which we'll place a few files.
  113. Open Godot and create a new project. For this example, we will place it in a
  114. folder called ``demo`` inside our GDNative module's folder structure.
  115. In our demo project, we'll create a scene containing a Node called "Main" and
  116. we'll save it as ``main.tscn``. We'll come back to that later.
  117. Back in the top-level GDNative module folder, we're also going to create a
  118. subfolder called ``src`` in which we'll place our source files.
  119. You should now have ``demo``, ``godot-cpp``, ``godot_headers``, and ``src``
  120. directories in your GDNative module.
  121. In the ``src`` folder, we'll start with creating our header file for the
  122. GDNative node we'll be creating. We will name it ``gdexample.h``:
  123. .. tabs::
  124. .. code-tab:: C++ NativeScript 1.1
  125. #ifndef GDEXAMPLE_H
  126. #define GDEXAMPLE_H
  127. #include <Godot.hpp>
  128. #include <Sprite.hpp>
  129. namespace godot {
  130. class GDExample : public Sprite {
  131. GODOT_CLASS(GDExample, Sprite)
  132. private:
  133. float time_passed;
  134. public:
  135. static void _register_methods();
  136. GDExample();
  137. ~GDExample();
  138. void _init(); // our initializer called by Godot
  139. void _process(float delta);
  140. };
  141. }
  142. #endif
  143. .. code-tab:: C++ NativeScript 1.0
  144. #ifndef GDEXAMPLE_H
  145. #define GDEXAMPLE_H
  146. #include <Godot.hpp>
  147. #include <Sprite.hpp>
  148. namespace godot {
  149. class GDExample : public godot::GodotScript<Sprite> {
  150. GODOT_CLASS(GDExample)
  151. private:
  152. float time_passed;
  153. public:
  154. static void _register_methods();
  155. GDExample();
  156. ~GDExample();
  157. void _process(float delta);
  158. };
  159. }
  160. #endif
  161. There are a few things of note to the above. We're including ``Godot.hpp`` which
  162. contains all our basic definitions. After that, we include ``Sprite.hpp`` which
  163. contains bindings to the Sprite class. We'll be extending this class in our
  164. module.
  165. We're using the namespace ``godot``, since everything in GDNative is defined
  166. within this namespace.
  167. Then we have our class definition, which inherits from our Sprite through a
  168. container class. We'll see a few side effects of this later on. The
  169. ``GODOT_CLASS`` macro sets up a few internal things for us.
  170. After that, we declare a single member variable called ``time_passed``.
  171. In the next block we're defining our methods, we obviously have our constructor
  172. and destructor defined, but there are two other functions that will likely look
  173. familiar to some, and one new method.
  174. The first is ``_register_methods``, which is a static function that Godot will
  175. call to find out which methods can be called on our NativeScript and which
  176. properties it exposes. The second is our ``_process`` function, which will work
  177. exactly the same as the ``_process`` function you're used to in GDScript. The
  178. third is our ``_init`` function which is called after Godot has properly set up
  179. our object. It has to exist even if you don't place any code in it.
  180. Let's implement our functions by creating our ``gdexample.cpp`` file:
  181. .. tabs::
  182. .. code-tab:: C++ NativeScript 1.1
  183. #include "gdexample.h"
  184. using namespace godot;
  185. void GDExample::_register_methods() {
  186. register_method("_process", &GDExample::_process);
  187. }
  188. GDExample::GDExample() {
  189. }
  190. GDExample::~GDExample() {
  191. // add your cleanup here
  192. }
  193. void GDExample::_init() {
  194. // initialize any variables here
  195. time_passed = 0.0;
  196. }
  197. void GDExample::_process(float delta) {
  198. time_passed += delta;
  199. Vector2 new_position = Vector2(10.0 + (10.0 * sin(time_passed * 2.0)), 10.0 + (10.0 * cos(time_passed * 1.5)));
  200. set_position(new_position);
  201. }
  202. .. code-tab:: C++ NativeScript 1.0
  203. #include "gdexample.h"
  204. using namespace godot;
  205. void GDExample::_register_methods() {
  206. register_method((char *)"_process", &GDExample::_process);
  207. }
  208. GDExample::GDExample() {
  209. // Initialize any variables here
  210. time_passed = 0.0;
  211. }
  212. GDExample::~GDExample() {
  213. // Add your cleanup procedure here
  214. }
  215. void GDExample::_process(float delta) {
  216. time_passed += delta;
  217. Vector2 new_position = Vector2(10.0 + (10.0 * sin(time_passed * 2.0)), 10.0 + (10.0 * cos(time_passed * 1.5)));
  218. owner->set_position(new_position);
  219. }
  220. This one should be straightforward. We're implementing each method of our class
  221. that we defined in our header file. Note that the ``register_method`` call
  222. **must** expose the ``_process`` method, otherwise Godot will not be able to use
  223. it. However, we do not have to tell Godot about our constructor, destructor and
  224. ``_init`` functions.
  225. The other method of note is our ``_process`` function, which simply keeps track
  226. of how much time has passed and calculates a new position for our sprite using a
  227. simple sine and cosine function. What stands out is calling
  228. ``owner->set_position`` to call one of the build in methods of our Sprite. This
  229. is because our class is a container class; ``owner`` points to the actual Sprite
  230. node our script relates to. In the upcoming NativeScript 1.1, ``set_position``
  231. can be called directly on our class.
  232. There is one more C++ file we need; we'll name it ``gdlibrary.cpp``. Our
  233. GDNative plugin can contain multiple NativeScripts, each with their own header
  234. and source file like we've implemented ``GDExample`` up above. What we need now
  235. is a small bit of code that tells Godot about all the NativeScripts in our
  236. GDNative plugin.
  237. .. code-block:: C++
  238. #include "gdexample.h"
  239. extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
  240. godot::Godot::gdnative_init(o);
  241. }
  242. extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
  243. godot::Godot::gdnative_terminate(o);
  244. }
  245. extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
  246. godot::Godot::nativescript_init(handle);
  247. godot::register_class<godot::GDExample>();
  248. }
  249. Note that we are not using the ``godot`` namespace here, since the three
  250. functions implemented here need to be defined without a namespace.
  251. The ``godot_gdnative_init`` and ``godot_gdnative_terminate`` functions get
  252. called respectively when Godot loads our plugin and when it unloads it. All
  253. we're doing here is parse through the functions in our bindings module to
  254. initialize them, but you might have to set up more things depending on your
  255. needs.
  256. The important function is the third function called ``godot_nativescript_init``.
  257. We first call a function in our bindings library that does its usual stuff.
  258. After that, we call the function ``register_class`` for each of our classes in
  259. our library.
  260. Compiling the plugin
  261. --------------------
  262. We cannot easily write by hand a ``SConstruct`` file that SCons would use for
  263. building. For the purpose of this example, just use
  264. :download:`this hardcoded SConstruct file <files/cpp_example/SConstruct>` we've
  265. prepared. We'll cover a more customizable, detailed example on how to use these
  266. build files in a subsequent tutorial.
  267. .. note::
  268. This ``SConstruct`` file was written to be used with the latest ``godot-cpp``
  269. master, you may need to make small changes using it with older versions or
  270. refer to the ``SConstruct`` file in the Godot 3.0 documentation.
  271. Once you've downloaded the ``SConstruct`` file, place it in your GDNative module
  272. folder besides ``godot-cpp``, ``godot_headers`` and ``demo``, then run:
  273. .. code-block:: none
  274. scons platform=<platform>
  275. You should now be able to find the module in ``demo/bin/<platform>``.
  276. .. note::
  277. Here, we've compiled both godot-cpp and our gdexample library as debug
  278. builds. For optimized builds, you should compile them using the
  279. ``target=release`` switch.
  280. Using the GDNative module
  281. -------------------------
  282. Before we jump back into Godot, we need to create two more files in
  283. ``demo/bin/``. Both can be created using the Godot editor, but it may be faster
  284. to create them directly.
  285. The first one is a file that lets Godot know what dynamic libraries should be
  286. loaded for each platform and is called ``gdexample.gdnlib``.
  287. .. code-block:: none
  288. [general]
  289. singleton=false
  290. load_once=true
  291. symbol_prefix="godot_"
  292. reloadable=false
  293. [entry]
  294. X11.64="res://bin/x11/libgdexample.so"
  295. Windows.64="res://bin/win64/libgdexample.dll"
  296. OSX.64="res://bin/osx/libgdexample.dylib"
  297. [dependencies]
  298. X11.64=[]
  299. Windows.64=[]
  300. OSX.64=[]
  301. This file contains a ``general`` section that controls how the module is loaded.
  302. It also contains a prefix section which should be left on ``godot_`` for now. If
  303. you change this, you'll need to rename various functions that are used as entry
  304. points. This was added for the iPhone platform because it doesn't allow dynamic
  305. libraries to be deployed, yet GDNative modules are linked statically.
  306. The ``entry`` section is the important bit: it tells Godot the location of the
  307. dynamic library in the project's filesystem for each supported platform. It will
  308. also result in *just* that file being exported when you export the project,
  309. which means the data pack won't contain libraries that are incompatible with the
  310. target platform.
  311. Finally, the ``dependencies`` section allows you to name additional dynamic
  312. libraries that should be included as well. This is important when your GDNative
  313. plugin implements someone else's library and requires you to supply a
  314. third-party dynamic library with your project.
  315. If you double click on the ``gdexample.gdnlib`` file within Godot, you'll see
  316. there are far more options to set:
  317. .. image:: img/gdnative_library.png
  318. The second file we need to create is a file used by each NativeScript we've
  319. added to our plugin. We'll name it ``gdexample.gdns`` for our gdexample
  320. NativeScript.
  321. .. code-block:: none
  322. [gd_resource type="NativeScript" load_steps=2 format=2]
  323. [ext_resource path="res://bin/gdexample.gdnlib" type="GDNativeLibrary" id=1]
  324. [resource]
  325. resource_name = "gdexample"
  326. class_name = "GDExample"
  327. library = ExtResource( 1 )
  328. This is a standard Godot resource; you could just create it directly in your
  329. scene, but saving it to a file makes it much easier to reuse it in other places.
  330. This resource points to our gdnlib file, so that Godot can know which dynamic
  331. library contains our NativeScript. It also defines the ``class_name`` which
  332. identifies the NativeScript in our plugin we want to use.
  333. Time to jump back into Godot. We load up the main scene we created way back in
  334. the beginning and now add a Sprite to our scene:
  335. .. image:: img/gdnative_cpp_nodes.png
  336. We're going to assign the Godot logo to this sprite as our texture, disable the
  337. ``centered`` property and drag our ``gdexample.gdns`` file onto the ``script``
  338. property of the sprite:
  339. .. image:: img/gdnative_cpp_sprite.png
  340. We're finally ready to run the project:
  341. .. image:: img/gdnative_cpp_animated.gif
  342. Adding properties
  343. -----------------
  344. GDScript allows you to add properties to your script using the ``export``
  345. keyword. In GDNative you have to register the properties and there are two ways
  346. of doing this. You can either bind directly to a member or use a setter and
  347. getter function.
  348. .. note::
  349. There is a third option, just like in GDScript you can directly implement the
  350. ``_get_property_list``, ``_get`` and ``_set`` methods of an object but that
  351. goes far beyond the scope of this tutorial.
  352. We'll examine both starting with the direct bind. Lets add a property that
  353. allows us to control the amplitude of our wave.
  354. In our ``gdexample.h`` file we simply need to add a member variable like so:
  355. .. code-block:: C++
  356. ...
  357. private:
  358. float time_passed;
  359. float amplitude;
  360. ...
  361. In our ``gdexample.cpp`` file we need to make a number of changes, we will only
  362. show the methods we end up changing, don't remove the lines we're omitting:
  363. .. tabs::
  364. .. code-tab:: C++ NativeScript 1.1
  365. void GDExample::_register_methods() {
  366. register_method("_process", &GDExample::_process);
  367. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  368. }
  369. void GDExample::_init() {
  370. // initialize any variables here
  371. time_passed = 0.0;
  372. amplitude = 10.0;
  373. }
  374. void GDExample::_process(float delta) {
  375. time_passed += delta;
  376. Vector2 new_position = Vector2(
  377. amplitude + (amplitude * sin(time_passed * 2.0)),
  378. amplitude + (amplitude * cos(time_passed * 1.5))
  379. );
  380. set_position(new_position);
  381. }
  382. .. code-tab:: C++ NativeScript 1.0
  383. void GDExample::_register_methods() {
  384. register_method((char *)"_process", &GDExample::_process);
  385. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  386. }
  387. GDExample::GDExample() {
  388. // initialize any variables here
  389. time_passed = 0.0;
  390. amplitude = 10.0;
  391. }
  392. void GDExample::_process(float delta) {
  393. time_passed += delta;
  394. Vector2 new_position = Vector2(
  395. amplitude + (amplitude * sin(time_passed * 2.0)),
  396. amplitude + (amplitude * cos(time_passed * 1.5))
  397. );
  398. owner->set_position(new_position);
  399. }
  400. Once you compile the module with these changes in place you will see that a
  401. property has been added to our interface. You can now change this property and
  402. when you run your project, you will see that our Godot icon travels along a
  403. larger figure.
  404. .. note::
  405. The ``reloadable`` property in the ``gdexample.gdnlib`` file must be set to
  406. ``true`` for the Godot editor to automatically pick up the newly added
  407. property.
  408. However, this setting should be used with care especially when tool classes
  409. are used, as the editor might hold objects then that have script instances
  410. attached to them that are managed by a GDNative library.
  411. Lets do the same but for the speed of our animation and use a setter and getter
  412. function. Our ``gdexample.h`` header file again only needs a few more lines of
  413. code:
  414. .. code-block:: C++
  415. ...
  416. float amplitude;
  417. float speed;
  418. ...
  419. void _process(float delta);
  420. void set_speed(float p_speed);
  421. float get_speed();
  422. ...
  423. This requires a few more changes to our ``gdexample.cpp`` file, again we're only
  424. showing the methods that have changed so don't remove anything we're omitting:
  425. .. tabs::
  426. .. code-tab:: C++ NativeScript 1.1
  427. void GDExample::_register_methods() {
  428. register_method("_process", &GDExample::_process);
  429. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  430. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  431. }
  432. void GDExample::_init() {
  433. // initialize any variables here
  434. time_passed = 0.0;
  435. amplitude = 10.0;
  436. speed = 1.0;
  437. }
  438. void GDExample::_process(float delta) {
  439. time_passed += speed * delta;
  440. Vector2 new_position = Vector2(
  441. amplitude + (amplitude * sin(time_passed * 2.0)),
  442. amplitude + (amplitude * cos(time_passed * 1.5))
  443. );
  444. set_position(new_position);
  445. }
  446. void GDExample::set_speed(float p_speed) {
  447. speed = p_speed;
  448. }
  449. float GDExample::get_speed() {
  450. return speed;
  451. }
  452. .. code-tab:: C++ NativeScript 1.0
  453. void GDExample::_register_methods() {
  454. register_method((char *)"_process", &GDExample::_process);
  455. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  456. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  457. }
  458. GDExample::GDExample() {
  459. // initialize any variables here
  460. time_passed = 0.0;
  461. amplitude = 10.0;
  462. speed = 1.0;
  463. }
  464. void GDExample::_process(float delta) {
  465. time_passed += speed * delta;
  466. Vector2 new_position = Vector2(
  467. amplitude + (amplitude * sin(time_passed * 2.0)),
  468. amplitude + (amplitude * cos(time_passed * 1.5))
  469. );
  470. owner->set_position(new_position);
  471. }
  472. void GDExample::set_speed(float p_speed) {
  473. speed = p_speed;
  474. }
  475. float GDExample::get_speed() {
  476. return speed;
  477. }
  478. Now when the project is compiled we'll see another property called speed.
  479. Changing its value will make the animation go faster or slower.
  480. For this example there is no obvious advantage of using a setter and getter. It
  481. is just more code to write. For a simple example as this there may be a good
  482. reason for a setter if you want to react on the variable being changed but in
  483. many cases just binding the variable will be enough.
  484. Getters and setters become far more useful in more complex scenarios where you
  485. need to make additional choices based on the state of your object.
  486. .. note::
  487. For simplicity we've left out the optional parameters in the
  488. register_property<class, type> method call. These parameters are
  489. ``rpc_mode``, ``usage``, ``hint`` and ``hint_string``. These can be used to
  490. further configure how properties are displayed and set on the Godot side.
  491. Modern C++ compilers are able to infer the class and variable type and allow
  492. you to omit the ``<GDExample, float>`` part of our ``register_property``
  493. method. We've had mixed experiences with this however.
  494. Signals
  495. -------
  496. Last but not least, signals fully work in GDNative as well. Having your module
  497. react to a signal given out by another object requires you to call ``connect``
  498. on that object. We can't think of a good example for our wobbling Godot icon, we
  499. would need to showcase a far more complete example.
  500. This however is the required syntax:
  501. .. tabs::
  502. .. code-tab:: C++ NativeScript 1.1
  503. some_other_node->connect("the_signal", this, "my_method");
  504. .. code-tab:: C++ NativeScript 1.0
  505. some_other_node->connect("the_signal", owner, "my_method");
  506. Note that you can only call ``my_method`` if you've previously registered it in
  507. your ``_register_methods`` method.
  508. Having your object sending out signals is far more common. For our wobbling
  509. Godot icon we'll do something silly just to show how it works. We're going to
  510. emit a signal every time a second has passed and pass the new location along.
  511. In our ``gdexample.h`` header file we just need to define a new member
  512. ``time_emit``:
  513. .. code-block:: C++
  514. ...
  515. float time_passed;
  516. float time_emit;
  517. float amplitude;
  518. ...
  519. The changes in ``gdexample.cpp`` are a bit more elaborate this time. First
  520. you'll need to set ``time_emit = 0.0;`` in either our ``_init`` method or in our
  521. constructor. But the other two needed changes we'll look at one by one.
  522. In our ``_register_methods`` method we need to declare our signal and we do this
  523. as follows:
  524. .. tabs::
  525. .. code-tab:: C++ NativeScript 1.1
  526. void GDExample::_register_methods() {
  527. register_method("_process", &GDExample::_process);
  528. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  529. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  530. register_signal<GDExample>((char *)"position_changed", "node", GODOT_VARIANT_TYPE_OBJECT, "new_pos", GODOT_VARIANT_TYPE_VECTOR2);
  531. }
  532. .. code-tab:: C++ NativeScript 1.0
  533. void GDExample::_register_methods() {
  534. register_method((char *)"_process", &GDExample::_process);
  535. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  536. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  537. Dictionary args;
  538. args[Variant("node")] = Variant(Variant::OBJECT);
  539. args[Variant("new_pos")] = Variant(Variant::VECTOR2);
  540. register_signal<GDExample>((char *)"position_changed", args);
  541. }
  542. Here we see a nice improvement in the latest version of godot-cpp where our
  543. ``register_signal`` method can be a single call first taking the signals name,
  544. then having pairs of values specifying the parameter name and type of each
  545. parameter we'll send along with this signal.
  546. For NativeScript 1.0 we first build a dictionary in which we tell Godot about
  547. the types of arguments we will pass to our signal, and then register it.
  548. Next we'll need to change our ``_process`` method:
  549. .. tabs::
  550. .. code-tab:: C++ NativeScript 1.1
  551. void GDExample::_process(float delta) {
  552. time_passed += speed * delta;
  553. Vector2 new_position = Vector2(
  554. amplitude + (amplitude * sin(time_passed * 2.0)),
  555. amplitude + (amplitude * cos(time_passed * 1.5))
  556. );
  557. set_position(new_position);
  558. time_emit += delta;
  559. if (time_emit > 1.0) {
  560. emit_signal("position_changed", this, new_position);
  561. time_emit = 0.0;
  562. }
  563. }
  564. .. code-tab:: C++ NativeScript 1.0
  565. void GDExample::_process(float delta) {
  566. time_passed += speed * delta;
  567. Vector2 new_position = Vector2(
  568. amplitude + (amplitude * sin(time_passed * 2.0)),
  569. amplitude + (amplitude * cos(time_passed * 1.5))
  570. );
  571. owner->set_position(new_position);
  572. time_emit += delta;
  573. if (time_emit > 1.0) {
  574. Array args;
  575. args.push_back(Variant(owner));
  576. args.push_back(Variant(new_position));
  577. owner->emit_signal("position_changed", args);
  578. time_emit = 0.0;
  579. }
  580. }
  581. After a second has passed we emit our signal and reset our counter. Again in the
  582. new version of godot-cpp we can add our parameter values directly to
  583. ``emit_signal``. In NativeScript 1.0 We first build an array of values and then
  584. call ``emit_signal``.
  585. Once compiled we can go into Godot and select our sprite node. On our ``Node``
  586. tab we find our new signal and link it up by pressing connect. We've added a
  587. script on our main node and implemented our signal like this:
  588. .. code-block:: none
  589. extends Node
  590. func _on_Sprite_position_changed(node, new_pos):
  591. print("The position of " + node.name + " is now " + str(new_pos))
  592. Every second we simply output our position to the console.
  593. NativeScript 1.1 vs NativeScript 1.0
  594. ------------------------------------
  595. So far in our example above there doesn't seem to be a lot of difference between
  596. the old and new syntax. The class is defined slightly differently and we no
  597. longer use the ``owner`` member to call methods on the Godot side of our object.
  598. A lot of the improvements are hidden under the hood.
  599. This example only deals with simple variables and simple methods. Especially
  600. once you start passing references to other objects or when you start calling
  601. methods that require more complex parameters, NativeScript 1.1 does start to
  602. show its benefits.
  603. Next steps
  604. ----------
  605. The above is only a simple example, but we hope it shows you the basics. You can
  606. build upon this example to create full-fledged scripts to control nodes in Godot
  607. using C++.
  608. You should be able to edit and recompile the plugin while the Godot editor
  609. remains open; just rerun the project after the library has finished building.