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

CPP reloading #621

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
93 changes: 8 additions & 85 deletions kt/godot-library/src/main/kotlin/godot/runtime/Bootstrap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,15 @@ import godot.core.variantMapper
import godot.registration.ClassRegistry
import godot.registration.Entry
import godot.util.err
import godot.util.info
import godot.util.warning
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import java.nio.file.FileSystems
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchService
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit


internal class Bootstrap {
private val classRegistries: MutableList<ClassRegistry> = mutableListOf()
private lateinit var classloader: ClassLoader
private lateinit var serviceLoader: ServiceLoader<Entry>
private var executor: ScheduledExecutorService? = null
private var watchService: WatchService? = null
private var engineTypesRegistered: Boolean = false

/** projectRootDir is empty if not in editor (only used for reloading)
* userCodePath is empty if usercode loaded as part of the VM
Expand All @@ -38,67 +26,18 @@ internal class Bootstrap {
doInitGraal()
} else {
val userCodeFile = File(userCodePath)

if (userCodeFile.exists()) {
doInit(userCodeFile.toURI().toURL(), loader)
} else {
if (projectRootDir.isNotEmpty()) {
::warning
} else {
::err
}.invoke("No main.jar detected at $userCodeFile. No classes will be loaded. Build the gradle project to load classes")
}

if (projectRootDir.isNotEmpty()) {
watchService = FileSystems.getDefault().newWatchService()
val watchKey = getBuildLockDir(projectRootDir).toPath().register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY,
)

executor = Executors.newSingleThreadScheduledExecutor { runnable ->
val thread = Thread(runnable)
thread.isDaemon = true
thread
}

executor!!.scheduleAtFixedRate({
val events = watchKey.pollEvents()
if (events.isNotEmpty()) {
if (File(getBuildLockDir(projectRootDir), "buildLock.lock").exists()) {
info("Build lock present. Not reloading...")
return@scheduleAtFixedRate
}
info("Changes detected, reloading classes ...")

if (::serviceLoader.isInitialized) {
clearClassesCache()
serviceLoader.reload()
}

if (userCodeFile.exists()) {
doInit(userCodeFile.toURI().toURL(), null) //no classloader so new main jar gets loaded
} else {
warning("No main.jar detected. No classes will be loaded. Build the project to load classes")
}
}
}, 3, 3, TimeUnit.SECONDS)
}
doInit(userCodeFile.toURI().toURL(), loader)
}
}

fun finish() {
executor?.shutdown()
watchService?.close()
Thread.currentThread().contextClassLoader = null
clearClassesCache()
serviceLoader.reload()
}

private fun doInit(mainJar: URL, classLoader: ClassLoader?) {
classloader = classLoader ?: URLClassLoader(arrayOf(mainJar), this::class.java.classLoader)
Thread.currentThread().contextClassLoader = classloader
serviceLoader = ServiceLoader.load(Entry::class.java, classloader)
initializeUsingEntry()
}
Expand All @@ -123,6 +62,7 @@ internal class Bootstrap {
// the entry with the most class registrars is always the "main" entry. All other entries are from dependencies
// reason: the "main" compilation generates the registration files from all class registrars (its own AND all from dependencies). Hence, it will always be the one with the highest registrar count
val mainEntry = entries.maxBy { entry -> entry.classRegistrarCount }
val classRegistries = mutableListOf<ClassRegistry>()

entries.forEach { entry ->
val isMainEntry = entry == mainEntry
Expand All @@ -131,23 +71,21 @@ internal class Bootstrap {
projectName = entry.projectName,
isDependency = !isMainEntry,
)
classRegistries.add(registry)

classRegistries.add(registry)
val context = Entry.Context(registry)

with(entry) {
if (!engineTypesRegistered && isMainEntry) {
if (isMainEntry) {
context.initEngineTypes()
for (clazz in context.getRegisteredClasses()) {
variantMapper[clazz] = VariantType.OBJECT
}
registerManagedEngineTypes(
TypeManager.engineTypeNames.toTypedArray(),
TypeManager.engineSingletonsNames.toTypedArray()
)
engineTypesRegistered = true
}

for (clazz in context.getRegisteredClasses()) {
variantMapper[clazz] = VariantType.OBJECT
}
context.init()
}
}
Expand All @@ -162,22 +100,7 @@ internal class Bootstrap {
// END: order matters!
}

private fun getBuildLockDir(projectDir: String): File {
val name = "${File(projectDir).name}_buildLockDir" //keep the same in the gradle plugin!
val tmpDir = System.getProperty("java.io.tmpdir")
val lockDir = File(tmpDir, name)

return if (lockDir.exists() && lockDir.isDirectory) {
lockDir
} else {
lockDir.delete()
lockDir.mkdirs()
lockDir
}
}

private fun clearClassesCache() {
classRegistries.clear()
TypeManager.clearUserTypes()
}

Expand Down
16 changes: 13 additions & 3 deletions register_types.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "register_types.h"
#include "resource_format/jvm_resource_format_loader.h"
#include "resource_format/jvm_resource_format_saver.h"
#include "resource_format/java_archive_resource_format_loader.h"
#include "script/jvm_script.h"
#include "script/language/gdj_script.h"
#include "script/language/java_script.h"
Expand All @@ -22,6 +23,8 @@
Ref<JvmResourceFormatLoader> resource_format_loader;
Ref<JvmResourceFormatSaver> resource_format_saver;

Ref<JavaArchiveFormatLoader> java_archive_format_loader;

#ifdef TOOLS_ENABLED
static void editor_init() {
Ref<KotlinEditorExportPlugin> export_plugin;
Expand All @@ -40,7 +43,7 @@
#endif

if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) {
GDKotlin::get_instance().init();
GDKotlin::get_instance().initialize_up_to(GDKotlin::State::CORE_LIBRARY_INITIALIZED);

GDREGISTER_ABSTRACT_CLASS(JvmScript);
GDREGISTER_CLASS(GdjScript);
Expand All @@ -55,6 +58,11 @@
ResourceLoader::add_resource_format_loader(resource_format_loader);
resource_format_saver.instantiate();
ResourceSaver::add_resource_format_saver(resource_format_saver);

java_archive_format_loader.instantiate();
ResourceLoader::add_resource_format_loader(java_archive_format_loader);

MessageQueue::get_singleton()->push_callable(callable_mp(GDKotlin::get_instance(), &GDKotlin::initialize_up_to));

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor release (target=editor)

'create_custom_callable_function_pointer': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor release (target=editor)

'CallQueue::push_callable': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor debug (target=editor, debug_symbols=true )

'create_custom_callable_function_pointer': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor debug (target=editor, debug_symbols=true )

'CallQueue::push_callable': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor dev (target=editor, dev_build=yes, debug_symbols=true )

'create_custom_callable_function_pointer': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build editor dev (target=editor, dev_build=yes, debug_symbols=true )

'CallQueue::push_callable': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build release template

'create_custom_callable_function_pointer': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build release template

'CallQueue::push_callable': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build debug template

'create_custom_callable_function_pointer': no matching overloaded function found

Check failure on line 65 in register_types.cpp

View workflow job for this annotation

GitHub Actions / 🪟 Build Windows / Build debug template

'CallQueue::push_callable': no matching overloaded function found
}

#ifdef TOOLS_ENABLED
Expand All @@ -70,7 +78,9 @@
if (Engine::get_singleton()->is_project_manager_hint()) { return; }
#endif

if (p_level != MODULE_INITIALIZATION_LEVEL_SERVERS) { return; }
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; }

ResourceLoader::remove_resource_format_loader((java_archive_format_loader));

ResourceLoader::remove_resource_format_loader((resource_format_loader));
ResourceSaver::remove_resource_format_saver(resource_format_saver);
Expand All @@ -89,5 +99,5 @@
ScriptServer::unregister_language(jvm_language);
memdelete(jvm_language);

GDKotlin::get_instance().finish();
GDKotlin::get_instance().finalize_down_to(GDKotlin::State::NOT_STARTED);
}
Loading
Loading