Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Optimización usando Servidores

Las plataformas como Godot ofrecen una mayor facilidad de uso gracias a sus construcciones y características de alto nivel. La mayoría de ellas se acceden y utilizan a través del Sistema de Escenas. El uso de nodos y recursos simplifica la organización del proyecto y la gestión de activos en juegos complejos.

Por supuesto, siempre existen inconvenientes:

  • There is an extra layer of complexity.

  • Performance is lower than when using simple APIs directly.

  • It is not possible to use multiple threads to control them.

  • Se necesita más memoria.

En muchos casos, esto no es realmente un problema (Godot está muy optimizado y la mayoría de las operaciones se manejan con señales, por lo que no se requiere sondeo). Aún así, a veces puede serlo. Por ejemplo, lidiar con decenas de miles de instancias de algo que debe procesarse en cada fotograma puede ser un cuello de botella.

Este tipo de situación hace que los programadores se arrepientan de estar usando un motor de juego y deseen poder volver a una implementación más artesanal y de bajo nivel del código del juego.

Aún así, Godot está diseñado para solucionar este problema.

Ver también

You can see how using low-level servers works in action using the Bullet Shower demo project

Servidores

Una de las decisiones de diseño más interesantes de Godot es el hecho de que todo el sistema de escenas es opcional. Aunque actualmente no es posible compilarlo por separado, se puede evitar por completo su uso.

En esencia, Godot usa el concepto de servidores. Son APIs de muy bajo nivel para controlar el renderizado, la física, el sonido, etc. El sistema de escenas se construye sobre ellas y las usa directamente. Los servidores más comunes son:

  • RenderingServer: handles everything related to graphics.

  • PhysicsServer3D: handles everything related to 3D physics.

  • PhysicsServer2D: handles everything related to 2D physics.

  • AudioServer: se encarga de todo lo relacionado con el audio.

Simplemente explore sus APIs y se dará cuenta de que todas las funciones proporcionadas son implementaciones de bajo nivel de todo lo que Godot le permite hacer.

RIDs*

La clave para utilizar los servidores es comprender los objetos Resource ID (RID). Estos son identificadores opacos para la implementación del servidor. Se asignan y liberan manualmente. Casi todas las funciones de los servidores requieren RIDs para acceder al recurso real.

La mayoría de los nodos y recursos de Godot contienen estos RIDs de los servidores de forma interna, y se pueden obtener mediante diferentes funciones. De hecho, cualquier cosa que herede de Resource se puede convertir directamente a un RID. Sin embargo, no todos los recursos contienen un RID; en esos casos, el RID estará vacío. El recurso luego se puede pasar a las APIs de los servidores como un RID.

Advertencia

Resources are reference-counted (see RefCounted), and references to a resource's RID are not counted when determining whether the resource is still in use. Make sure to keep a reference to the resource outside the server, or else both it and its RID will be erased.

Para los nodos, hay muchas funciones disponibles:

  • Para CanvasItem, el método CanvasItem.get_canvas_item() retornará el RID del canvas item en el servidor.

  • Para CanvasLayer, el método CanvasLayer.get_canvas() devolverá el RID del lienzo en el servidor.

  • Para Viewport, el método Viewport.get_viewport_rid() devolverá el RID del viewport en el servidor.

  • For 3D, the World3D resource (obtainable in the Viewport and Node3D nodes) contains functions to get the RenderingServer Scenario, and the PhysicsServer Space. This allows creating 3D objects directly with the server API and using them.

  • For 2D, the World2D resource (obtainable in the Viewport and CanvasItem nodes) contains functions to get the RenderingServer Canvas, and the Physics2DServer Space. This allows creating 2D objects directly with the server API and using them.

  • The VisualInstance3D class, allows getting the scenario instance and instance base via the VisualInstance3D.get_instance() and VisualInstance3D.get_base() respectively.

Intenta explorar los nodos y recursos con los que estás familiarizado y encuentra las funciones para obtener los RIDs del servidor.

No se recomienda controlar los RIDs de objetos que ya tienen un nodo asociado. En cambio, las funciones del servidor siempre deben usarse para crear y controlar nuevas e interactuar con las existentes.

Creando un sprite

This is an example of how to create a sprite from code and move it using the low-level CanvasItem API.

extends Node2D


# RenderingServer expects references to be kept around.
var texture


func _ready():
    # Create a canvas item, child of this node.
    var ci_rid = RenderingServer.canvas_item_create()
    # Make this node the parent.
    RenderingServer.canvas_item_set_parent(ci_rid, get_canvas_item())
    # Draw a texture on it.
    # Remember, keep this reference.
    texture = load("res://my_texture.png")
    # Add it, centered.
    RenderingServer.canvas_item_add_texture_rect(ci_rid, Rect2(texture.get_size() / 2, texture.get_size()), texture)
    # Add the item, rotated 45 degrees and translated.
    var xform = Transform2D().rotated(deg_to_rad(45)).translated(Vector2(20, 30))
    RenderingServer.canvas_item_set_transform(ci_rid, xform)

La API de Canvas Item en el servidor te permite agregar primitivas de dibujo. Una vez agregadas, no se pueden modificar. Es necesario borrar el ítem y volver a agregar las primitivas (esto no es necesario para establecer la transformación, que se puede hacer tantas veces como se desee).

Los primitivos se eliminan de esta manera:

RenderingServer.canvas_item_clear(ci_rid)

Instanciando una malla en el espacio 3D

Las API 3D son diferentes de las 2D, por lo que se debe utilizar la API de instanciación.

extends Node3D


# RenderingServer expects references to be kept around.
var mesh


func _ready():
    # Create a visual instance (for 3D).
    var instance = RenderingServer.instance_create()
    # Set the scenario from the world, this ensures it
    # appears with the same objects as the scene.
    var scenario = get_world_3d().scenario
    RenderingServer.instance_set_scenario(instance, scenario)
    # Add a mesh to it.
    # Remember, keep the reference.
    mesh = load("res://mymesh.obj")
    RenderingServer.instance_set_base(instance, mesh)
    # Move the mesh around.
    var xform = Transform3D(Basis(), Vector3(20, 100, 0))
    RenderingServer.instance_set_transform(instance, xform)

Creando un RigidBody 2D y moviendo un sprite con este

This creates a RigidBody2D using the PhysicsServer2D API, and moves a CanvasItem when the body moves.

# Physics2DServer expects references to be kept around.
var body
var shape


func _body_moved(state, index):
    # Created your own canvas item, use it here.
    RenderingServer.canvas_item_set_transform(canvas_item, state.transform)


func _ready():
    # Create the body.
    body = Physics2DServer.body_create()
    Physics2DServer.body_set_mode(body, Physics2DServer.BODY_MODE_RIGID)
    # Add a shape.
    shape = Physics2DServer.rectangle_shape_create()
    # Set rectangle extents.
    Physics2DServer.shape_set_data(shape, Vector2(10, 10))
    # Make sure to keep the shape reference!
    Physics2DServer.body_add_shape(body, shape)
    # Set space, so it collides in the same space as current scene.
    Physics2DServer.body_set_space(body, get_world_2d().space)
    # Move initial position.
    Physics2DServer.body_set_state(body, Physics2DServer.BODY_STATE_TRANSFORM, Transform2D(0, Vector2(10, 20)))
    # Add the transform callback, when body moves
    # The last parameter is optional, can be used as index
    # if you have many bodies and a single callback.
    Physics2DServer.body_set_force_integration_callback(body, self, "_body_moved", 0)

The 3D version should be very similar, as 2D and 3D physics servers are identical (using RigidBody3D and PhysicsServer3D respectively).

Obteniendo datos de servidores

Try to never request any information from RenderingServer, PhysicsServer2D or PhysicsServer3D by calling functions unless you know what you are doing. These servers will often run asynchronously for performance and calling any function that returns a value will stall them and force them to process anything pending until the function is actually called. This will severely decrease performance if you call them every frame (and it won't be obvious why).

Debido a esto, la mayoría de las API en dichos servidores están diseñadas de tal manera que ni siquiera es posible solicitar información de vuelta hasta que sea realmente un dato que pueda ser guardado.