@preeternal/react-native-godot 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ /**************************************************************************/
2
+ /* LibGodotABI.h */
3
+ /**************************************************************************/
4
+ /* LibGodot C ABI used by the native bridge. */
5
+ /* Keep this bridge-local declaration in sync with the selected LibGodot headers. */
6
+ /**************************************************************************/
7
+
8
+ #pragma once
9
+
10
+ #include <gdextension_interface.h>
11
+ #include <godot_cpp/variant/string.hpp>
12
+ #include <godot_cpp/variant/string_name.hpp>
13
+
14
+ #include <stdbool.h>
15
+
16
+ // Generated builtin layouts depend on the target architecture. Mixing ARM32
17
+ // headers with an ARM64 library corrupts memory even when the C ABI matches.
18
+ static_assert(sizeof(godot::StringName) == sizeof(void *),
19
+ "LibGodot godot-cpp StringName headers do not match the target ABI. Use headers generated for this architecture.");
20
+ static_assert(sizeof(godot::String) == sizeof(void *),
21
+ "LibGodot godot-cpp String headers do not match the target ABI. Use headers generated for this architecture.");
22
+
23
+ #if defined(__ANDROID__) || defined(ANDROID)
24
+ #include <jni.h>
25
+ #endif
26
+
27
+ using RNLibGodotLogCallbackData = void *;
28
+ using RNLibGodotLogCallbackFunction = void (*)(RNLibGodotLogCallbackData p_data, const char *p_log_message, bool p_err);
29
+
30
+ using RNLibGodotCreateFunction = GDExtensionObjectPtr (*)(
31
+ int p_argc,
32
+ char *p_argv[],
33
+ GDExtensionInitializationFunction p_init_func,
34
+ RNLibGodotLogCallbackFunction p_log_func,
35
+ RNLibGodotLogCallbackData p_log_data);
36
+
37
+ using RNLibGodotDestroyFunction = void (*)(GDExtensionObjectPtr p_godot_instance);
38
+
39
+ #if defined(__ANDROID__) || defined(ANDROID)
40
+ using RNLibGodotCreateAndroidFunction = GDExtensionObjectPtr (*)(
41
+ int p_argc,
42
+ char *p_argv[],
43
+ GDExtensionInitializationFunction p_init_func,
44
+ RNLibGodotLogCallbackFunction p_log_func,
45
+ RNLibGodotLogCallbackData p_log_data,
46
+ JNIEnv *p_env,
47
+ jobject p_asset_manager,
48
+ jobject p_net_utils,
49
+ jobject p_directory_access_handler,
50
+ jobject p_file_access_handler,
51
+ jobject p_godot_io_wrapper);
52
+ #endif
@@ -719,7 +719,7 @@ jsi::Value createNativeGodotModule(jsi::Runtime &rt, const std::shared_ptr<faceb
719
719
  GodotModule *mod = GodotModule::get_singleton();
720
720
  godot::GodotInstance *instance = mod->get_or_create_instance(godotArgs);
721
721
  if (!instance) {
722
- return jsi::Value::undefined();
722
+ throw jsi::JSError(rt, "Failed to create Godot instance. See the native engine log for the startup error.");
723
723
  }
724
724
  return GodotHostObject::godotVariantToJsiValue(workletContext, rt, godot::Variant(instance));
725
725
  };
@@ -29,7 +29,6 @@
29
29
  #define LOG_TAG "GodotModule"
30
30
  #include "godot-log.h"
31
31
 
32
- #include <libgodot/libgodot.h>
33
32
  #include <godot_cpp/classes/display_server_embedded.hpp>
34
33
  #include <godot_cpp/classes/engine.hpp>
35
34
  #include <godot_cpp/classes/gd_extension_manager.hpp>
@@ -43,6 +42,11 @@
43
42
  #include <map>
44
43
  #include <mutex>
45
44
  #include <string>
45
+ #include <vector>
46
+
47
+ #include "../cpp/AppleRendererPolicy.h"
48
+ #include "../cpp/LibGodotABI.h"
49
+ #include <TargetConditionals.h>
46
50
 
47
51
  static constexpr NSInteger kGodotMaxFramesPerSecond = 60;
48
52
 
@@ -156,9 +160,6 @@ static void configureGodotDisplayLink(CADisplayLink *displayLink) {
156
160
 
157
161
  @end
158
162
 
159
- typedef GDExtensionObjectPtr (*libgodot_create_godot_instance_type)(int, char *[], GDExtensionInitializationFunction, InvokeCallbackFunction, ExecutorData, InvokeCallbackFunction, ExecutorData, LogCallbackFunction, LogCallbackData);
160
- typedef void (*libgodot_destroy_godot_instance_type)(GDExtensionObjectPtr p_godot_instance);
161
-
162
163
  struct ApplePlatformData : PlatformData {
163
164
  CALayer *mainWindowLayer;
164
165
  godot::Ref<godot::RenderingNativeSurface> mainSurface;
@@ -167,11 +168,14 @@ struct ApplePlatformData : PlatformData {
167
168
  bool in_background = true;
168
169
  bool paused = false;
169
170
  void *handle = nullptr;
170
- libgodot_create_godot_instance_type func_libgodot_create_godot_instance = nullptr;
171
- libgodot_destroy_godot_instance_type func_libgodot_destroy_godot_instance = nullptr;
172
-
173
- std::map<std::string, std::function<void(bool)>> windowUpdateCallbacks;
174
- std::map<void *, std::string> handleToWindowName;
171
+ RNLibGodotCreateFunction func_libgodot_create_godot_instance = nullptr;
172
+ RNLibGodotDestroyFunction func_libgodot_destroy_godot_instance = nullptr;
173
+
174
+ struct WindowCallback {
175
+ std::string name;
176
+ std::function<void(bool)> callback;
177
+ };
178
+ std::map<void *, WindowCallback> windowUpdateCallbacks;
175
179
  std::mutex windowUpdateMutex;
176
180
  std::mutex createMutex;
177
181
  GodotThread *thread = nil;
@@ -196,11 +200,26 @@ static void observeApplicationLifecycle(GodotModule *module) {
196
200
  static NSArray *observers;
197
201
  observers = @[
198
202
  [center addObserverForName:UIApplicationWillResignActiveNotification
199
- object:nil queue:[NSOperationQueue mainQueue]
200
- usingBlock:^(NSNotification *notification) { module->appPause(); }],
203
+ object:nil
204
+ queue:[NSOperationQueue mainQueue]
205
+ usingBlock:^(NSNotification *notification) {
206
+ module->appPause();
207
+ }],
201
208
  [center addObserverForName:UIApplicationDidBecomeActiveNotification
202
- object:nil queue:[NSOperationQueue mainQueue]
203
- usingBlock:^(NSNotification *notification) { module->appResume(); }]
209
+ object:nil
210
+ queue:[NSOperationQueue mainQueue]
211
+ usingBlock:^(NSNotification *notification) {
212
+ module->appResume();
213
+ }],
214
+ [center addObserverForName:UIApplicationWillTerminateNotification
215
+ object:nil
216
+ queue:nil
217
+ usingBlock:^(NSNotification *notification) {
218
+ if ([NSProcessInfo processInfo].iOSAppOnMac) {
219
+ // Finish engine cleanup before exit runs LibGodot's static destructors.
220
+ module->destroy_instance();
221
+ }
222
+ }]
204
223
  ];
205
224
  if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
206
225
  module->appResume();
@@ -230,7 +249,12 @@ static void uninitialize_default_module(godot::ModuleInitializationLevel p_level
230
249
  }
231
250
  }
232
251
 
233
- static void logCallBack(LogCallbackData p_data, const char *p_log_message, bool p_err) {
252
+ static void logCallBack(RNLibGodotLogCallbackData p_data, const char *p_log_message, bool p_err) {
253
+ if (p_err) {
254
+ LOGE("%s", p_log_message);
255
+ } else {
256
+ LOGI("%s", p_log_message);
257
+ }
234
258
  GodotModule *gm = (GodotModule *)p_data;
235
259
  gm->log(p_log_message, p_err);
236
260
  }
@@ -247,6 +271,15 @@ GDExtensionBool GDE_EXPORT gdextension_default_init(GDExtensionInterfaceGetProcA
247
271
  }
248
272
 
249
273
  godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::string> args) {
274
+ godot::GodotInstance *result = nullptr;
275
+ runOnGodotThread([this, &args, &result]() {
276
+ result = get_or_create_instance_on_godot_thread(std::move(args));
277
+ },
278
+ true);
279
+ return result;
280
+ }
281
+
282
+ godot::GodotInstance *GodotModule::get_or_create_instance_on_godot_thread(std::vector<std::string> args) {
250
283
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
251
284
 
252
285
  // Make sure that we only run this method once at a time.
@@ -259,28 +292,29 @@ godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::strin
259
292
  }
260
293
  }
261
294
 
295
+ const auto renderer = rn_godot::configure_apple_renderer(args, TARGET_OS_SIMULATOR);
296
+ if (!renderer.error.empty()) {
297
+ LOGE("Invalid iOS renderer request: %s", renderer.error.c_str());
298
+ return nullptr;
299
+ }
300
+ LOGI("iOS renderer target=%s requested=%s/%s selected=%s/%s",
301
+ TARGET_OS_SIMULATOR ? "simulator" : "device",
302
+ renderer.requested_driver.empty() ? "default" : renderer.requested_driver.c_str(),
303
+ renderer.requested_method.empty() ? "default" : renderer.requested_method.c_str(),
304
+ renderer.driver.c_str(), renderer.method.c_str());
262
305
  observeApplicationLifecycle(this);
263
306
 
264
- void *handle = nullptr;
265
- if (data->func_libgodot_create_godot_instance == nullptr) {
266
- handle = dlopen("libgodot.framework/libgodot", RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
267
-
268
- if (handle == nullptr) {
269
- NSLog(@"Unable to open libgodot.framework: %s", dlerror());
270
- return nullptr;
271
- }
272
- libgodot_create_godot_instance_type func_libgodot_create_godot_instance = (libgodot_create_godot_instance_type)dlsym(handle, "libgodot_create_godot_instance");
273
-
274
- if (func_libgodot_create_godot_instance == nullptr) {
275
- NSLog(@"Unable to load libgodot_create_godot_instance symbol: %s", dlerror());
276
- dlclose(handle);
277
- return nullptr;
278
- }
279
-
280
- {
281
- std::lock_guard lock(_mutex);
282
- data->func_libgodot_create_godot_instance = func_libgodot_create_godot_instance;
283
- }
307
+ void *handle = dlopen("libgodot.framework/libgodot", RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
308
+ if (!handle) {
309
+ NSLog(@"Unable to open libgodot.framework: %s", dlerror());
310
+ return nullptr;
311
+ }
312
+ auto create = reinterpret_cast<RNLibGodotCreateFunction>(dlsym(handle, "libgodot_create_godot_instance"));
313
+ auto destroy = reinterpret_cast<RNLibGodotDestroyFunction>(dlsym(handle, "libgodot_destroy_godot_instance"));
314
+ if (!create || !destroy) {
315
+ NSLog(@"LibGodot requires both create and destroy symbols");
316
+ dlclose(handle);
317
+ return nullptr;
284
318
  }
285
319
 
286
320
  godot::GodotInstance *instance = nullptr;
@@ -295,22 +329,35 @@ godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::strin
295
329
  cargs.push_back(arg.c_str());
296
330
  }
297
331
 
298
- GDExtensionObjectPtr instance_ptr = data->func_libgodot_create_godot_instance(cargs.size(), (char **)cargs.data(), gdextension_default_init, nullptr, nullptr, nullptr, nullptr, logCallBack, this); // TODO: Do we want to use the extra 4 params?
299
- if (instance_ptr == nullptr) {
300
- // Unable to start Godot
301
- NSLog(@"Unable to start Godot");
332
+ GDExtensionObjectPtr instance_ptr = create(
333
+ static_cast<int>(cargs.size()),
334
+ (char **)cargs.data(),
335
+ gdextension_default_init,
336
+ logCallBack,
337
+ this);
338
+ // Raw teardown must work even if godot-cpp cannot bind the returned object.
339
+ // Call only after releasing every local Godot Ref/Variant/Callable.
340
+ auto cleanupFailedCreate = [&]() {
341
+ if (instance_ptr) {
342
+ destroy(instance_ptr);
343
+ }
344
+ godot::GDExtensionBinding::deinit();
302
345
  if (handle) {
303
346
  dlclose(handle);
304
- handle = nullptr;
305
- {
306
- std::lock_guard lock(_mutex);
307
- data->func_libgodot_create_godot_instance = nullptr;
308
- }
309
347
  }
348
+ };
349
+ if (!instance_ptr) {
350
+ NSLog(@"Unable to create GodotInstance");
351
+ cleanupFailedCreate();
310
352
  return nullptr;
311
353
  }
312
354
 
313
355
  instance = reinterpret_cast<godot::GodotInstance *>(godot::internal::get_object_instance_binding(instance_ptr));
356
+ if (!instance) {
357
+ NSLog(@"Unable to bind GodotInstance returned by LibGodot");
358
+ cleanupFailedCreate();
359
+ return nullptr;
360
+ }
314
361
 
315
362
  CGRect screen = [[UIScreen mainScreen] bounds];
316
363
  CGFloat contentScaleFactor = [[UIScreen mainScreen] scale];
@@ -319,6 +366,11 @@ godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::strin
319
366
 
320
367
  // Godot automatically creates the correct type of layer based on the selected rendering driver
321
368
  godot::Ref<godot::RenderingNativeSurfaceApple> appleSurface = godot::RenderingNativeSurfaceApple::create(0);
369
+ if (appleSurface.is_null()) {
370
+ NSLog(@"Unable to create the main Apple rendering surface");
371
+ cleanupFailedCreate();
372
+ return nullptr;
373
+ }
322
374
  CALayer __block *mainWindowLayer = (__bridge CALayer *)(void *)appleSurface->get_layer();
323
375
  mainWindowLayer.bounds = CGRectMake(0, 0, screen.size.width, screen.size.height);
324
376
  mainWindowLayer.position = CGPointMake(0, 0);
@@ -330,7 +382,14 @@ godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::strin
330
382
 
331
383
  godot::DisplayServerEmbedded::set_native_surface(nativeSurface);
332
384
 
333
- instance->start();
385
+ if (!instance->start()) {
386
+ NSLog(@"Unable to start GodotInstance");
387
+ godot::DisplayServerEmbedded::set_native_surface(godot::Ref<godot::RenderingNativeSurface>());
388
+ nativeSurface.unref();
389
+ appleSurface.unref();
390
+ cleanupFailedCreate();
391
+ return nullptr;
392
+ }
334
393
  bool inBackground;
335
394
 
336
395
  {
@@ -340,12 +399,16 @@ godot::GodotInstance *GodotModule::get_or_create_instance(std::vector<std::strin
340
399
  data->mainSurface = nativeSurface;
341
400
  data->contentScaleFactor = contentScaleFactor;
342
401
  data->handle = handle;
402
+ data->func_libgodot_create_godot_instance = create;
403
+ data->func_libgodot_destroy_godot_instance = destroy;
343
404
 
344
405
  _instance = instance;
406
+ _instanceGeneration.store(++_lastInstanceGeneration);
345
407
  inBackground = data->in_background;
346
408
  }
347
409
 
348
410
  if (inBackground) {
411
+ instance->focus_out();
349
412
  instance->pause();
350
413
  }
351
414
  updateState();
@@ -366,6 +429,13 @@ double GodotModule::get_content_scale_factor() {
366
429
  }
367
430
 
368
431
  void GodotModule::destroy_instance() {
432
+ runOnGodotThread([this]() {
433
+ destroy_instance_on_godot_thread();
434
+ },
435
+ true);
436
+ }
437
+
438
+ void GodotModule::destroy_instance_on_godot_thread() {
369
439
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
370
440
 
371
441
  // Make sure that we only run this method once at a time.
@@ -377,31 +447,8 @@ void GodotModule::destroy_instance() {
377
447
  }
378
448
 
379
449
  if (!data->func_libgodot_destroy_godot_instance) {
380
- libgodot_destroy_godot_instance_type func_libgodot_destroy_godot_instance = nullptr;
381
- void *handle = nullptr;
382
-
383
- {
384
- std::lock_guard lock(_mutex);
385
- handle = data->handle;
386
- }
387
-
388
- if (handle == nullptr) {
389
- NSLog(@"Unable to open libgodot.framework: %s", dlerror());
390
- return;
391
- }
392
- func_libgodot_destroy_godot_instance = (libgodot_destroy_godot_instance_type)dlsym(handle, "libgodot_destroy_godot_instance");
393
-
394
- if (func_libgodot_destroy_godot_instance == nullptr) {
395
- NSLog(@"Unable to load libgodot_destroy_godot_instance symbol: %s", dlerror());
396
- dlclose(handle);
397
- handle = nullptr;
398
- return;
399
- }
400
-
401
- {
402
- std::lock_guard lock(_mutex);
403
- data->func_libgodot_destroy_godot_instance = func_libgodot_destroy_godot_instance;
404
- }
450
+ NSLog(@"Missing destroy function for the active Godot instance");
451
+ return;
405
452
  }
406
453
 
407
454
  {
@@ -411,6 +458,7 @@ void GodotModule::destroy_instance() {
411
458
  data->displayLink = nil;
412
459
 
413
460
  updateWindows(false);
461
+ _instanceGeneration.store(0);
414
462
 
415
463
  godot::DisplayServerEmbedded::set_native_surface(godot::Ref<godot::RenderingNativeSurface>(nullptr));
416
464
  data->mainWindowLayer = nil;
@@ -422,6 +470,9 @@ void GodotModule::destroy_instance() {
422
470
 
423
471
  dlclose(data->handle);
424
472
  data->handle = nullptr;
473
+ data->func_libgodot_create_godot_instance = nullptr;
474
+ data->func_libgodot_destroy_godot_instance = nullptr;
475
+ data->paused = false;
425
476
  }
426
477
  }
427
478
 
@@ -482,6 +533,7 @@ void GodotModule::appPause() {
482
533
  [data->thread scheduleBlock:^{
483
534
  godot::GodotInstance *instance = get_instance();
484
535
  if (instance) {
536
+ instance->focus_out();
485
537
  instance->pause();
486
538
  }
487
539
  [[UIApplication sharedApplication] endBackgroundTask:bgTask];
@@ -500,6 +552,7 @@ void GodotModule::appResume() {
500
552
  godot::GodotInstance *instance = get_instance();
501
553
  if (instance) {
502
554
  instance->resume();
555
+ instance->focus_in();
503
556
  }
504
557
  }];
505
558
  updateState();
@@ -535,10 +588,10 @@ void GodotModule::updateState() {
535
588
  }
536
589
  } else if (!threadData->displayLink) {
537
590
  threadData->displayLink = [CADisplayLink displayLinkWithTarget:threadData->thread
538
- selector:@selector(step:)];
591
+ selector:@selector(step:)];
539
592
  configureGodotDisplayLink(threadData->displayLink);
540
593
  [threadData->displayLink addToRunLoop:[NSRunLoop currentRunLoop]
541
- forMode:NSRunLoopCommonModes];
594
+ forMode:NSRunLoopCommonModes];
542
595
  }
543
596
  }];
544
597
  }
@@ -590,53 +643,42 @@ godot::Callable GodotModule::create_callable(std::function<void(const godot::Var
590
643
  void GodotModule::registerWindowUpdateCallback(std::string name, void *handle, std::function<void(bool)> f, void *ref) {
591
644
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
592
645
  std::lock_guard lock(data->windowUpdateMutex);
593
- NSLog(@"Registering Window: %llx, %s", (uint64_t)handle, name.c_str());
594
- if (data->handleToWindowName.contains(handle)) {
595
- std::string currentName = data->handleToWindowName[handle];
596
- if (currentName != name) {
597
- NSLog(@"ERROR: registerWindowUpdateCallback: Unable to register a different name for the same handle");
598
- return;
599
- }
600
- } else {
601
- data->handleToWindowName[handle] = name;
602
- }
603
- data->windowUpdateCallbacks[name] = f;
646
+ data->windowUpdateCallbacks[handle] = { std::move(name), std::move(f) };
604
647
  }
605
648
 
606
649
  void GodotModule::unregisterWindowUpdateCallback(void *handle) {
607
650
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
608
651
  std::lock_guard lock(data->windowUpdateMutex);
609
- if (data->handleToWindowName.contains(handle)) {
610
- std::string name = data->handleToWindowName[handle];
611
- NSLog(@"Unregistering Window: %llx, %s", (uint64_t)handle, name.c_str());
612
- data->windowUpdateCallbacks.erase(name);
613
- data->handleToWindowName.erase(handle);
614
- }
652
+ data->windowUpdateCallbacks.erase(handle);
615
653
  }
616
654
 
617
655
  void GodotModule::updateWindow(std::string name, bool adding) {
618
656
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
619
- std::function<void(bool)> cb;
657
+ std::vector<std::function<void(bool)>> callbacks;
620
658
  {
621
659
  std::lock_guard lock(data->windowUpdateMutex);
622
- if (!data->windowUpdateCallbacks.contains(name)) {
623
- return;
660
+ for (const auto &[handle, entry] : data->windowUpdateCallbacks) {
661
+ if (entry.name == name) {
662
+ callbacks.push_back(entry.callback);
663
+ }
624
664
  }
625
- cb = data->windowUpdateCallbacks[name];
626
665
  }
627
- cb(adding);
666
+ for (const auto &callback : callbacks) {
667
+ callback(adding);
668
+ }
628
669
  }
629
670
 
630
671
  void GodotModule::updateWindows(bool adding) {
631
672
  ApplePlatformData *data = static_cast<ApplePlatformData *>(_data);
632
- std::map<std::string, std::function<void(bool)>> callbacks;
673
+ std::vector<std::function<void(bool)>> callbacks;
633
674
  {
634
675
  std::lock_guard lock(data->windowUpdateMutex);
635
- callbacks = data->windowUpdateCallbacks;
676
+ for (const auto &[handle, entry] : data->windowUpdateCallbacks) {
677
+ callbacks.push_back(entry.callback);
678
+ }
636
679
  }
637
- for (const std::pair<std::string, std::function<void(bool)>> elem : callbacks) {
638
- NSLog(@"Updating Window: %s", elem.first.c_str());
639
- elem.second(adding);
680
+ for (const auto &callback : callbacks) {
681
+ callback(adding);
640
682
  }
641
683
  }
642
684
 
@@ -649,7 +691,8 @@ void GodotModule::runOnGodotThread(std::function<void()> f, bool wait) {
649
691
  waitUntilDone:wait];
650
692
  }
651
693
 
652
- void GodotModule::iterate() {
694
+ void GodotModule::iterate(std::optional<uint64_t> frameGeneration) {
695
+ (void)frameGeneration;
653
696
  godot::GodotInstance *instance = nullptr;
654
697
  {
655
698
  std::lock_guard lock(_mutex);