using_servers.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. :article_outdated: True
  2. .. _doc_using_servers:
  3. Optimization using Servers
  4. ==========================
  5. Engines like Godot provide increased ease of use thanks to their high-level constructs and features.
  6. Most of them are accessed and used via the :ref:`Scene System<doc_scene_tree>`. Using nodes and
  7. resources simplifies project organization and asset management in complex games.
  8. There are, of course, always drawbacks:
  9. * There is an extra layer of complexity.
  10. * Performance is lower than when using simple APIs directly.
  11. * It is not possible to use multiple threads to control them.
  12. * More memory is needed.
  13. In many cases, this is not really a problem (Godot is very optimized, and most operations are handled
  14. with signals, so no polling is required). Still, sometimes it can be. For example, dealing with
  15. tens of thousands of instances for something that needs to be processed every frame can be a bottleneck.
  16. This type of situation makes programmers regret they are using a game engine and wish they could go
  17. back to a more handcrafted, low-level implementation of game code.
  18. Still, Godot is designed to work around this problem.
  19. .. seealso::
  20. You can see how using low-level servers works in action using the
  21. `Bullet Shower demo project <https://github.com/godotengine/godot-demo-projects/tree/master/2d/bullet_shower>`__
  22. Servers
  23. -------
  24. One of the most interesting design decisions for Godot is the fact that the whole scene system is
  25. *optional*. While it is not currently possible to compile it out, it can be completely bypassed.
  26. At the core, Godot uses the concept of Servers. They are very low-level APIs to control
  27. rendering, physics, sound, etc. The scene system is built on top of them and uses them directly.
  28. The most common servers are:
  29. * :ref:`RenderingServer <class_RenderingServer>`: handles everything related to graphics.
  30. * :ref:`PhysicsServer3D <class_PhysicsServer3D>`: handles everything related to 3D physics.
  31. * :ref:`PhysicsServer2D <class_PhysicsServer2D>`: handles everything related to 2D physics.
  32. * :ref:`AudioServer <class_AudioServer>`: handles everything related to audio.
  33. Explore their APIs and you will realize that all the functions provided are low-level
  34. implementations of everything Godot allows you to do.
  35. RIDs
  36. ----
  37. The key to using servers is understanding Resource ID (:ref:`RID <class_RID>`) objects. These are opaque
  38. handles to the server implementation. They are allocated and freed manually. Almost every
  39. function in the servers requires RIDs to access the actual resource.
  40. Most Godot nodes and resources contain these RIDs from the servers internally, and they can
  41. be obtained with different functions. In fact, anything that inherits :ref:`Resource <class_Resource>`
  42. can be directly casted to an RID. Not all resources contain an RID, though: in such cases, the RID will be empty. The resource can then be passed to server APIs as an RID.
  43. .. Warning:: Resources are reference-counted (see :ref:`RefCounted <class_RefCounted>`), and
  44. references to a resource's RID are *not* counted when determining whether
  45. the resource is still in use. Make sure to keep a reference to the resource
  46. outside the server, or else both it and its RID will be erased.
  47. For nodes, there are many functions available:
  48. * For CanvasItem, the :ref:`CanvasItem.get_canvas_item() <class_CanvasItem_method_get_canvas_item>`
  49. method will return the canvas item RID in the server.
  50. * For CanvasLayer, the :ref:`CanvasLayer.get_canvas() <class_CanvasLayer_method_get_canvas>`
  51. method will return the canvas RID in the server.
  52. * For Viewport, the :ref:`Viewport.get_viewport_rid() <class_Viewport_method_get_viewport_rid>`
  53. method will return the viewport RID in the server.
  54. * For 3D, the :ref:`World3D <class_World3D>` resource (obtainable in the :ref:`Viewport <class_Viewport>`
  55. and :ref:`Node3D <class_Node3D>` nodes)
  56. contains functions to get the *RenderingServer Scenario*, and the *PhysicsServer Space*. This
  57. allows creating 3D objects directly with the server API and using them.
  58. * For 2D, the :ref:`World2D <class_World2D>` resource (obtainable in the :ref:`Viewport <class_Viewport>`
  59. and :ref:`CanvasItem <class_CanvasItem>` nodes)
  60. contains functions to get the *RenderingServer Canvas*, and the *Physics2DServer Space*. This
  61. allows creating 2D objects directly with the server API and using them.
  62. * The :ref:`VisualInstance3D<class_VisualInstance3D>` class, allows getting the scenario *instance* and
  63. *instance base* via the :ref:`VisualInstance3D.get_instance() <class_VisualInstance3D_method_get_instance>`
  64. and :ref:`VisualInstance3D.get_base() <class_VisualInstance3D_method_get_base>` respectively.
  65. Try exploring the nodes and resources you are familiar with and find the functions to obtain the server *RIDs*.
  66. It is not advised to control RIDs from objects that already have a node associated. Instead, server
  67. functions should always be used for creating and controlling new ones and interacting with the existing ones.
  68. Creating a sprite
  69. -----------------
  70. This is an example of how to create a sprite from code and move it using the low-level
  71. :ref:`CanvasItem <class_CanvasItem>` API.
  72. .. tabs::
  73. .. code-tab:: gdscript GDScript
  74. extends Node2D
  75. # RenderingServer expects references to be kept around.
  76. var texture
  77. func _ready():
  78. # Create a canvas item, child of this node.
  79. var ci_rid = RenderingServer.canvas_item_create()
  80. # Make this node the parent.
  81. RenderingServer.canvas_item_set_parent(ci_rid, get_canvas_item())
  82. # Draw a texture on it.
  83. # Remember, keep this reference.
  84. texture = load("res://my_texture.png")
  85. # Add it, centered.
  86. RenderingServer.canvas_item_add_texture_rect(ci_rid, Rect2(-texture.get_size() / 2, texture.get_size()), texture)
  87. # Add the item, rotated 45 degrees and translated.
  88. var xform = Transform2D().rotated(deg_to_rad(45)).translated(Vector2(20, 30))
  89. RenderingServer.canvas_item_set_transform(ci_rid, xform)
  90. .. code-tab:: csharp
  91. public partial class MyNode2D : Node2D
  92. {
  93. // RenderingServer expects references to be kept around.
  94. private Texture2D _texture;
  95. public override void _Ready()
  96. {
  97. // Create a canvas item, child of this node.
  98. Rid ciRid = RenderingServer.CanvasItemCreate();
  99. // Make this node the parent.
  100. RenderingServer.CanvasItemSetParent(ciRid, GetCanvasItem());
  101. // Draw a texture on it.
  102. // Remember, keep this reference.
  103. _texture = ResourceLoader.Load<Texture2D>("res://MyTexture.png");
  104. // Add it, centered.
  105. RenderingServer.CanvasItemAddTextureRect(ciRid, new Rect2(-_texture.GetSize() / 2, _texture.GetSize()), _texture.GetRid());
  106. // Add the item, rotated 45 degrees and translated.
  107. Transform2D xform = Transform2D.Identity.Rotated(Mathf.DegToRad(45)).Translated(new Vector2(20, 30));
  108. RenderingServer.CanvasItemSetTransform(ciRid, xform);
  109. }
  110. }
  111. The Canvas Item API in the server allows you to add draw primitives to it. Once added, they can't be modified.
  112. The Item needs to be cleared and the primitives re-added (this is not the case for setting the transform,
  113. which can be done as many times as desired).
  114. Primitives are cleared this way:
  115. .. tabs::
  116. .. code-tab:: gdscript GDScript
  117. RenderingServer.canvas_item_clear(ci_rid)
  118. .. code-tab:: csharp
  119. RenderingServer.CanvasItemClear(ciRid);
  120. Instantiating a Mesh into 3D space
  121. ----------------------------------
  122. The 3D APIs are different from the 2D ones, so the instantiation API must be used.
  123. .. tabs::
  124. .. code-tab:: gdscript GDScript
  125. extends Node3D
  126. # RenderingServer expects references to be kept around.
  127. var mesh
  128. func _ready():
  129. # Create a visual instance (for 3D).
  130. var instance = RenderingServer.instance_create()
  131. # Set the scenario from the world, this ensures it
  132. # appears with the same objects as the scene.
  133. var scenario = get_world_3d().scenario
  134. RenderingServer.instance_set_scenario(instance, scenario)
  135. # Add a mesh to it.
  136. # Remember, keep the reference.
  137. mesh = load("res://mymesh.obj")
  138. RenderingServer.instance_set_base(instance, mesh)
  139. # Move the mesh around.
  140. var xform = Transform3D(Basis(), Vector3(20, 100, 0))
  141. RenderingServer.instance_set_transform(instance, xform)
  142. .. code-tab:: csharp
  143. public partial class MyNode3D : Node3D
  144. {
  145. // RenderingServer expects references to be kept around.
  146. private Mesh _mesh;
  147. public override void _Ready()
  148. {
  149. // Create a visual instance (for 3D).
  150. Rid instance = RenderingServer.InstanceCreate();
  151. // Set the scenario from the world, this ensures it
  152. // appears with the same objects as the scene.
  153. Rid scenario = GetWorld3D().Scenario;
  154. RenderingServer.InstanceSetScenario(instance, scenario);
  155. // Add a mesh to it.
  156. // Remember, keep the reference.
  157. _mesh = ResourceLoader.Load<Mesh>("res://MyMesh.obj");
  158. RenderingServer.InstanceSetBase(instance, _mesh.GetRid());
  159. // Move the mesh around.
  160. Transform3D xform = new Transform3D(Basis.Identity, new Vector3(20, 100, 0));
  161. RenderingServer.InstanceSetTransform(instance, xform);
  162. }
  163. }
  164. Creating a 2D RigidBody and moving a sprite with it
  165. ---------------------------------------------------
  166. This creates a :ref:`RigidBody2D <class_RigidBody2D>` using the :ref:`PhysicsServer2D <class_PhysicsServer2D>` API,
  167. and moves a :ref:`CanvasItem <class_CanvasItem>` when the body moves.
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. # Physics2DServer expects references to be kept around.
  171. var body
  172. var shape
  173. func _body_moved(state, index):
  174. # Created your own canvas item, use it here.
  175. RenderingServer.canvas_item_set_transform(canvas_item, state.transform)
  176. func _ready():
  177. # Create the body.
  178. body = Physics2DServer.body_create()
  179. Physics2DServer.body_set_mode(body, Physics2DServer.BODY_MODE_RIGID)
  180. # Add a shape.
  181. shape = Physics2DServer.rectangle_shape_create()
  182. # Set rectangle extents.
  183. Physics2DServer.shape_set_data(shape, Vector2(10, 10))
  184. # Make sure to keep the shape reference!
  185. Physics2DServer.body_add_shape(body, shape)
  186. # Set space, so it collides in the same space as current scene.
  187. Physics2DServer.body_set_space(body, get_world_2d().space)
  188. # Move initial position.
  189. Physics2DServer.body_set_state(body, Physics2DServer.BODY_STATE_TRANSFORM, Transform2D(0, Vector2(10, 20)))
  190. # Add the transform callback, when body moves
  191. # The last parameter is optional, can be used as index
  192. # if you have many bodies and a single callback.
  193. Physics2DServer.body_set_force_integration_callback(body, self, "_body_moved", 0)
  194. .. code-tab:: csharp
  195. using Godot;
  196. public partial class MyNode2D : Node2D
  197. {
  198. private Rid _canvasItem;
  199. private void BodyMoved(PhysicsDirectBodyState2D state, int index)
  200. {
  201. RenderingServer.CanvasItemSetTransform(_canvasItem, state.Transform);
  202. }
  203. public override void _Ready()
  204. {
  205. // Create the body.
  206. var body = PhysicsServer2D.BodyCreate();
  207. PhysicsServer2D.BodySetMode(body, PhysicsServer2D.BodyMode.Rigid);
  208. // Add a shape.
  209. var shape = PhysicsServer2D.RectangleShapeCreate();
  210. // Set rectangle extents.
  211. PhysicsServer2D.ShapeSetData(shape, new Vector2(10, 10));
  212. // Make sure to keep the shape reference!
  213. PhysicsServer2D.BodyAddShape(body, shape);
  214. // Set space, so it collides in the same space as current scene.
  215. PhysicsServer2D.BodySetSpace(body, GetWorld2D().Space);
  216. // Move initial position.
  217. PhysicsServer2D.BodySetState(body, PhysicsServer2D.BodyState.Transform, new Transform2D(0, new Vector2(10, 20)));
  218. // Add the transform callback, when body moves
  219. // The last parameter is optional, can be used as index
  220. // if you have many bodies and a single callback.
  221. PhysicsServer2D.BodySetForceIntegrationCallback(body, new Callable(this, MethodName.BodyMoved), 0);
  222. }
  223. }
  224. The 3D version should be very similar, as 2D and 3D physics servers are identical (using
  225. :ref:`RigidBody3D <class_RigidBody3D>` and :ref:`PhysicsServer3D <class_PhysicsServer3D>` respectively).
  226. Getting data from the servers
  227. -----------------------------
  228. Try to **never** request any information from ``RenderingServer``, ``PhysicsServer2D`` or ``PhysicsServer3D``
  229. by calling functions unless you know what you are doing. These servers will often run asynchronously
  230. for performance and calling any function that returns a value will stall them and force them to process
  231. anything pending until the function is actually called. This will severely decrease performance if you
  232. call them every frame (and it won't be obvious why).
  233. Because of this, most APIs in such servers are designed so it's not even possible to request information
  234. back, until it's actual data that can be saved.