Importing 3D scenes

Godot scene importer

When dealing with 3D assets, Godot has a flexible and configurable importer.

Godot works with scenes. This means that the entire scene being worked on in your favorite 3D DCC will be transferred as close as possible.

Godot supports the following 3D scene file fomats:

  • DAE (COLLADA), which is currently the most mature workflow.
  • glTF 2.0. Both text and binary formats are supported. Godot has full support for it, but the format is new and gaining traction.
  • Formatos OBJ (Wavefront). Também é oferecido suporte completo, mas bastante limitado (sem suporte para pivots, esqueletos, etc).
  • ESCN, a Godot specific format that Blender can export with a plugin.

Simplesmente copie o arquivo todo da cena com a textura para o repositório do projeto, e o Godot fará uma importação completa.

É importante que a malha não esteja deformada pelos ossos quando for exportar. Tenha certeza que o esqueleto esteja setado em pose tipo T ou pose de descanso padrão antes de exportar usando seu editor 3D favorito.

Por que não FBX?

A maioria das engines de jogos usa o formato FBX para importar cenas 3D, que é com certeza um dos formatos mais usados da indústria. Porém, esse formato requer o uso de uma biblioteca de código fechado da Autodesk, que é distribuida com uma licensa mais restritiva do que a da Godot.

O plano é, futuramente, oferecer um plugin binário usando GDNative.

Exportando arquivos DAE do Maya e 3DS Max

A Autodesk adicionou suporte nativo ao formato COLLADA no Maya e no 3DS Max, mas ele não funciona por padrão e não deveria ser utilizado. A menlhor maneira de exportar esse formado é usando os plugins OpenCollada. Eles funcionam bem, apesar de que nem sempre estão atualizados com a última versão do software.

Exportando arquivos DAE no Blender

O Blender possui suporte ao formato COLLADA nativamente, mas está quebrado e não deveria ser usado.

A Godot oferece um Plugin Python que faz um trabalho bem melhor de exportar cenas.

Exporting glTF 2.0 files from Blender

There are three ways to export glTF files from Blender. As a glTF binary (.glb file), glTF embedded (.gltf file), and with textures (gltf + .bin + textures).

glTF binary files are the smallest of the three options. They include the mesh and textures set up in Blender. When brought into Godot the textures are part of the object’s material file.

glTF embedded files function the same way as binary files. They don’t provide extra functionality in Godot, and shouldn’t be used since they have a larger file size.

There are two reasons to use glTF with the textures separate. One is to have the scene description in a text based format and the binary data in a separate binary file. This can be useful for version control if you want to review changes in a text based format. The second is you need the texture files separate from the material file. If you don’t need either of those glTF binary files are fine.

Nota

Blender does not export emissive textures with the glTF file. If your model uses one it must be brought in separately.

Exportando arquivos ESCN do Blender

O mais poderoso, chamado godot-blender-exporter. Ele usa um arquivo .escn, o qual é uma espécie de arquivo .tscn (arquivo Godot Scene); ele retém o máximo de informações possível sobre uma Blender Scene.

O exportador ESCN tem um detalhado document descrevendo seu uso e funcionalidade.

Importar fluxos de trabalho

O importador de cenas do Godot permite diferentes fluxos de trabalho a respeito de como os dados são importados. Dependendo de muitas opções, é possível importar a cena usando:

  • Materiais externos (padrão): Onde cada material é salvado em um arquivo. Modificações serão mantidas.
  • Malhas externas: Onde cada malha é salva em diferentes arquivos. Vários usuários preferem lidar com malhas diretamente.
  • Animações externas: Permitir que animações salvas sejam modificadas e mescladas quando fonte for alterada.
  • Cenas externas: Salve cada um dos nós raiz das cenas importadas em uma cena separada.
  • Cena única: Um único arquivo de cena com tudo configurado.
../../../_images/scene_import1.png

O processo de importação é altamente customizável, já que diferentes desenvolvedores possuem diferentes necessidades.

Import options

O importador possui diversas opções, que serão discutidas logo abaixo:

../../../_images/scene_import2.png

Nós

Tipo da Raiz

Por padrão, o tipo do nó raiz nas cenas importadas é “Espacial”, mas isso pode ser modificado.

Nome da Raiz

Permite setar um nome específico para o nó raiz gerado.

Root Scale

The scale of the root node.

Script Personalizado

A special script to process the whole scene after import can be provided. This is great for post processing, changing materials, doing funny stuff with the geometry etc.

Crie um script dessa forma:

tool # needed so it runs in the editor
extends EditorScenePostImport

func post_import(scene):
  # do your stuff here
  return scene # remember to return the imported scene

A função post_import recebe a cena importada como argumento (o parâmetro é o nó raiz da cena). A cena que será utilizada tem que ser retornada. Pode ser uma diferente.

Armazenamento

Por padrão, o Godot importa uma única cena. Essa opção permite especificar que cada um dos nós abaixo da raiz serão uma cena separada e a instancia na cena importada.

Claro, instanciar essas cenas importadas em outros lugares manualmente também funciona.

Materiais

Localização

Godot tem suporte a materiais em malha ou em nós. Por padrão, materiais serão colocados em cada um dos nós.

Armazenamento

Materiais podem ser armazenados na cena ou em um arquivo externo. Por padrão, eles são armazenados em arquivos externos para que seja possível editá-los. Isso acontece porquê a maioria dos DCCs 3D não possuem as mesmas opções de material que o Godot.

Quando os materiais são compilados, eles serão perdidos toda vez que a cena principal for modificada ou importada.

Manter ao Reimportar

Once materials are edited to use Godot features, the importer will keep the edited ones and ignore the ones coming from the source scene. This option is only present if materials are saved as files.

Meshes

Compress

Makes meshes use less precise numbers for multiple aspects of the mesh in order to save space.

These are:
  • Transform Matrix (Location, rotation, and scale) : 32-bit float to 16-bit signed integer.
  • Vertices : 32-bit float to 16-bit signed integer.
  • Normals : 32-bit float to 32-bit unsigned integer.
  • Tangents : 32-bit float to 32-bit unsigned integer.
  • Vertex Colors : 32-bit float to 32-bit unsigned integer.
  • UV : 32-bit float to 32-bit unsigned integer.
  • UV2 : 32-bit float to 32-bit unsigned integer.
  • Vertex weights : 32-bit float to 16-bit unsigned integer.
  • Armature bones : 32-bit float to 16-bit unsigned integer.
  • Array index : 32-bit or 16-bit unsigned integer based on how many elements there are.
Informação adicional:
  • UV2 = The second UV channel for detail textures and baked lightmap textures.
  • Array index = An array of numbers that number each element of the arrays above; i.e. they number the vertices and normals.

In some cases, this might lead to loss of precision, so disabling this option may be needed. For instance, if a mesh is very big or there are multiple meshes being imported that cover a large area, compressing the import of this mesh(es) may lead to gaps in geometry or vertices not being exactly where they should be.

Ensure Tangents

If textures with normal mapping are to be used, meshes need to have tangent arrays. This option ensures that these are generated if not present in the source scene. Godot uses Mikktspace for this, but it’s always better to have them generated in the exporter.

Armazenamento

Meshes can be stored in separate files (resources) instead of built-in. This does not have much practical use unless one wants to build objects with them directly.

This option is provided to help those who prefer working directly with meshes instead of scenes.

Light Baking

Whether or not the mesh is used in baked lightmaps.

  • Disabled: The mesh is not used in baked lightmaps.
  • Enable: The mesh is used in baked lightmaps.
  • Gen Lightmaps: The mesh is used in baked lightmaps, and unwraps a second UV layer for lightmaps.

Nota

For more information on light baking see Baked lightmaps.

External Files

Generated meshes and materials can be optionally stored in a subdirectory with the name of the scene.

Animation options

Godot provides many options regarding how animation data is dealt with. Some exporters (such as Blender) can generate many animations in a single file. Others, such as 3DS Max or Maya, need many animations put into the same timeline or, at worst, put each animation in a separate file.

../../../_images/scene_import3.png

Import of animations is enabled by default.

FPS

Most 3D export formats store animation timeline in seconds instead of frames. To ensure animations are imported as faithfully as possible, please specify the frames per second used to edit them. Failing to do this may result in shaky animations.

Filter Script

It is possible to specify a filter script in a special syntax to decide which tracks from which animations should be kept. (@TODO this needs documentation)

Armazenamento

By default, animations are saved as built-in. It is possible to save them to a file instead. This allows adding custom tracks to the animations and keeping them after a reimport.

Optimizer

When animations are imported, an optimizer is run, which reduces the size of the animation considerably. In general, this should always be turned on unless you suspect that an animation might be broken due to it being enabled.

Clips

It is possible to specify multiple animations from a single timeline as clips. Specify from which frame to which frame each clip must be taken (and, of course, don’t forget to specify the FPS option above).

Scene inheritance

In many cases, it may be desired to make modifications to the imported scene. By default, this is not possible because if the source asset changes (source .dae, .gltf, .obj file re-exported from 3D modelling app), Godot will re-import the whole scene.

It is possible, however, to make local modifications by using Scene Inheritance. Try to open the imported scene and the following dialog will appear:

../../../_images/scene_import4.png

In inherited scenes, the only limitations for modifications are:

  • Nodes can’t be removed (but can be added anywhere).
  • Sub-Resources can’t be edited (save them externally as described above for this)

Other than that, everything is allowed!

Import hints

Many times, when editing a scene, there are common tasks that need to be done after exporting:

  • Adding collision detection to objects
  • Setting objects as navigation meshes
  • Deleting nodes that are not used in the game engine (like specific lights used for modelling)

To simplify this workflow, Godot offers a few suffixes that can be added to the names of the objects in your 3D modelling software. When imported, Godot will detect them and perform actions automatically:

Remove nodes (-noimp)

Node names that have this suffix will be removed at import time, no matter what their type is. They will not appear in the imported scene.

Create collisions (-col, -colonly, -convcolonly)

Option “-col” will work only for Mesh nodes. If it is detected, a child static collision node will be added, using the same geometry as the mesh.

However, it is often the case that the visual geometry is too complex or too un-smooth for collisions, which ends up not working well.

To solve this, the “-colonly” modifier exists, which will remove the mesh upon import and create a class_staticbody collision instead. This helps the visual mesh and actual collision to be separated.

Option “-convcolonly” will create a class_convexpolygonshape instead of a class_concavepolygonshape.

Option “-colonly” can also be used with Blender’s empty objects. On import, it will create a class_staticbody with a collision node as a child. The collision node will have one of a number of predefined shapes, depending on Blender’s empty draw type:

../../../_images/3dimp_BlenderEmptyDrawTypes.png
  • Single arrow will create a class_rayshape
  • Cube will create a class_boxshape
  • Image will create a class_planeshape
  • Sphere (and the others not listed) will create a class_sphereshape

For better visibility in Blender’s editor, the user can set “X-Ray” option on collision empties and set some distinct color for them in User Preferences / Themes / 3D View / Empty.

Create navigation (-navmesh)

A mesh node with this suffix will be converted to a navigation mesh. Original Mesh node will be removed.

Create a VehicleBody (-vehicle)

A mesh node with this suffix will be imported as a child to a VehicleBody node.

Create a VehicleWheel (-wheel)

A mesh node with this suffix will be imported as a child to a VehicleWheel node.

Rigid Body (-rigid)

Creates a rigid body from this mesh.

Animation loop (-loop, -cycle)

Animation clips in the COLLADA document that start or end with the token “loop” or “cycle” will be imported as a Godot Animation with the loop flag set. This is case-sensitive and does not require a hyphen.

In Blender, this requires using the NLA Editor and naming the Action with the “loop” or “cycle” prefix or suffix.