Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Ensure class servers methods are loaded after hot reload #636

Merged
merged 1 commit into from
Mar 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions godot-core/src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

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

use godot_ffi as sys;

use sys::GodotFfi;
Expand Down Expand Up @@ -53,17 +55,38 @@ pub unsafe fn __gdext_load_library<E: ExtensionLibrary>(
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,
) {
let level = InitLevel::from_sys(init_level);
let ctx = || format!("failed to initialize GDExtension level `{:?}`", level);

// Swallow panics. TODO consider crashing if gdext init fails.
let _ = crate::private::handle_panic(ctx, || {
fn try_load<E: ExtensionLibrary>(level: InitLevel) {
// 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(Relaxed) {
try_load::<E>(InitLevel::Core);
try_load::<E>(InitLevel::Servers);
}
} else if level == InitLevel::Core {
// When it's normal initialization, the `Servers` level is normally initialized.
LEVEL_SERVERS_CORE_LOADED.store(true, Relaxed);
}

gdext_on_level_init(level);
E::on_level_init(level);
}

// Swallow panics. TODO consider crashing if gdext init fails.
let _ = crate::private::handle_panic(ctx, || {
try_load::<E>(level);
});
}

Expand All @@ -76,6 +99,11 @@ unsafe extern "C" fn ffi_deinitialize_layer<E: ExtensionLibrary>(

// Swallow panics.
let _ = crate::private::handle_panic(ctx, || {
if level == InitLevel::Core {
// Once the CORE api is unloaded, reset the flag to initial state.
LEVEL_SERVERS_CORE_LOADED.store(false, Relaxed);
}

E::on_level_deinit(level);
gdext_on_level_deinit(level);
});
Expand Down
Loading