godot-core 0.5.1

Internal crate used by godot-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
 * Copyright (c) godot-rust; Bromeon and contributors.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use std::sync::atomic::{AtomicBool, Ordering};

use godot_ffi as sys;
use sys::GodotFfi;

use crate::builtin::{GString, StringName};
use crate::obj::Singleton;
use crate::out;

mod reexport_pub {
    // `Engine::singleton()` is not available before `InitLevel::Scenes` for Godot before 4.4.
    #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
    pub use super::sys::is_editor_hint;
    #[cfg(not(wasm_nothreads))] #[cfg_attr(published_docs, doc(cfg(not(wasm_nothreads))))]
    pub use super::sys::main_thread_id;
    pub use super::sys::{GdextBuild, InitStage, is_main_thread};
}
pub use reexport_pub::*;

use crate::obj::signal::prune_stored_signal_connections;

#[repr(C)]
struct InitUserData {
    library: sys::GDExtensionClassLibraryPtr,
    #[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
    main_loop_callbacks: sys::GDExtensionMainLoopCallbacks,
}

#[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
unsafe extern "C" fn startup_func<E: ExtensionLibrary>() {
    let ctx = || "ExtensionLibrary::on_stage_init(MainLoop)".to_string();

    swallow_panics(ctx, || {
        E::on_stage_init(InitStage::MainLoop);
    });

    // Now that editor UI is ready, display all warnings/error collected so far.
    sys::print_deferred_startup_messages();
}

#[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
unsafe extern "C" fn frame_func<E: ExtensionLibrary>() {
    let ctx = || "ExtensionLibrary::on_main_loop_frame()".to_string();

    swallow_panics(ctx, || {
        E::on_main_loop_frame();
    });
}

#[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
unsafe extern "C" fn shutdown_func<E: ExtensionLibrary>() {
    let ctx = || "ExtensionLibrary::on_stage_deinit(MainLoop)".to_string();

    swallow_panics(ctx, || {
        E::on_stage_deinit(InitStage::MainLoop);
    });
}

#[doc(hidden)]
pub unsafe fn __gdext_load_library<E: ExtensionLibrary>(
    get_proc_address: sys::GDExtensionInterfaceGetProcAddress,
    library: sys::GDExtensionClassLibraryPtr,
    init: *mut sys::GDExtensionInitialization,
) -> sys::GDExtensionBool {
    let init_code = || {
        // Make sure the first thing we do is check whether hot reloading should be enabled or not. This is to ensure that if we do anything to
        // cause TLS-destructors to run then we have a setting already for how to deal with them. Otherwise, this could cause the default
        // behavior to kick in and disable hot reloading.
        #[cfg(target_os = "linux")] #[cfg_attr(published_docs, doc(cfg(target_os = "linux")))]
        sys::linux_reload_workaround::default_set_hot_reload();

        let tool_only_in_editor = match E::editor_run_behavior() {
            EditorRunBehavior::ToolClassesOnly => true,
            EditorRunBehavior::AllClasses => false,
        };

        let config = sys::GdextConfig::new(tool_only_in_editor);

        // SAFETY: no custom code has run yet + no other thread is accessing global handle.
        unsafe {
            sys::initialize(get_proc_address, library, config);
        }

        // With experimental-features enabled, we can always print panics to godot_print!
        #[cfg(feature = "experimental-threads")] #[cfg_attr(published_docs, doc(cfg(feature = "experimental-threads")))]
        crate::private::set_gdext_hook(|| true);

        // Without experimental-features enabled, we can only print panics with godot_print! if the panic occurs on the main (Godot) thread.
        #[cfg(not(feature = "experimental-threads"))]
        {
            let main_thread = std::thread::current().id();
            crate::private::set_gdext_hook(move || std::thread::current().id() == main_thread);
        }

        // Currently no way to express failure; could be exposed to E if necessary.
        // No early exit, unclear if Godot still requires output parameters to be set.
        let success = true;
        // Leak the userdata. It will be dropped in core level deinitialization.
        let userdata = Box::into_raw(Box::new(InitUserData {
            library,
            #[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
            main_loop_callbacks: sys::GDExtensionMainLoopCallbacks {
                startup_func: Some(startup_func::<E>),
                frame_func: Some(frame_func::<E>),
                shutdown_func: Some(shutdown_func::<E>),
            },
        }));

        let godot_init_params = sys::GDExtensionInitialization {
            minimum_initialization_level: E::min_level().to_sys(),
            userdata: userdata.cast::<std::ffi::c_void>(),
            initialize: Some(ffi_initialize_layer::<E>),
            deinitialize: Some(ffi_deinitialize_layer::<E>),
        };

        // SAFETY: Godot is responsible for passing us a valid pointer.
        unsafe {
            *init = godot_init_params;
        }

        success as u8
    };

    // Use std::panic::catch_unwind instead of handle_panic: handle_panic uses TLS, which
    // calls `thread_atexit` on linux, which sets the hot reloading flag on linux.
    // Using std::panic::catch_unwind avoids this, although we lose out on context information
    // for debugging.
    let is_success = std::panic::catch_unwind(init_code);

    is_success.unwrap_or(0)
}

static LEVEL_SERVERS_CORE_LOADED: AtomicBool = AtomicBool::new(false);

unsafe extern "C" fn ffi_initialize_layer<E: ExtensionLibrary>(
    userdata: *mut std::ffi::c_void,
    init_level: sys::GDExtensionInitializationLevel,
) {
    unsafe {
        let userdata = userdata.cast::<InitUserData>().as_ref().unwrap();
        let level = InitLevel::from_sys(init_level);
        let ctx = || format!("ExtensionLibrary::on_stage_init({level:?})");

        fn try_load<E: ExtensionLibrary>(level: InitLevel, userdata: &InitUserData) {
            // Workaround for https://github.com/godot-rust/gdext/issues/629:
            // When using editor plugins, Godot may unload all levels but only reload from Scene upward.
            // Manually run initialization of lower levels.

            // TODO: Remove this workaround once after the upstream issue is resolved.
            if level == InitLevel::Scene {
                if !LEVEL_SERVERS_CORE_LOADED.load(Ordering::Relaxed) {
                    try_load::<E>(InitLevel::Core, userdata);
                    try_load::<E>(InitLevel::Servers, userdata);
                }
            } else if level == InitLevel::Core {
                // When it's normal initialization, the `Servers` level is normally initialized.
                LEVEL_SERVERS_CORE_LOADED.store(true, Ordering::Relaxed);
            }

            // SAFETY: Godot will call this from the main thread, after `__gdext_load_library` where the library is initialized,
            // and only once per level.
            unsafe { gdext_on_level_init(level, userdata) };
            E::on_stage_init(level.to_stage());
        }

        // TODO consider crashing if gdext init fails.
        swallow_panics(ctx, || {
            try_load::<E>(level, userdata);
        });
    }
}

unsafe extern "C" fn ffi_deinitialize_layer<E: ExtensionLibrary>(
    userdata: *mut std::ffi::c_void,
    init_level: sys::GDExtensionInitializationLevel,
) {
    unsafe {
        let level = InitLevel::from_sys(init_level);
        let ctx = || format!("ExtensionLibrary::on_stage_deinit({level:?})");

        swallow_panics(ctx, || {
            if level == InitLevel::Core {
                // Once the CORE api is unloaded, reset the flag to initial state.
                LEVEL_SERVERS_CORE_LOADED.store(false, Ordering::Relaxed);

                // Drop the userdata.
                drop(Box::from_raw(userdata.cast::<InitUserData>()));
            }

            E::on_stage_deinit(level.to_stage());
            gdext_on_level_deinit(level);
        });
    }
}

/// Tasks needed to be done by gdext internally upon loading an initialization level. Called before user code.
///
/// # Safety
///
/// - Must be called from the main thread.
/// - The interface must have been initialized.
/// - Must only be called once per level.
unsafe fn gdext_on_level_init(level: InitLevel, _userdata: &InitUserData) {
    // TODO: in theory, a user could start a thread in one of the early levels, and run concurrent code that messes with the global state
    // (e.g. class registration). This would break the assumption that the load_class_method_table() calls are exclusive.
    // We could maybe protect globals with a mutex until initialization is complete, and then move it to a directly-accessible, read-only static.

    // SAFETY: we are in the main thread, initialize has been called, has never been called with this level before.
    unsafe { sys::load_class_method_table(level) };

    match level {
        InitLevel::Core => {
            #[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
            unsafe {
                sys::interface_fn!(register_main_loop_callbacks)(
                    _userdata.library,
                    &raw const _userdata.main_loop_callbacks,
                )
            };

            #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
            sys::set_editor_hint(crate::classes::Engine::singleton().is_editor_hint());
        }
        InitLevel::Servers => {
            // SAFETY: called from the main thread, sys::initialized has already been called.
            unsafe { sys::discover_main_thread() };
        }
        InitLevel::Scene => {
            // SAFETY: On the main thread, api initialized, `Scene` was initialized above.
            unsafe { ensure_godot_features_compatible() };
        }
        InitLevel::Editor => {
            #[cfg(all(since_api = "4.3", feature = "register-docs"))]
            // SAFETY: Godot binding is initialized, and this is called from the main thread.
            unsafe {
                crate::docs::register();
            }
        }
    }

    crate::registry::class::auto_register_classes(level);
}

/// Tasks needed to be done by gdext internally upon unloading an initialization level. Called after user code.
fn gdext_on_level_deinit(level: InitLevel) {
    if level == InitLevel::Editor {
        prune_stored_signal_connections();
    }

    crate::registry::class::unregister_classes(level);

    if level == InitLevel::Core {
        // If lowest level is unloaded, call global deinitialization.
        // No business logic by itself, but ensures consistency if re-initialization (hot-reload on Linux) occurs.

        crate::task::cleanup();
        crate::tools::cleanup();

        // Garbage-collect various statics.
        // SAFETY: this is the last time meta APIs are used.
        unsafe {
            crate::meta::cleanup();
        }

        // SAFETY: called after all other logic, so no concurrent access.
        // TODO: multithreading must make sure other threads are joined/stopped here.
        unsafe {
            sys::deinitialize();
        }
    }
}

/// Catches panics without propagating them further. Prints error messages.
fn swallow_panics<E, F>(error_context: E, code: F)
where
    E: Fn() -> String,
    F: FnOnce() + std::panic::UnwindSafe,
{
    let _ = crate::private::handle_panic(error_context, code);
}

// ----------------------------------------------------------------------------------------------------------------------------------------------

/// Defines the entry point for a GDExtension Rust library.
///
/// Every library should have exactly one implementation of this trait. It is always used in combination with the
/// [`#[gdextension]`][gdextension] proc-macro attribute.
///
/// # Example
/// The simplest usage is as follows. This will automatically perform the necessary init and cleanup routines, and register
/// all classes marked with `#[derive(GodotClass)]`, without needing to mention them in a central list. The order in which
/// classes are registered is not specified.
///
/// ```
/// use godot::init::*;
///
/// struct MyExtension;
///
/// #[gdextension]
/// unsafe impl ExtensionLibrary for MyExtension {}
/// ```
///
/// # Custom entry symbol
/// There is usually no reason to, but you can use a different entry point (C function in the dynamic library). This must match the key
/// that you specify in the `.gdextension` file. Let's say your `.gdextension` file has such a section:
/// ```toml
/// [configuration]
/// entry_symbol = "custom_name"
/// ```
/// then you can implement the trait like this:
/// ```no_run
/// # use godot::init::*;
/// struct MyExtension;
///
/// #[gdextension(entry_symbol = custom_name)]
/// unsafe impl ExtensionLibrary for MyExtension {}
/// ```
/// Note that this only changes the name. You cannot provide your own function -- use the [`on_stage_init()`][ExtensionLibrary::on_stage_init]
/// hook for custom startup logic.
///
/// # Availability of Godot APIs during init and deinit
// Init order: see also special_cases.rs > classify_codegen_level().
/// Godot loads functionality gradually during its startup routines, and unloads it during shutdown. As a result, Godot classes are only
/// available above a certain level. Trying to access a class API when it's not available will panic (if not, please report it as a bug).
///
/// A few singletons (`Engine`, `Os`, `Time`, `ProjectSettings`) are available from the `Core` level onward and can be used inside
/// this method. Most other singletons are **not available during init** at all, and will only become accessible once the first frame has
/// run.
///
/// The exact time a class is available depends on the Godot initialization logic, which is quite complex and may change between versions.
/// To get an up-to-date view, inspect the Godot source code of [main.cpp], particularly `Main::setup()`, `Main::setup2()` and
/// `Main::cleanup()` methods. Make sure to look at the correct version of the file.
///
/// In case of doubt, do not rely on classes being available during init/deinit.
///
/// [main.cpp]: https://github.com/godotengine/godot/blob/master/main/main.cpp
///
/// # Safety
/// The library cannot enforce any safety guarantees outside Rust code, which means that **you as a user** are
/// responsible to uphold them: namely in GDScript code or other GDExtension bindings loaded by the engine.
/// Violating this may cause undefined behavior, even when invoking _safe_ functions.
///
/// If you use the `disengaged` [safeguard level], you accept that UB becomes possible even **in safe Rust APIs**, if you use them wrong
/// (e.g. accessing a destroyed object).
///
/// # Using other GDExtension libraries as dependencies
///
/// When using any other GDExtension library as a dependency, the implementor of the user-forwarding `ExtensionLibrary` must be specified
/// via the `GDRUST_MAIN_EXTENSION` environment variable. That _main_ crate will be responsible
/// for loading all classes, as well as managing the `ExtensionLibrary` callbacks.
///
/// For example, you have a workspace with a crate `my-extension`, that uses libraries `lib-a` and `lib-b` as dependencies.
/// If the `impl ExtensionLibrary` is called `MyExtension`, then you can build all crates in the workspace with:
///
/// ```bash
/// GDRUST_MAIN_EXTENSION="MyExtension" cargo build
/// ```
///
/// ```ignore
/// // lib.rs of my-extension crate.
/// // Usage of other dependencies must be explicitly declared; otherwise, they won't be registered.
/// extern crate lib_a;
/// extern crate lib_b;
///
/// struct MyExtension;
///
/// #[gdextension]
/// unsafe impl ExtensionLibrary for MyExtension {}
/// ```
///
/// The name of the `ExtensionLibrary` implementor must be unique and different from those used by its dependencies.
///
/// Given dependencies must be compilable as `rlib`. That is, they either specify `rlib` as a possible crate-type in their `Cargo.toml`:
///
/// ```ignore
/// # my_dependency/Cargo.toml
///
/// [lib]
/// crate-type = ["cdylib", "rlib"]
/// ```
///
/// Or do not specify `[lib]` at all (and are compiled with `cargo rustc --features ... --crate-type cdylib` instead).
///
/// Note that it is the user's responsibility to ensure that the same classes are not loaded twice –
/// which might be a result of loading another extension in the project which already defines said classes.
/// Do not use this feature to bundle dependencies to end-users unless it is necessary to do so.
///
/// [gdextension]: attr.gdextension.html
/// [safety]: https://godot-rust.github.io/book/gdext/advanced/safety.html
/// [safeguard level]: ../index.html#safeguard-levels
// FIXME intra-doc link
#[doc(alias = "entry_symbol", alias = "entry_point")]
pub unsafe trait ExtensionLibrary {
    /// Determines if and how an extension's code is run in the editor.
    fn editor_run_behavior() -> EditorRunBehavior {
        EditorRunBehavior::ToolClassesOnly
    }

    /// Determines the initialization level at which the extension is loaded (`Scene` by default).
    ///
    /// If the level is lower than [`InitLevel::Scene`], the engine needs to be restarted to take effect.
    fn min_level() -> InitLevel {
        InitLevel::Scene
    }

    /// Custom logic when a certain initialization stage is loaded.
    ///
    /// This will be invoked for stages >= [`Self::min_level()`], in ascending order. Use `if` or `match` to hook to specific stages.
    ///
    /// The stages are loaded in order: `Core` → `Servers` → `Scene` → `Editor` (if in editor) → `MainLoop` (4.5+).  \
    /// The `MainLoop` stage represents the fully initialized state of Godot, after all initialization levels and classes have been loaded.
    ///
    /// See also [`on_main_loop_frame()`][Self::on_main_loop_frame] for per-frame processing.
    ///
    /// # Panics
    /// If the overridden method panics, an error will be printed, but GDExtension loading is **not** aborted.
    #[allow(unused_variables)]
    fn on_stage_init(stage: InitStage) {}

    /// Custom logic when a certain initialization stage is unloaded.
    ///
    /// This will be invoked for stages >= [`Self::min_level()`], in descending order. Use `if` or `match` to hook to specific stages.
    ///
    /// The stages are unloaded in reverse order: `MainLoop` (4.5+) → `Editor` (if in editor) → `Scene` → `Servers` → `Core`.  \
    /// At the time `MainLoop` is deinitialized, all classes are still available.
    ///
    /// # Panics
    /// If the overridden method panics, an error will be printed, but GDExtension unloading is **not** aborted.
    #[allow(unused_variables)]
    fn on_stage_deinit(stage: InitStage) {}

    /// Callback invoked for every process frame.
    ///
    /// This is called during the main loop, after Godot is fully initialized. It runs after all
    /// [`process()`][crate::classes::INode::process] methods on Node, and before the Godot-internal `ScriptServer::frame()`.
    /// This is intended to be the equivalent of [`IScriptLanguageExtension::frame()`][`crate::classes::IScriptLanguageExtension::frame()`]
    /// for GDExtension language bindings that don't use the script API.
    ///
    /// # Example
    /// To hook into startup/shutdown of the main loop, use [`on_stage_init()`][Self::on_stage_init] and
    /// [`on_stage_deinit()`][Self::on_stage_deinit] and watch for [`InitStage::MainLoop`].
    ///
    /// ```no_run
    /// # use godot::init::*;
    /// # struct MyExtension;
    /// #[gdextension]
    /// unsafe impl ExtensionLibrary for MyExtension {
    ///     fn on_stage_init(stage: InitStage) {
    ///         if stage == InitStage::MainLoop {
    ///             // Startup code after fully initialized.
    ///         }
    ///     }
    ///
    ///     fn on_main_loop_frame() {
    ///         // Per-frame logic.
    ///     }
    ///
    ///     fn on_stage_deinit(stage: InitStage) {
    ///         if stage == InitStage::MainLoop {
    ///             // Cleanup code before shutdown.
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Panics
    /// If the overridden method panics, an error will be printed, but execution continues.
    #[cfg(since_api = "4.5")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.5")))]
    fn on_main_loop_frame() {}
}

/// Determines if and how an extension's code is run in the editor.
///
/// By default, Godot 4 runs all virtual lifecycle callbacks (`_ready`, `_process`, `_physics_process`, ...)
/// for extensions. This behavior is different from Godot 3, where extension classes needed to be explicitly
/// marked as "tool".
///
/// In many cases, users write extension code with the intention to run in games, not inside the editor.
/// This is why the default behavior in gdext deviates from Godot: lifecycle callbacks are disabled inside the
/// editor (see [`ToolClassesOnly`][Self::ToolClassesOnly]). It is possible to configure this.
///
/// See also [`ExtensionLibrary::editor_run_behavior()`].
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub enum EditorRunBehavior {
    /// Only runs `#[class(tool)]` classes in the editor.
    ///
    /// All classes are registered, and calls from GDScript to Rust are possible. However, virtual lifecycle callbacks
    /// (`_ready`, `_process`, `_physics_process`, ...) are not run unless the class is annotated with `#[class(tool)]`.
    ToolClassesOnly,

    /// Runs the extension with full functionality in editor.
    ///
    /// Ignores any `#[class(tool)]` annotations.
    AllClasses,
}

// ----------------------------------------------------------------------------------------------------------------------------------------------

pub use sys::InitLevel;

// ----------------------------------------------------------------------------------------------------------------------------------------------

/// # Safety
///
/// - Must be called from the main thread.
/// - The interface must be initialized.
/// - The `Scene` api level must have been initialized.
unsafe fn ensure_godot_features_compatible() {
    // The reason why we don't simply call Os::has_feature() here is that we might move the high-level engine classes out of godot-core
    // later, and godot-core would only depend on godot-sys. This makes future migrations easier. We still have access to builtins though.

    out!("Check Godot precision setting...");

    #[cfg(feature = "debug-log")] // Display safeguards level in debug log.
    let safeguards_level = if cfg!(safeguards_strict) {
        "strict"
    } else if cfg!(safeguards_balanced) {
        "balanced"
    } else {
        "disengaged"
    };
    out!("Safeguards: {safeguards_level}");

    let os_class = StringName::from("OS");
    let single = GString::from("single");
    let double = GString::from("double");

    let gdext_is_double = cfg!(feature = "double-precision");

    // SAFETY: main thread, after initialize(), valid string pointers, `Scene` initialized.
    let godot_is_double = unsafe {
        let is_single = sys::godot_has_feature(os_class.string_sys(), single.sys());
        let is_double = sys::godot_has_feature(os_class.string_sys(), double.sys());

        assert_ne!(
            is_single, is_double,
            "Godot has invalid configuration: single={is_single}, double={is_double}"
        );

        is_double
    };

    let s = |is_double: bool| -> &'static str { if is_double { "double" } else { "single" } };

    out!(
        "Is double precision: Godot={}, gdext={}",
        s(godot_is_double),
        s(gdext_is_double)
    );

    if godot_is_double != gdext_is_double {
        panic!(
            "Godot runs with {} precision, but gdext was compiled with {} precision.\n\
            Cargo feature `double-precision` must be used if and only if Godot is compiled with `precision=double`.\n",
            s(godot_is_double),
            s(gdext_is_double),
        );
    }
}