import_plugins.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. .. _doc_import_plugins:
  2. Import plugins
  3. ==============
  4. .. note:: This tutorial assumes you already know how to make generic plugins. If
  5. in doubt, refer to the :ref:`doc_making_plugins` page. This also
  6. assumes you are acquainted with Godot's import system.
  7. Introduction
  8. ------------
  9. An import plugin is a special type of editor tool that allows custom resources
  10. to be imported by Godot and be treated as first-class resources. The editor
  11. itself comes bundled with a lot of import plugins to handle the common resources
  12. like PNG images, Collada and glTF models, Ogg Vorbis sounds, and many more.
  13. This tutorial will show you how to create a simple import plugin to load a
  14. custom text file as a material resource. This text file will contain three
  15. numeric values separated by comma, which represents the three channels of a
  16. color, and the resulting color will be used as the albedo (main color) of the
  17. imported material. In this example it will contain the pure blue color
  18. (zero red, zero green, and full blue):
  19. .. code-block:: none
  20. 0,0,255
  21. Configuration
  22. -------------
  23. First we need a generic plugin that will handle the initialization and
  24. destruction of our import plugin. Let's add the ``plugin.cfg`` file first:
  25. .. code-block:: ini
  26. [plugin]
  27. name="Silly Material Importer"
  28. description="Imports a 3D Material from an external text file."
  29. author="Yours Truly"
  30. version="1.0"
  31. script="material_import.gd"
  32. Then we need the ``material_import.gd`` file to add and remove the import plugin
  33. when needed:
  34. ::
  35. # material_import.gd
  36. tool
  37. extends EditorPlugin
  38. var import_plugin
  39. func _enter_tree():
  40. import_plugin = preload("import_plugin.gd").new()
  41. add_import_plugin(import_plugin)
  42. func _exit_tree():
  43. remove_import_plugin(import_plugin)
  44. import_plugin = null
  45. When this plugin is activated, it will create a new instance of the import
  46. plugin (which we'll soon make) and add it to the editor using the
  47. :ref:`add_import_plugin() <class_EditorPlugin_method_add_import_plugin>` method. We store
  48. a reference to it in a class member ``import_plugin`` so we can refer to it
  49. later when removing it. The
  50. :ref:`remove_import_plugin() <class_EditorPlugin_method_remove_import_plugin>` method is
  51. called when the plugin is deactivated to clean up the memory and let the editor
  52. know the import plugin isn't available anymore.
  53. Note that the import plugin is a reference type, so it doesn't need to be
  54. explicitly released from memory with the ``free()`` function. It will be
  55. released automatically by the engine when it goes out of scope.
  56. The EditorImportPlugin class
  57. ----------------------------
  58. The main character of the show is the
  59. :ref:`EditorImportPlugin class <class_EditorImportPlugin>`. It is responsible for
  60. implementing the methods that are called by Godot when it needs to know how to deal
  61. with files.
  62. Let's begin to code our plugin, one method at time:
  63. ::
  64. # import_plugin.gd
  65. tool
  66. extends EditorImportPlugin
  67. func get_importer_name():
  68. return "demos.sillymaterial"
  69. The first method is the
  70. :ref:`get_importer_name()<class_EditorImportPlugin_method_get_importer_name>`. This is a
  71. unique name for your plugin that is used by Godot to know which import was used
  72. in a certain file. When the files needs to be reimported, the editor will know
  73. which plugin to call.
  74. ::
  75. func get_visible_name():
  76. return "Silly Material"
  77. The :ref:`get_visible_name()<class_EditorImportPlugin_method_get_visible_name>` method is
  78. responsible for returning the name of the type it imports and it will be shown to the
  79. user in the Import dock.
  80. You should choose this name as a continuation to "Import as", e.g. *"Import as
  81. Silly Material"*. You can name it whatever you want but we recommend a
  82. descriptive name for your plugin.
  83. ::
  84. func get_recognized_extensions():
  85. return ["mtxt"]
  86. Godot's import system detects file types by their extension. In the
  87. :ref:`get_recognized_extensions()<class_EditorImportPlugin_method_get_recognized_extensions>`
  88. method you return an array of strings to represent each extension that this
  89. plugin can understand. If an extension is recognized by more than one plugin,
  90. the user can select which one to use when importing the files.
  91. .. tip:: Common extensions like ``.json`` and ``.txt`` might be used by many
  92. plugins. Also, there could be files in the project that are just data
  93. for the game and should not be imported. You have to be careful when
  94. importing to validate the data. Never expect the file to be well-formed.
  95. ::
  96. func get_save_extension():
  97. return "material"
  98. The imported files are saved in the ``.import`` folder at the project's root.
  99. Their extension should match the type of resource you are importing, but since
  100. Godot can't tell what you'll use (because there might be multiple valid
  101. extensions for the same resource), you need to declare what will be used in
  102. the import.
  103. Since we're importing a Material, we'll use the special extension for such
  104. resource types. If you are importing a scene, you can use ``scn``. Generic
  105. resources can use the ``res`` extension. However, this is not enforced in any
  106. way by the engine.
  107. ::
  108. func get_resource_type():
  109. return "SpatialMaterial"
  110. The imported resource has a specific type, so the editor can know which property
  111. slot it belongs to. This allows drag and drop from the FileSystem dock to a
  112. property in the Inspector.
  113. In our case it's a :ref:`class_SpatialMaterial`, which can be applied to 3D
  114. objects.
  115. .. note:: If you need to import different types from the same extension, you
  116. have to create multiple import plugins. You can abstract the import
  117. code on another file to avoid duplication in this regard.
  118. Options and presets
  119. -------------------
  120. Your plugin can provide different options to allow the user to control how the
  121. resource will be imported. If a set of selected options is common, you can also
  122. create different presets to make it easier for the user. The following image
  123. shows how the options will appear in the editor:
  124. .. image:: img/import_plugin_options.png
  125. Since there might be many presets and they are identified with a number, it's a
  126. good practice to use an enum so you can refer to them using names.
  127. ::
  128. tool
  129. extends EditorImportPlugin
  130. enum Presets { DEFAULT }
  131. ...
  132. Now that the enum is defined, let's keep looking at the methods of an import
  133. plugin:
  134. ::
  135. func get_preset_count():
  136. return Presets.size()
  137. The :ref:`get_preset_count() <class_EditorImportPlugin_method_get_preset_count>` method
  138. returns the amount of presets that this plugins defines. We only have one preset
  139. now, but we can make this method future-proof by returning the size of our
  140. ``Presets`` enumeration.
  141. ::
  142. func get_preset_name(preset):
  143. match preset:
  144. Presets.DEFAULT:
  145. return "Default"
  146. _:
  147. return "Unknown"
  148. Here we have the
  149. :ref:`get_preset_name() <class_EditorImportPlugin_method_get_preset_name>` method, which
  150. gives names to the presets as they will be presented to the user, so be sure to
  151. use short and clear names.
  152. We can use the ``match`` statement here to make the code more structured. This
  153. way it's easy to add new presets in the future. We use the catch all pattern to
  154. return something too. Although Godot won't ask for presets beyond the preset
  155. count you defined, it's always better to be on the safe side.
  156. If you have only one preset you could simply return its name directly, but if
  157. you do this you have to be careful when you add more presets.
  158. ::
  159. func get_import_options(preset):
  160. match preset:
  161. Presets.DEFAULT:
  162. return [{
  163. "name": "use_red_anyway",
  164. "default_value": false
  165. }]
  166. _:
  167. return []
  168. This is the method which defines the available options.
  169. :ref:`get_import_options() <class_EditorImportPlugin_method_get_import_options>` returns
  170. an array of dictionaries, and each dictionary contains a few keys that are
  171. checked to customize the option as its shown to the user. The following table
  172. shows the possible keys:
  173. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  174. | Key | Type | Description |
  175. +===================+============+==========================================================================================================+
  176. | ``name`` | String | The name of the option. When showed, underscores become spaces and first letters are capitalized. |
  177. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  178. | ``default_value`` | Any | The default value of the option for this preset. |
  179. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  180. | ``property_hint`` | Enum value | One of the :ref:`PropertyHint <enum_@GlobalScope_PropertyHint>` values to use as hint. |
  181. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  182. | ``hint_string`` | String | The hint text of the property. The same as you'd add in the ``export`` statement in GDScript. |
  183. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  184. | ``usage`` | Enum value | One of the :ref:`PropertyUsageFlags <enum_@GlobalScope_PropertyUsageFlags>` values to define the usage. |
  185. +-------------------+------------+----------------------------------------------------------------------------------------------------------+
  186. The ``name`` and ``default_value`` keys are **mandatory**, the rest are optional.
  187. Note that the ``get_import_options`` method receives the preset number, so you
  188. can configure the options for each different preset (especially the default
  189. value). In this example we use the ``match`` statement, but if you have lots of
  190. options and the presets only change the value you may want to create the array
  191. of options first and then change it based on the preset.
  192. .. warning:: The ``get_import_options`` method is called even if you don't
  193. define presets (by making ``get_preset_count`` return zero). You
  194. have to return an array even it's empty, otherwise you can get
  195. errors.
  196. ::
  197. func get_option_visibility(option, options):
  198. return true
  199. For the
  200. :ref:`get_option_visibility() <class_EditorImportPlugin_method_get_option_visibility>`
  201. method, we simply return ``true`` because all of our options (i.e. the single
  202. one we defined) are visible all the time.
  203. If you need to make certain option visible only if another is set with a certain
  204. value, you can add the logic in this method.
  205. The ``import`` method
  206. ---------------------
  207. The heavy part of the process, responsible for converting the files into
  208. resources, is covered by the :ref:`import() <class_EditorImportPlugin_method_import>`
  209. method. Our sample code is a bit long, so let's split in a few parts:
  210. ::
  211. func import(source_file, save_path, options, r_platform_variants, r_gen_files):
  212. var file = File.new()
  213. var err = file.open(source_file, File.READ)
  214. if err != OK:
  215. return err
  216. var line = file.get_line()
  217. file.close()
  218. The first part of our import method opens and reads the source file. We use the
  219. :ref:`File <class_File>` class to do that, passing the ``source_file``
  220. parameter which is provided by the editor.
  221. If there's an error when opening the file, we return it to let the editor know
  222. that the import wasn't successful.
  223. ::
  224. var channels = line.split(",")
  225. if channels.size() != 3:
  226. return ERR_PARSE_ERROR
  227. var color
  228. if options.use_red_anyway:
  229. color = Color8(255, 0, 0)
  230. else:
  231. color = Color8(int(channels[0]), int(channels[1]), int(channels[2]))
  232. This code takes the line of the file it read before and splits it in pieces
  233. that are separated by a comma. If there are more or less than the three values,
  234. it considers the file invalid and reports an error.
  235. Then it creates a new :ref:`Color <class_Color>` variable and sets its values
  236. according to the input file. If the ``use_red_anyway`` option is enabled, then
  237. it sets the color as a pure red instead.
  238. ::
  239. var material = SpatialMaterial.new()
  240. material.albedo_color = color
  241. This part makes a new :ref:`SpatialMaterial <class_SpatialMaterial>` that is the
  242. imported resource. We create a new instance of it and then set its albedo color
  243. as the value we got before.
  244. ::
  245. return ResourceSaver.save("%s.%s" % [save_path, get_save_extension()], material)
  246. This is the last part and quite an important one, because here we save the made
  247. resource to the disk. The path of the saved file is generated and informed by
  248. the editor via the ``save_path`` parameter. Note that this comes **without** the
  249. extension, so we add it using :ref:`string formatting <doc_gdscript_printf>`. For
  250. this we call the ``get_save_extension`` method that we defined earlier, so we
  251. can be sure that they won't get out of sync.
  252. We also return the result from the
  253. :ref:`ResourceSaver.save() <class_ResourceSaver_method_save>` method, so if there's an
  254. error in this step, the editor will know about it.
  255. Platform variants and generated files
  256. -------------------------------------
  257. You may have noticed that our plugin ignored two arguments of the ``import``
  258. method. Those are *return arguments* (hence the ``r`` at the beginning of their
  259. name), which means that the editor will read from them after calling your import
  260. method. Both of them are arrays that you can fill with information.
  261. The ``r_platform_variants`` argument is used if you need to import the resource
  262. differently depending on the target platform. While it's called *platform*
  263. variants, it is based on the presence of :ref:`feature tags <doc_feature_tags>`,
  264. so even the same platform can have multiple variants depending on the setup.
  265. To import a platform variant, you need to save it with the feature tag before
  266. the extension, and then push the tag to the ``r_platform_variants`` array so the
  267. editor can know that you did.
  268. For example, let's say we save a different material for a mobile platform. We
  269. would need to do something like the following:
  270. ::
  271. r_platform_variants.push_back("mobile")
  272. return ResourceSaver.save("%s.%s.%s" % [save_path, "mobile", get_save_extension()], mobile_material)
  273. The ``r_gen_files`` argument is meant for extra files that are generated during
  274. your import process and need to be kept. The editor will look at it to
  275. understand the dependencies and make sure the extra file is not inadvertently
  276. deleted.
  277. This is also an array and should be filled with full paths of the files you
  278. save. As an example, let's create another material for the next pass and save it
  279. in a different file:
  280. ::
  281. var next_pass = SpatialMaterial.new()
  282. next_pass.albedo_color = color.inverted()
  283. var next_pass_path = "%s.next_pass.%s" % [save_path, get_save_extension()]
  284. err = ResourceSaver.save(next_pass_path, next_pass)
  285. if err != OK:
  286. return err
  287. r_gen_files.push_back(next_pass_path)
  288. Trying the plugin
  289. -----------------
  290. This has been theoretical, but now that the import plugin is done, let's
  291. test it. Make sure you created the sample file (with the contents described in
  292. the introduction section) and save it as ``test.mtxt``. Then activate the plugin
  293. in the Project Settings.
  294. If everything goes well, the import plugin is added to the editor and the file
  295. system is scanned, making the custom resource appear on the FileSystem dock. If
  296. you select it and focus the Import dock, you can see the only option to select
  297. there.
  298. Create a MeshInstance node in the scene, and for its Mesh property set up a new
  299. SphereMesh. Unfold the Material section in the Inspector and then drag the file
  300. from the FileSystem dock to the material property. The object will update in the
  301. viewport with the blue color of the imported material.
  302. .. image:: img/import_plugin_trying.png
  303. Go to Import dock, enable the "Use Red Anyway" option, and click on "Reimport".
  304. This will update the imported material and should automatically update the view
  305. showing the red color instead.
  306. And that's it! Your first import plugin is done! Now get creative and make
  307. plugins for your own beloved formats. This can be quite useful to write your
  308. data in a custom format and then use it in Godot as if they were native
  309. resources. This shows how the import system is powerful and extendable.