runtime_file_loading_and_saving.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. .. _doc_runtime_loading_and_saving:
  2. Runtime file loading and saving
  3. ===============================
  4. .. seealso::
  5. See :ref:`doc_saving_games` for information on saving and loading game progression.
  6. Sometimes, :ref:`exporting packs, patches, and mods <doc_exporting_pcks>` is not
  7. ideal when you want players to be able to load user-generated content in your
  8. project. It requires users to generate a PCK or ZIP file through the Godot
  9. editor, which contains resources imported by Godot.
  10. Example use cases for runtime file loading and saving include:
  11. - Loading texture packs designed for the game.
  12. - Loading user-provided audio tracks and playing them back in an in-game radio station.
  13. - Loading custom levels or 3D models that can be designed with any 3D DCC that
  14. can export to glTF (including glTF scenes saved by Godot at runtime).
  15. - Using user-provided fonts for menus and HUD.
  16. - Saving/loading a file format that can contain multiple files but can still
  17. easily be read by other applications (ZIP).
  18. - Loading files created by another game or program, or even game data files from
  19. another game not made with Godot.
  20. Runtime file loading can be combined with :ref:`HTTP requests <doc_http_request_class>`
  21. to load resources from the Internet directly.
  22. .. warning::
  23. Do **not** use this runtime loading approach to load resources that are part
  24. of the project, as it's less efficient and doesn't allow benefiting from
  25. Godot's resource handling functionality (such as translation remaps). See
  26. :ref:`doc_import_process` for details.
  27. .. seealso::
  28. You can see how saving and loading works in action using the
  29. `Run-time File Saving and Loading (Serialization) demo project <https://github.com/godotengine/godot-demo-projects/blob/master/loading/runtime_save_load>`__.
  30. Plain text and binary files
  31. ---------------------------
  32. Godot's :ref:`class_FileAccess` class provides methods to access files on the
  33. filesystem for reading and writing:
  34. ::
  35. func save_file(content):
  36. var file = FileAccess.open("/path/to/file.txt", FileAccess.WRITE)
  37. file.store_string(content)
  38. func load_file():
  39. var file = FileAccess.open("/path/to/file.txt", FileAccess.READ)
  40. var content = file.get_as_text()
  41. return content
  42. To handle custom binary formats (such as loading file formats not supported by
  43. Godot), :ref:`class_FileAccess` provides several methods to read/write integers,
  44. floats, strings and more. These FileAccess methods have names that start with
  45. ``get_`` and ``store_``.
  46. If you need more control over reading binary files or need to read binary
  47. streams that are not part of a file, :ref:`class_PackedByteArray` provides
  48. several helper methods to decode/encode series of bytes to integers, floats,
  49. strings and more. These PackedByteArray methods have names that start with
  50. ``decode_`` and ``encode_``. See also :ref:`doc_binary_serialization_api`.
  51. .. _doc_runtime_file_loading_and_saving_images:
  52. Images
  53. ------
  54. Image's :ref:`Image.load_from_file <class_Image_method_load_from_file>` static method
  55. handles everything, from format detection based on file extension to reading the
  56. file from disk.
  57. If you need error handling or more control (such as changing the scale a SVG is
  58. loaded at), use one of the following methods depending on the file format:
  59. - :ref:`Image.load_jpg_from_buffer <class_Image_method_load_jpg_from_buffer>`
  60. - :ref:`Image.load_ktx_from_buffer <class_Image_method_load_ktx_from_buffer>`
  61. - :ref:`Image.load_png_from_buffer <class_Image_method_load_png_from_buffer>`
  62. - :ref:`Image.load_svg_from_buffer <class_Image_method_load_svg_from_buffer>`
  63. or :ref:`Image.load_svg_from_string <class_Image_method_load_svg_from_string>`
  64. - :ref:`Image.load_tga_from_buffer <class_Image_method_load_tga_from_buffer>`
  65. - :ref:`Image.load_webp_from_buffer <class_Image_method_load_webp_from_buffer>`
  66. Several image formats can also be saved by Godot at runtime using the following
  67. methods:
  68. - :ref:`Image.save_png <class_Image_method_save_png>`
  69. or :ref:`Image.save_png_to_buffer <class_Image_method_save_png_to_buffer>`
  70. - :ref:`Image.save_webp <class_Image_method_save_webp>`
  71. or :ref:`Image.save_webp_to_buffer <class_Image_method_save_webp_to_buffer>`
  72. - :ref:`Image.save_jpg <class_Image_method_save_jpg>`
  73. or :ref:`Image.save_jpg_to_buffer <class_Image_method_save_jpg_to_buffer>`
  74. - :ref:`Image.save_exr <class_Image_method_save_exr>`
  75. or :ref:`Image.save_exr_to_buffer <class_Image_method_save_exr_to_buffer>`
  76. *(only available in editor builds, cannot be used in exported projects)*
  77. The methods with the ``to_buffer`` suffix save the image to a PackedByteArray
  78. instead of the filesystem. This is useful to send the image over the network or
  79. into a ZIP archive without having to write it on the filesystem. This can
  80. increase performance by reducing I/O utilization.
  81. .. note::
  82. If displaying the loaded image on a 3D surface, make sure to call
  83. :ref:`Image.generate_mipmaps <class_Image_method_generate_mipmaps>`
  84. so that the texture doesn't look grainy when viewed at a distance.
  85. This is also useful in 2D when following instructions on
  86. :ref:`reducing aliasing when downsampling <doc_multiple_resolutions_reducing_aliasing_on_downsampling>`.
  87. Example of loading an image and displaying it in a :ref:`class_TextureRect` node
  88. (which requires conversion to :ref:`class_ImageTexture`):
  89. ::
  90. # Load an image of any format supported by Godot from the filesystem.
  91. var image = Image.load_from_file(path)
  92. # Optionally, generate mipmaps if displaying the texture on a 3D surface
  93. # so that the texture doesn't look grainy when viewed at a distance.
  94. #image.generate_mipmaps()
  95. $TextureRect.texture = ImageTexture.create_from_image(image)
  96. # Save the loaded Image to a PNG image.
  97. image.save_png("/path/to/file.png")
  98. # Save the converted ImageTexture to a PNG image.
  99. $TextureRect.texture.get_image().save_png("/path/to/file.png")
  100. .. _doc_runtime_file_loading_and_saving_audio_video_files:
  101. Audio/video files
  102. -----------------
  103. Godot supports loading Ogg Vorbis audio at runtime. Note that not *all* files
  104. with an ``.ogg`` extension may be Ogg Vorbis files. Some may be Ogg Theora
  105. videos, or contain Opus audio within an Ogg container. These files will **not**
  106. load correctly as audio files in Godot.
  107. Example of loading an Ogg Vorbis audio file in an :ref:`class_AudioStreamPlayer` node:
  108. ::
  109. $AudioStreamPlayer.stream = AudioStreamOggVorbis.load_from_file(path)
  110. Example of loading an Ogg Theora video file in a :ref:`class_VideoStreamPlayer` node:
  111. ::
  112. var video_stream_theora = VideoStreamTheora.new()
  113. # File extension is ignored, so it is possible to load Ogg Theora videos
  114. # that have an `.ogg` extension this way.
  115. video_stream_theora.file = "/path/to/file.ogv"
  116. $VideoStreamPlayer.stream = video_stream_theora
  117. # VideoStreamPlayer's Autoplay property won't work if the stream is empty
  118. # before this property is set, so call `play()` after setting `stream`.
  119. $VideoStreamPlayer.play()
  120. .. note::
  121. Godot doesn't support runtime loading of MP3 or WAV files yet. Until this is
  122. implemented, it's feasible to implement runtime WAV loading using a script
  123. since :ref:`class_AudioStreamWAV`'s ``data`` property is exposed to
  124. scripting.
  125. It's still possible to *save* WAV files using
  126. :ref:`AudioStreamWAV.save_to_wav <class_AudioStreamWAV_method_save_to_wav>`, which is useful
  127. for procedurally generated audio or microphone recordings.
  128. .. _doc_runtime_file_loading_and_saving_3d_scenes:
  129. 3D scenes
  130. ---------
  131. Godot has first-class support for glTF 2.0, both in the editor and exported
  132. projects. Using :ref:`class_gltfdocument` and :ref:`class_gltfstate` together,
  133. Godot can load and save glTF files in exported projects, in both text
  134. (``.gltf``) and binary (``.glb``) formats. The binary format should be preferred
  135. as it's faster to write and smaller, but the text format is easier to debug.
  136. Example of loading a glTF scene and appending its root node to the scene:
  137. ::
  138. # Load an existing glTF scene.
  139. # GLTFState is used by GLTFDocument to store the loaded scene's state.
  140. # GLTFDocument is the class that handles actually loading glTF data into a Godot node tree,
  141. # which means it supports glTF features such as lights and cameras.
  142. var gltf_document_load = GLTFDocument.new()
  143. var gltf_state_load = GLTFState.new()
  144. var error = gltf_document_load.append_from_file("/path/to/file.gltf", gltf_state_load)
  145. if error == OK:
  146. var gltf_scene_root_node = gltf_document_load.generate_scene(gltf_state_load)
  147. add_child(gltf_scene_root_node)
  148. else:
  149. show_error("Couldn't load glTF scene (error code: %s)." % error_string(error))
  150. # Save a new glTF scene.
  151. var gltf_document_save := GLTFDocument.new()
  152. var gltf_state_save := GLTFState.new()
  153. gltf_document_save.append_from_scene(gltf_scene_root_node, gltf_state_save)
  154. # The file extension in the output `path` (`.gltf` or `.glb`) determines
  155. # whether the output uses text or binary format.
  156. # `GLTFDocument.generate_buffer()` is also available for saving to memory.
  157. gltf_document_save.write_to_filesystem(gltf_state_save, path)
  158. .. note::
  159. When loading a glTF scene, a *base path* must be set so that external
  160. resources like textures can be loaded correctly. When loading from a file,
  161. the base path is automatically set to the folder containing the file. When
  162. loading from a buffer, this base path must be manually set as there is no
  163. way for Godot to infer this path.
  164. To set the base path, set
  165. :ref:`GLTFState.base_path <class_GLTFState_property_base_path>` on your
  166. GLTFState instance *before* calling
  167. :ref:`GLTFDocument.append_from_buffer <class_GLTFDocument_method_append_from_buffer>`
  168. or :ref:`GLTFDocument.append_from_file <class_GLTFDocument_method_append_from_file>`.
  169. .. _doc_runtime_file_loading_and_saving_fonts:
  170. Fonts
  171. -----
  172. :ref:`FontFile.load_dynamic_font <class_FontFile_method_load_bitmap_font>` supports the following
  173. font file formats: TTF, OTF, WOFF, WOFF2, PFB, PFM
  174. On the other hand, :ref:`FontFile.load_bitmap_font <class_FontFile_method_load_bitmap_font>` supports
  175. the `BMFont <https://www.angelcode.com/products/bmfont/>`__ format (``.fnt`` or ``.font``).
  176. Additionally, it is possible to load any font that is installed on the system using
  177. Godot's support for :ref:`doc_using_fonts_system_fonts`.
  178. Example of loading a font file automatically according to its file extension,
  179. then adding it as a theme override to a :ref:`class_Label` node:
  180. ::
  181. var path = "/path/to/font.ttf"
  182. var path_lower = path.to_lower()
  183. var font_file = FontFile.new()
  184. if (
  185. path_lower.ends_with(".ttf")
  186. or path_lower.ends_with(".otf")
  187. or path_lower.ends_with(".woff")
  188. or path_lower.ends_with(".woff2")
  189. or path_lower.ends_with(".pfb")
  190. or path_lower.ends_with(".pfm")
  191. ):
  192. font_file.load_dynamic_font(path)
  193. elif path_lower.ends_with(".fnt") or path_lower.ends_with(".font"):
  194. font_file.load_bitmap_font(path)
  195. else:
  196. push_error("Invalid font file format.")
  197. if not font_file.data.is_empty():
  198. # If font was loaded successfully, add it as a theme override.
  199. $Label.add_theme_font_override("font", font_file)
  200. ZIP archives
  201. ------------
  202. Godot supports reading and writing ZIP archives using the :ref:`class_zipreader`
  203. and :ref:`class_zippacker` classes. This supports any ZIP file, including files
  204. generated by Godot's "Export PCK/ZIP" functionality (although these will contain
  205. imported Godot resources rather than the original project files).
  206. .. note::
  207. Use :ref:`ProjectSettings.load_resource_pack <class_ProjectSettings_method_load_resource_pack>`
  208. to load PCK or ZIP files exported by Godot as
  209. :ref:`additional data packs <doc_exporting_pcks>`. That approach is preferred
  210. for DLCs, as it makes interacting with additional data packs seamless (virtual filesystem).
  211. This ZIP archive support can be combined with runtime image, 3D scene and audio
  212. loading to provide a seamless modding experience without requiring users to go
  213. through the Godot editor to generate PCK/ZIP files.
  214. Example that lists files in a ZIP archive in an :ref:`class_ItemList` node,
  215. then writes contents read from it to a new ZIP archive (essentially duplicating the archive):
  216. ::
  217. # Load an existing ZIP archive.
  218. var zip_reader = ZIPReader.new()
  219. zip_reader.open(path)
  220. var files = zip_reader.get_files()
  221. # The list of files isn't sorted by default. Sort it for more consistent processing.
  222. files.sort()
  223. for file in files:
  224. $ItemList.add_item(file, null)
  225. # Make folders disabled in the list.
  226. $ItemList.set_item_disabled(-1, file.ends_with("/"))
  227. # Save a new ZIP archive.
  228. var zip_packer = ZIPPacker.new()
  229. var error = zip_packer.open(path)
  230. if error != OK:
  231. push_error("Couldn't open path for saving ZIP archive (error code: %s)." % error_string(error))
  232. return
  233. # Reuse the above ZIPReader instance to read files from an existing ZIP archive.
  234. for file in zip_reader.get_files():
  235. zip_packer.start_file(file)
  236. zip_packer.write_file(zip_reader.read_file(file))
  237. zip_packer.close_file()
  238. zip_packer.close()