godot/lib.rs
1#![cfg_attr(published_docs, feature(doc_cfg))]
2/*
3 * Copyright (c) godot-rust; Bromeon and contributors.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9//! # Rust bindings for Godot 4
10//!
11//! The **gdext** library implements Rust bindings for the [Godot](https://godotengine.org) engine, more precisely its version 4.
12//! It does so using the GDExtension API, a C interface to integrate third-party language bindings with the engine.
13//!
14//! This API doc is accompanied by the [book](https://github.com/godot-rust/book), which provides tutorials
15//! that guide you along the way.
16//!
17//! An overview of fundamental types and concepts can be found on [this page](__docs).
18//!
19//!
20//! ## Module organization
21//!
22//! The contains generated code, which is derived from the GDExtension API specification. This code spans the official Godot API and
23//! is mostly the same as the API you would use in GDScript.
24//!
25//! The Godot API is divided into several modules:
26//!
27//! * [`builtin`]: Built-in types, such as `Vector2`, `Color`, and `String`.
28//! * [`classes`]: Godot classes, such as `Node`, `RefCounted` or `Resource`.
29//! * [`global`]: Global functions and enums, such as `godot_print!`, `smoothstep` or `JoyAxis`.
30//!
31//! In addition to generated code, we provide a framework that allows you to easily interface the Godot engine.
32//! Noteworthy modules in this context are:
33//!
34//! * [`register`], used to register **your own** Rust symbols (classes, methods, constants etc.) with Godot.
35//! * [`obj`], everything related to handling Godot objects, such as the `Gd<T>` type.
36//! * [`tools`], higher-level utilities that extend the generated code, e.g. `load<T>()`.
37//! * [`meta`], fundamental information about types, properties and conversions.
38//! * [`init`], entry point and global library configuration.
39//! * [`task`], integration with async code.
40//!
41//! The [`prelude`] contains often-imported symbols; feel free to `use godot::prelude::*` in your code.
42//! <br><br>
43//!
44//!
45//! ## Public API
46//!
47//! Some symbols in the API are not intended for users, however Rust's visibility feature is not strong enough to express that in all cases
48//! (for example, proc-macros and separated crates may need access to internals).
49//!
50//! The following API symbols are considered private:
51//!
52//! * Symbols annotated with `#[doc(hidden)]`.
53//! * Any of the dependency crates (crate `godot` is the only public interface).
54//! * Modules named `private` and all their contents.
55//!
56//! This means there are **no guarantees** regarding API stability, robustness or correctness. Problems arising from using private APIs are
57//! not considered bugs, and anything relying on them may stop working without announcement. Please refrain from using undocumented and
58//! private features; if you are missing certain functionality, bring it up for discussion instead. This allows us to improve the library!
59//! <br><br>
60//!
61//!
62//! ## Safeguard levels
63//!
64//! godot-rust uses three tiers that differ in the amount of runtime checks and validations that are performed. \
65//! They can be configured via [Cargo features](#cargo-features).
66//!
67//! - 🛡️ **Strict** (default for dev builds)
68//!
69//! Lots of additional, sometimes expensive checks. Detects many bugs during development.
70//! - `Gd::bind/bind_mut()` provides extensive diagnostics to locate runtime borrow errors.
71//! - `Array` safe conversion checks (for types like `Array<i8>`).
72//! - RTTI checks on object access (protect against type mismatch edge cases).
73//! - Geometric invariants (e.g. normalized quaternions).
74//! - Access to engine APIs outside valid scope.<br><br>
75//!
76//! - ⚖️ **Balanced** (default for release builds)
77//!
78//! Basic validity and invariant checks, reasonably fast. Within this level, you should not be able to encounter undefined behavior (UB)
79//! in safe Rust code. Invariant violations may however cause panics and logic errors.
80//! - Object liveness checks.
81//! - `Gd::bind/bind_mut()` cause panics on borrow errors.<br><br>
82//!
83//! - ☣️ **Disengaged**
84//!
85//! Most checks disabled, sacrifices safety for raw speed. This renders a large part of the godot-rust API `unsafe` without polluting the
86//! code; you opt in via `unsafe impl ExtensionLibrary`.
87//!
88//! Before using this, measure to ensure you truly need the last bit of performance (balanced should be fast enough for most cases; if not,
89//! consider bringing it up). Also test your code thoroughly using the other levels first. Undefined behavior and crashes arising
90//! from using this level are your full responsibility. When reporting a bug, make sure you can reproduce it under the balanced level.
91//! - Unchecked object access -> instant UB if an object is dead.
92//! - `Gd::bind/bind_mut()` are unchecked -> UB if mutable aliasing occurs.
93//!
94//! <div class="warning">
95//! <p>Safeguards are a recent addition to godot-rust and need calibrating over time. If you are unhappy with how the <i>balanced</i> level
96//! performs in basic operations, consider bringing it up for discussion. We'd like to offer the <i>disengaged</i> level for power users who
97//! really need it, but it shouldn't be the only choice for decent runtime performance, as it comes with heavy trade-offs.</p>
98//!
99//! <p>As of v0.4, the above checks are not fully implemented yet. Neither are they guarantees; categorization may change over time.</p>
100//! </div>
101//!
102//!
103//! ## Cargo features
104//!
105//! The following features can be enabled for this crate. All of them are off by default.
106//!
107//! Avoid `default-features = false` unless you know exactly what you are doing; it will disable some required internal features.
108//!
109//! _Godot version and configuration:_
110//!
111//! * **`api-4-{minor}`**
112//! * **`api-custom`**
113//! * **`api-custom-json`**
114//!
115//! Sets the [**API level**](https://godot-rust.github.io/book/toolchain/godot-version.html) to the specified Godot version,
116//! or a custom-built local binary.
117//! You can use at most one `api-*` feature. If absent, the current Godot minor version is used, with patch level 0.
118//!
119//! `api-custom` feature requires specifying `GDRUST_GODOT_BIN` environment variable with a path to your Godot4 binary.
120//!
121//! The `api-custom-json` feature requires specifying `GDRUST_GODOT_API_JSON` environment variable with a path
122//! to your custom-defined `extension_api.json`.<br><br>
123//!
124//! * **`double-precision`**
125//!
126//! Use `f64` instead of `f32` for the floating-point type [`real`][type@builtin::real]. Requires Godot to be compiled with the
127//! scons flag `precision=double`.<br><br>
128//!
129//! * **`experimental-godot-api`**
130//!
131//! Access to `godot::classes` APIs that Godot marks "experimental". These are under heavy development and may change at any time.
132//! If you opt in to this feature, expect breaking changes at compile and runtime.<br><br>
133//!
134//! _Rust functionality toggles:_
135//!
136//! * **`lazy-function-tables`**
137//!
138//! Instead of loading all engine function pointers at startup, load them lazily on first use. This reduces startup time and RAM usage, but
139//! incurs additional overhead in each FFI call. Also, you lose the guarantee that once the library has booted, all function pointers are
140//! truly available. Function calls may thus panic only at runtime, possibly in deeply nested code paths.
141//! This feature is not yet thread-safe and can thus not be combined with `experimental-threads`.<br><br>
142//!
143//! * **`experimental-threads`**
144//!
145//! Experimental threading support. This adds synchronization to access the user instance in `Gd<T>` and disables several single-thread checks.
146//! The safety aspects are not ironed out yet; there is a high risk of unsoundness at the moment.
147//! As this evolves, it is very likely that the API becomes stricter.<br><br>
148//!
149//! * **`experimental-wasm`**
150//!
151//! Support for WebAssembly exports is still a work-in-progress and is not yet well tested. This feature is in place for users
152//! to explicitly opt in to any instabilities or rough edges that may result.
153//!
154//! Please read [Export to Web](https://godot-rust.github.io/book/toolchain/export-web.html) in the book.
155//!
156//! By default, Wasm threads are enabled and require the flag `"-C", "link-args=-pthread"` in the `wasm32-unknown-unknown` target.
157//! This must be kept in sync with Godot's Web export settings (threading support enabled). To disable it, use **additionally* the feature
158//! `experimental-wasm-nothreads`.
159//!
160//! It is recommended to use this feature in combination with `lazy-function-tables` to reduce the size of the generated Wasm binary.<br><br>
161//!
162//! * **`experimental-wasm-nothreads`**
163//!
164//! Requires the `experimental-wasm` feature. Disables threading support for WebAssembly exports. This needs to be kept in sync with
165//! Godot's Web export setting (threading support disabled), and must _not_ use the `"-C", "link-args=-pthread"` flag in the
166//! `wasm32-unknown-unknown` target.<br><br>
167//!
168//! * **`codegen-rustfmt`**
169//!
170//! Use rustfmt to format generated binding code. Because rustfmt is so slow, this is detrimental to initial compile time.
171//! Without it, we use a lightweight and fast custom formatter to enable basic human readability.<br><br>
172//!
173//! * **`register-docs`**
174//!
175//! Generates documentation for your structs from your Rust documentation.
176//! Documentation is visible in Godot via `F1` -> searching for that class.
177//! This feature requires at least Godot 4.3.
178//! See also: [`#[derive(GodotClass)]`](register/derive.GodotClass.html#documentation)
179//!
180//! _Safeguards:_
181//!
182//! See [Safeguard levels](#safeguard-levels).
183//!
184//! * **`safeguards-dev-balanced`**
185//!
186//! For the `dev` Cargo profile, use the **balanced** safeguard level instead of the default strict level.<br><br>
187//!
188//! * **`safeguards-release-disengaged`**
189//!
190//! For the `release` Cargo profile, use the **disengaged** safeguard level instead of the default balanced level.
191//!
192//! _Third-party integrations:_
193//!
194//! * **`serde`**
195//!
196//! Implement the [serde](https://serde.rs/) traits `Serialize` and `Deserialize` traits for certain built-in types.
197//! The serialized representation underlies **no stability guarantees** and may change at any time, even without a SemVer-breaking change.
198//!
199
200#![doc(
201 html_logo_url = "https://raw.githubusercontent.com/godot-rust/assets/master/gdext/ferris.svg"
202)]
203
204#[cfg(doc)]
205pub mod __docs;
206
207// ----------------------------------------------------------------------------------------------------------------------------------------------
208// Validations
209
210// Many validations are moved to godot-ffi. #[cfg]s are not emitted in this crate, so move checks for those up to godot-core.
211
212#[cfg(all(target_family = "wasm", not(feature = "experimental-wasm")))]
213compile_error!(
214 "Wasm target requires opt-in via `experimental-wasm` Cargo feature;\n\
215 keep in mind that this is work in progress."
216);
217
218// See also https://github.com/godotengine/godot/issues/86346.
219// Could technically be moved to godot-codegen to reduce time-to-failure slightly, but would scatter validations even more.
220#[cfg(all(
221 feature = "double-precision",
222 not(feature = "api-custom"),
223 not(feature = "api-custom-json")
224))]
225compile_error!(
226 "The feature `double-precision` currently requires `api-custom` or `api-custom-json` due to incompatibilities in the GDExtension API JSON. \
227See: https://github.com/godotengine/godot/issues/86346"
228);
229
230// On non-Emscripen targets, wasm-ld will insert a call to __wasm_call_ctors (which calls all constructors) to the start all exported functions,
231// if it detects that __wasm_call_ctors is never called and not exported. This could cause constructors to run multiple times.
232// Emscripen should always export __wasm_call_ctors and call it at runtime.
233// See https://github.com/godot-rust/gdext/pull/1476 for more info and links.
234#[cfg(all(target_family = "wasm", not(target_os = "emscripten")))]
235compile_error!("Wasm targets not using Emscripten are not supported.");
236
237// ----------------------------------------------------------------------------------------------------------------------------------------------
238// Modules
239
240#[doc(hidden)]
241pub use godot_core::possibly_docs as docs;
242#[doc(hidden)]
243pub use godot_core::sys;
244#[doc(inline)]
245pub use godot_core::{builtin, classes, global, meta, obj, task, tools};
246
247/// Entry point and global init/shutdown of the library.
248pub mod init {
249 pub use godot_core::init::*;
250 // Re-exports
251 pub use godot_macros::gdextension;
252}
253
254/// Register/export Rust symbols to Godot: classes, methods, enums...
255pub mod register {
256 #[cfg(feature = "__codegen-full")]
257 pub use godot_core::registry::RpcConfig;
258 pub use godot_core::registry::property;
259 pub use godot_core::registry::signal::re_export::*;
260 pub use godot_macros::{Export, GodotClass, GodotConvert, Var, godot_api, godot_dyn};
261
262 /// Re-exports used by proc-macro API.
263 #[doc(hidden)]
264 pub mod private {
265 #[cfg(feature = "__codegen-full")]
266 pub use godot_core::registry::class::auto_register_rpcs;
267 pub use godot_core::registry::godot_register_wrappers::*;
268 pub use godot_core::registry::{constant, method};
269 }
270}
271
272/// Testing facilities (unstable).
273#[doc(hidden)]
274pub mod test {
275 pub use godot_macros::{bench, itest};
276}
277
278#[doc(hidden)]
279pub use godot_core::__deprecated;
280#[doc(hidden)]
281pub use godot_core::private;
282
283/// Often-imported symbols.
284pub mod prelude;