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-4-{minor}-{patch}`**
113//! * **`api-custom`**
114//! * **`api-custom-json`**
115//!
116//!   Sets the [**API level**](https://godot-rust.github.io/book/toolchain/godot-version.html) to the specified Godot version,
117//!   or a custom-built local binary.
118//!   You can use at most one `api-*` feature. If absent, the current Godot minor version is used, with patch level 0.
119//!
120//!   `api-custom` feature requires specifying `GODOT4_BIN` environment variable with a path to your Godot4 binary.
121//!
122//!   The `api-custom-json` feature requires specifying `GODOT4_GDEXTENSION_JSON` environment variable with a path
123//!   to your custom-defined `extension_api.json`.<br><br>
124//!
125//! * **`double-precision`**
126//!
127//!   Use `f64` instead of `f32` for the floating-point type [`real`][type@builtin::real]. Requires Godot to be compiled with the
128//!   scons flag `precision=double`.<br><br>
129//!
130//! * **`experimental-godot-api`**
131//!
132//!   Access to `godot::classes` APIs that Godot marks "experimental". These are under heavy development and may change at any time.
133//!   If you opt in to this feature, expect breaking changes at compile and runtime.<br><br>
134//!
135//! * **`experimental-required-objs`**
136//!
137//!   Enables _required_ objects in Godot function signatures. When GDExtension advertises parameters or return value as required (non-null), the
138//!   generated code will use `Gd<T>` instead of `Option<Gd<T>>` for type safety. This will undergo many breaking changes as the API evolves;
139//!   we are explicitly excluding this from any SemVer guarantees. Needs Godot 4.6-dev. See <https://github.com/godot-rust/gdext/pull/1383>.
140//!
141//! _Rust functionality toggles:_
142//!
143//! * **`lazy-function-tables`**
144//!
145//!   Instead of loading all engine function pointers at startup, load them lazily on first use. This reduces startup time and RAM usage, but
146//!   incurs additional overhead in each FFI call. Also, you lose the guarantee that once the library has booted, all function pointers are
147//!   truly available. Function calls may thus panic only at runtime, possibly in deeply nested code paths.
148//!   This feature is not yet thread-safe and can thus not be combined with `experimental-threads`.<br><br>
149//!
150//! * **`experimental-threads`**
151//!
152//!   Experimental threading support. This adds synchronization to access the user instance in `Gd<T>` and disables several single-thread checks.
153//!   The safety aspects are not ironed out yet; there is a high risk of unsoundness at the moment.
154//!   As this evolves, it is very likely that the API becomes stricter.<br><br>
155//!
156//! * **`experimental-wasm`**
157//!
158//!   Support for WebAssembly exports is still a work-in-progress and is not yet well tested. This feature is in place for users
159//!   to explicitly opt in to any instabilities or rough edges that may result.
160//!
161//!   Please read [Export to Web](https://godot-rust.github.io/book/toolchain/export-web.html) in the book.
162//!
163//!   By default, Wasm threads are enabled and require the flag `"-C", "link-args=-pthread"` in the `wasm32-unknown-unknown` target.
164//!   This must be kept in sync with Godot's Web export settings (threading support enabled). To disable it, use **additionally* the feature
165//!   `experimental-wasm-nothreads`.
166//!
167//!   It is recommended to use this feature in combination with `lazy-function-tables` to reduce the size of the generated Wasm binary.<br><br>
168//!
169//! * **`experimental-wasm-nothreads`**
170//!
171//!   Requires the `experimental-wasm` feature. Disables threading support for WebAssembly exports. This needs to be kept in sync with
172//!   Godot's Web export setting (threading support disabled), and must _not_ use the `"-C", "link-args=-pthread"` flag in the
173//!   `wasm32-unknown-unknown` target.<br><br>
174//!
175//! * **`codegen-rustfmt`**
176//!
177//!   Use rustfmt to format generated binding code. Because rustfmt is so slow, this is detrimental to initial compile time.
178//!   Without it, we use a lightweight and fast custom formatter to enable basic human readability.<br><br>
179//!
180//! * **`register-docs`**
181//!
182//!   Generates documentation for your structs from your Rust documentation.
183//!   Documentation is visible in Godot via `F1` -> searching for that class.
184//!   This feature requires at least Godot 4.3.
185//!   See also: [`#[derive(GodotClass)]`](register/derive.GodotClass.html#documentation)
186//!
187//! _Safeguards:_
188//!
189//! See [Safeguard levels](#safeguard-levels).
190//!
191//! * **`safeguards-dev-balanced`**
192//!
193//!   For the `dev` Cargo profile, use the **balanced** safeguard level instead of the default strict level.<br><br>
194//!
195//! * **`safeguards-release-disengaged`**
196//!
197//!   For the `release` Cargo profile, use the **disengaged** safeguard level instead of the default balanced level.
198//!
199//! _Third-party integrations:_
200//!
201//! * **`serde`**
202//!
203//!   Implement the [serde](https://serde.rs/) traits `Serialize` and `Deserialize` traits for certain built-in types.
204//!   The serialized representation underlies **no stability guarantees** and may change at any time, even without a SemVer-breaking change.
205//!
206
207#![doc(
208    html_logo_url = "https://raw.githubusercontent.com/godot-rust/assets/master/gdext/ferris.svg"
209)]
210
211#[cfg(doc)]
212pub mod __docs;
213
214// ----------------------------------------------------------------------------------------------------------------------------------------------
215// Validations
216
217// Many validations are moved to godot-ffi. #[cfg]s are not emitted in this crate, so move checks for those up to godot-core.
218
219#[cfg(all(target_family = "wasm", not(feature = "experimental-wasm")))]
220compile_error!(
221    "Wasm target requires opt-in via `experimental-wasm` Cargo feature;\n\
222    keep in mind that this is work in progress."
223);
224
225// See also https://github.com/godotengine/godot/issues/86346.
226// Could technically be moved to godot-codegen to reduce time-to-failure slightly, but would scatter validations even more.
227#[cfg(all(
228    feature = "double-precision",
229    not(feature = "api-custom"),
230    not(feature = "api-custom-json")
231))]
232compile_error!("The feature `double-precision` currently requires `api-custom` or `api-custom-json` due to incompatibilities in the GDExtension API JSON. \
233See: https://github.com/godotengine/godot/issues/86346");
234
235// ----------------------------------------------------------------------------------------------------------------------------------------------
236// Modules
237
238#[doc(hidden)]
239pub use godot_core::possibly_docs as docs;
240#[doc(hidden)]
241pub use godot_core::sys;
242#[doc(inline)]
243pub use godot_core::{builtin, classes, global, meta, obj, task, tools};
244
245/// Entry point and global init/shutdown of the library.
246pub mod init {
247    pub use godot_core::init::*;
248    // Re-exports
249    pub use godot_macros::gdextension;
250}
251
252/// Register/export Rust symbols to Godot: classes, methods, enums...
253pub mod register {
254    pub use godot_core::registry::property;
255    pub use godot_core::registry::signal::re_export::*;
256    #[cfg(feature = "__codegen-full")]
257    pub use godot_core::registry::RpcConfig;
258    pub use godot_macros::{godot_api, godot_dyn, Export, GodotClass, GodotConvert, Var};
259
260    /// Re-exports used by proc-macro API.
261    #[doc(hidden)]
262    pub mod private {
263        #[cfg(feature = "__codegen-full")]
264        pub use godot_core::registry::class::auto_register_rpcs;
265        pub use godot_core::registry::godot_register_wrappers::*;
266        pub use godot_core::registry::{constant, method};
267    }
268}
269
270/// Testing facilities (unstable).
271#[doc(hidden)]
272pub mod test {
273    pub use godot_macros::{bench, itest};
274}
275
276#[doc(hidden)]
277pub use godot_core::__deprecated;
278#[doc(hidden)]
279pub use godot_core::private;
280
281/// Often-imported symbols.
282pub mod prelude;
283
284/// Tests for code that must not compile.
285// Do not add #[cfg(test)], it seems to break `cargo test -p godot --features godot/api-custom,godot/experimental-required-objs`.
286mod no_compile_tests {
287    /// ```compile_fail
288    /// use godot::prelude::*;
289    /// let mut node: Gd<Node> = todo!();
290    /// let option = Some(node.clone());
291    /// let option: Option<&Gd<Node>> = option.as_ref();
292    ///
293    /// // Following must not compile since `add_child` accepts only required (non-null) arguments. Comment-out for sanity check.
294    /// node.add_child(option);
295    /// ```
296    #[cfg(feature = "experimental-required-objs")]
297    fn __test_invalid_patterns() {}
298}