@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.
@@ -38,9 +38,6 @@ class LibGodot {
38
38
  static inline jobject dir_access_handler = nullptr;
39
39
  static inline jobject file_access_handler = nullptr;
40
40
  static inline jobject godot_io = nullptr;
41
- static inline jobject godot_engine = nullptr;
42
- static inline jobject class_loader = nullptr;
43
- static inline jobject host_activity = nullptr;
44
41
 
45
42
  public:
46
43
  static jobject get_asset_manager() {
@@ -60,18 +57,6 @@ public:
60
57
  return godot_io;
61
58
  }
62
59
 
63
- static jobject get_godot_engine() {
64
- return godot_engine;
65
- }
66
-
67
- static jobject get_host_activity() {
68
- return host_activity;
69
- }
70
-
71
- static jobject get_class_loader() {
72
- return class_loader;
73
- }
74
-
75
60
  static ANativeWindow *get_main_surface();
76
61
 
77
62
  static int get_main_width();
@@ -82,9 +67,10 @@ public:
82
67
 
83
68
  static void set_java_vm(JavaVM *vm);
84
69
 
85
- static void initialize(JNIEnv *env, jobject p_asset_manager, jobject p_net_utils, jobject p_dir_access_handler, jobject p_file_access_handler, jobject p_godot_io, jobject p_main_surface, jint p_width, jint p_height, jobject p_godot_engine, jobject p_host_activity, jobject p_class_loader);
70
+ static void initialize(JNIEnv *env, jobject p_asset_manager, jobject p_net_utils, jobject p_dir_access_handler, jobject p_file_access_handler, jobject p_godot_io, jobject p_main_surface, jint p_width, jint p_height);
86
71
 
87
72
  static void cleanup(JNIEnv *env);
73
+ static void clear_input_state();
88
74
 
89
75
  static void updateWindowNative(JNIEnv *env, jstring p_name, jobject p_surface, jint p_width, jint p_height);
90
76
 
@@ -0,0 +1,123 @@
1
+ package com.preeternal.reactnativegodot
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.content.pm.ActivityInfo
7
+ import android.graphics.Rect
8
+ import android.net.Uri
9
+ import android.os.Build
10
+ import android.os.Environment
11
+ import android.provider.Settings
12
+ import android.util.DisplayMetrics
13
+ import android.util.Log
14
+ import android.view.Surface
15
+ import java.io.File
16
+ import java.util.Locale
17
+
18
+ // JNI contract: GodotIOJavaWrapper looks these methods up by name and descriptor.
19
+ // This adapter supplies Android services without starting Godot's standalone host.
20
+ internal class RTNGodotIO(
21
+ private val context: Context,
22
+ private val activity: () -> Activity?,
23
+ ) {
24
+ fun openURI(uri: String): Int = try {
25
+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(uri)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
26
+ 0
27
+ } catch (exception: Exception) {
28
+ Log.e("RTNGodotIO", "Unable to open URI", exception)
29
+ 1
30
+ }
31
+
32
+ fun getCacheDir(): String = context.cacheDir.absolutePath
33
+ fun getTempDir(): String = File(context.cacheDir, "tmp").also { it.mkdirs() }.absolutePath
34
+ fun getDataDir(): String = context.filesDir.absolutePath
35
+ fun getLocale(): String = Locale.getDefault().toString()
36
+ fun getModel(): String = Build.MODEL
37
+ fun getScreenDPI(): Int = context.resources.displayMetrics.densityDpi
38
+ fun getScaledDensity(): Float = when {
39
+ getScreenDPI() >= DisplayMetrics.DENSITY_XXXHIGH -> 4f
40
+ getScreenDPI() >= DisplayMetrics.DENSITY_XXHIGH -> 3f
41
+ getScreenDPI() >= DisplayMetrics.DENSITY_XHIGH -> 2f
42
+ getScreenDPI() >= DisplayMetrics.DENSITY_HIGH -> 1.5f
43
+ getScreenDPI() >= DisplayMetrics.DENSITY_MEDIUM -> 1f
44
+ else -> 0.75f
45
+ }
46
+
47
+ @Suppress("DEPRECATION")
48
+ fun getScreenRefreshRate(fallback: Double): Double =
49
+ activity()?.windowManager?.defaultDisplay?.refreshRate?.toDouble() ?: fallback
50
+
51
+ fun getDisplaySafeArea(): IntArray {
52
+ val rect = Rect()
53
+ activity()?.window?.decorView?.getWindowVisibleDisplayFrame(rect)
54
+ return intArrayOf(rect.left, rect.top, rect.width(), rect.height())
55
+ }
56
+
57
+ fun getDisplayCutouts(): IntArray = activity()?.window?.decorView?.rootWindowInsets
58
+ ?.displayCutout?.boundingRects?.flatMap { listOf(it.left, it.top, it.width(), it.height()) }
59
+ ?.toIntArray() ?: intArrayOf()
60
+
61
+ fun getUniqueID(): String = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) ?: ""
62
+
63
+ // Text entry is owned by React Native until an embedded IME bridge is available.
64
+ @Suppress("UNUSED_PARAMETER")
65
+ fun showKeyboard(text: String, type: Int, maxLength: Int, cursorStart: Int, cursorEnd: Int) {
66
+ Log.w("RTNGodotIO", "Embedded Godot text input is unavailable; use React Native text input")
67
+ }
68
+ fun hideKeyboard() = Unit
69
+ fun hasHardwareKeyboard(): Boolean = false
70
+
71
+ fun setScreenOrientation(orientation: Int) {
72
+ val requested = when (orientation) {
73
+ 0 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
74
+ 1 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
75
+ 2 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
76
+ 3 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
77
+ 4 -> ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
78
+ 5 -> ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
79
+ 6 -> ActivityInfo.SCREEN_ORIENTATION_FULL_USER
80
+ else -> return
81
+ }
82
+ activity()?.let { host -> host.runOnUiThread { host.requestedOrientation = requested } }
83
+ }
84
+
85
+ fun getScreenOrientation(): Int = when (activity()?.requestedOrientation) {
86
+ ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE -> 0
87
+ ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> 1
88
+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE -> 2
89
+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT -> 3
90
+ ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE -> 4
91
+ ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT -> 5
92
+ ActivityInfo.SCREEN_ORIENTATION_SENSOR, ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR,
93
+ ActivityInfo.SCREEN_ORIENTATION_FULL_USER -> 6
94
+ else -> -1
95
+ }
96
+
97
+ @Suppress("DEPRECATION")
98
+ fun getDisplayRotation(): Int = when (activity()?.windowManager?.defaultDisplay?.rotation) {
99
+ Surface.ROTATION_90 -> 90
100
+ Surface.ROTATION_180 -> 180
101
+ Surface.ROTATION_270 -> 270
102
+ else -> 0
103
+ }
104
+
105
+ @Suppress("DEPRECATION")
106
+ fun getSystemDir(index: Int, sharedStorage: Boolean): String {
107
+ val directory = when (index) {
108
+ 1 -> Environment.DIRECTORY_DCIM
109
+ 2 -> Environment.DIRECTORY_DOCUMENTS
110
+ 3 -> Environment.DIRECTORY_DOWNLOADS
111
+ 4 -> Environment.DIRECTORY_MOVIES
112
+ 5 -> Environment.DIRECTORY_MUSIC
113
+ 6 -> Environment.DIRECTORY_PICTURES
114
+ 7 -> Environment.DIRECTORY_RINGTONES
115
+ else -> null
116
+ }
117
+ val path = if (sharedStorage) {
118
+ if (directory == null) Environment.getExternalStorageDirectory()
119
+ else Environment.getExternalStoragePublicDirectory(directory)
120
+ } else context.getExternalFilesDir(directory)
121
+ return path?.absolutePath ?: context.filesDir.absolutePath
122
+ }
123
+ }
@@ -3,21 +3,32 @@ package com.preeternal.reactnativegodot
3
3
  import android.annotation.SuppressLint
4
4
  import android.content.Context
5
5
  import android.util.Log
6
+ import android.view.GestureDetector
6
7
  import android.view.MotionEvent
7
8
  import android.view.SurfaceHolder
8
9
  import android.view.SurfaceView
9
10
  import android.view.ViewGroup
10
- import org.godotengine.godot.input.GodotInputHandler
11
11
 
12
12
  class RTNGodotView(context: Context) : SurfaceView(context), SurfaceHolder.Callback2 {
13
- private val inputHandler: GodotInputHandler? = RTNLibGodot.getInstance().inputHandler
14
13
  private var windowName = ""
14
+ private var doubleTap = false
15
+ private val gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
16
+ override fun onDown(event: MotionEvent): Boolean = true
17
+ override fun onDoubleTap(event: MotionEvent): Boolean {
18
+ doubleTap = true
19
+ return true
20
+ }
21
+ })
15
22
 
16
23
  init {
17
24
  layoutParams = ViewGroup.LayoutParams(
18
25
  ViewGroup.LayoutParams.MATCH_PARENT,
19
26
  ViewGroup.LayoutParams.MATCH_PARENT,
20
27
  )
28
+ // The embedded Godot buffer is a child SurfaceControl. Keep it above the
29
+ // opaque React Native activity surface; default SurfaceView ordering leaves
30
+ // the rendered frame underneath the app canvas.
31
+ setZOrderMediaOverlay(true)
21
32
  holder.addCallback(this)
22
33
  }
23
34
 
@@ -50,29 +61,29 @@ class RTNGodotView(context: Context) : SurfaceView(context), SurfaceHolder.Callb
50
61
 
51
62
  @SuppressLint("ClickableViewAccessibility")
52
63
  override fun onTouchEvent(event: MotionEvent): Boolean {
53
- super.onTouchEvent(event)
54
- return inputHandler?.onTouchEvent(event) ?: false
55
- }
56
-
57
- override fun onGenericMotionEvent(event: MotionEvent): Boolean =
58
- inputHandler?.onGenericMotionEvent(event) ?: false
59
-
60
- override fun onCapturedPointerEvent(event: MotionEvent): Boolean =
61
- inputHandler?.onGenericMotionEvent(event) ?: false
62
-
63
- override fun requestPointerCapture() {
64
- super.requestPointerCapture()
65
- inputHandler?.onPointerCaptureChange(true)
66
- }
67
-
68
- override fun releasePointerCapture() {
69
- super.releasePointerCapture()
70
- inputHandler?.onPointerCaptureChange(false)
71
- }
72
-
73
- override fun onPointerCaptureChange(hasCapture: Boolean) {
74
- super.onPointerCaptureChange(hasCapture)
75
- inputHandler?.onPointerCaptureChange(hasCapture)
64
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) doubleTap = false
65
+ gestureDetector.onTouchEvent(event)
66
+ val positions = FloatArray(event.pointerCount * 6)
67
+ for (index in 0 until event.pointerCount) {
68
+ val offset = index * 6
69
+ positions[offset] = event.getPointerId(index).toFloat()
70
+ positions[offset + 1] = event.getX(index)
71
+ positions[offset + 2] = event.getY(index)
72
+ positions[offset + 3] = event.getPressure(index)
73
+ val tilt = event.getAxisValue(MotionEvent.AXIS_TILT, index)
74
+ val orientation = event.getOrientation(index)
75
+ positions[offset + 4] = -kotlin.math.sin(orientation) * kotlin.math.sin(tilt)
76
+ positions[offset + 5] = kotlin.math.cos(orientation) * kotlin.math.sin(tilt)
77
+ }
78
+ RTNLibGodot.getInstance().dispatchTouchEvent(
79
+ windowName,
80
+ event.actionMasked,
81
+ event.getPointerId(event.actionIndex),
82
+ event.pointerCount,
83
+ positions,
84
+ doubleTap,
85
+ )
86
+ return true
76
87
  }
77
88
 
78
89
  companion object {
@@ -8,142 +8,12 @@ import android.util.Log
8
8
  import android.view.Surface
9
9
  import android.view.SurfaceControl
10
10
  import android.view.SurfaceHolder
11
- import android.view.SurfaceView
12
- import org.godotengine.godot.Godot
13
- import org.godotengine.godot.GodotHost
14
- import org.godotengine.godot.GodotIO
15
- import org.godotengine.godot.GodotLib
16
- import org.godotengine.godot.GodotRenderView
17
- import org.godotengine.godot.IGodotLib
18
- import org.godotengine.godot.input.GodotInputHandler
19
11
  import org.godotengine.godot.io.directory.DirectoryAccessHandler
20
12
  import org.godotengine.godot.io.file.FileAccessHandler
21
- import org.godotengine.godot.plugin.AndroidRuntimePlugin
22
13
  import org.godotengine.godot.plugin.GodotPlugin
23
- import org.godotengine.godot.tts.GodotTTS
24
14
  import org.godotengine.godot.utils.GodotNetUtils
25
15
 
26
- class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView {
27
- private var godot: Godot? = null
28
- private var inputHandler: GodotInputHandler? = null
29
- private val hostPlugins = HashSet<GodotPlugin>()
30
-
31
- override fun initialize(
32
- godot: Godot,
33
- assetManager: AssetManager,
34
- godotIO: GodotIO,
35
- godotNetUtils: GodotNetUtils,
36
- directoryAccessHandler: DirectoryAccessHandler,
37
- fileAccessHandler: FileAccessHandler,
38
- unused: Boolean,
39
- ): Boolean {
40
- val mainWindow = windowData[""]
41
- if (mainWindow?.surface == null) {
42
- Log.e(TAG, "Main window surface is unavailable; call init() before initialize()")
43
- return false
44
- }
45
-
46
- initialize(
47
- assetManager,
48
- godotNetUtils,
49
- directoryAccessHandler,
50
- fileAccessHandler,
51
- godotIO,
52
- mainWindow.surface,
53
- mainWindow.width,
54
- mainWindow.height,
55
- godot,
56
- hostActivity,
57
- RTNLibGodot::class.java.classLoader,
58
- )
59
- return true
60
- }
61
-
62
- override fun ondestroy() = Unit
63
-
64
- override fun setup(strings: Array<String>, godotTTS: GodotTTS): Boolean = true
65
-
66
- override fun resize(surface: Surface, width: Int, height: Int) {
67
- Log.i(TAG, "Resize")
68
- }
69
-
70
- override fun newcontext(surface: Surface) = Unit
71
- override fun back() = Unit
72
- override fun step(): Boolean = false
73
- override fun ttsCallback(a: Int, b: Int, c: Int) = Unit
74
-
75
- override fun dispatchTouchEvent(
76
- event: Int,
77
- pointer: Int,
78
- pointerCount: Int,
79
- positions: FloatArray,
80
- doubleTap: Boolean,
81
- ) {
82
- dispatchTouchEvent("", event, pointer, pointerCount, positions, doubleTap)
83
- }
84
-
85
- override fun dispatchMouseEvent(
86
- event: Int,
87
- buttonMask: Int,
88
- x: Float,
89
- y: Float,
90
- deltaX: Float,
91
- deltaY: Float,
92
- doubleClick: Boolean,
93
- sourceMouseRelative: Boolean,
94
- pressure: Float,
95
- tiltX: Float,
96
- tiltY: Float,
97
- ) = Unit
98
-
99
- override fun magnify(a: Float, b: Float, c: Float) = Unit
100
- override fun pan(a: Float, b: Float, c: Float, d: Float) = Unit
101
- override fun accelerometer(a: Float, b: Float, c: Float) = Unit
102
- override fun gravity(a: Float, b: Float, c: Float) = Unit
103
- override fun magnetometer(a: Float, b: Float, c: Float) = Unit
104
- override fun gyroscope(a: Float, b: Float, c: Float) = Unit
105
- override fun key(a: Int, b: Int, c: Int, d: Boolean, e: Boolean) = Unit
106
- override fun joybutton(a: Int, b: Int, c: Boolean) = Unit
107
- override fun joyaxis(a: Int, b: Int, c: Float) = Unit
108
- override fun joyhat(a: Int, b: Int, c: Int) = Unit
109
- override fun joyconnectionchanged(a: Int, b: Boolean, c: String) = Unit
110
- override fun focusin() = Unit
111
- override fun focusout() = Unit
112
-
113
- override external fun getGlobal(path: String): String
114
- override external fun getRendererInfo(): Array<String>
115
-
116
- override fun getEditorSetting(path: String): String = ""
117
- override fun setEditorSetting(path: String, value: Any?) = Unit
118
- override fun getEditorProjectMetadata(path: String, key: String, defaultValue: Any?): Any? = null
119
- override fun setEditorProjectMetadata(path: String, key: String, value: Any?) = Unit
120
- override fun requestPermissionResult(permission: String, granted: Boolean) = Unit
121
- override fun onNightModeChanged() = Unit
122
- override fun hardwareKeyboardConnected(connected: Boolean) = Unit
123
- override fun filePickerCallback(success: Boolean, files: Array<String>) = Unit
124
- override fun setVirtualKeyboardHeight(height: Int) = Unit
125
- override fun onRendererResumed() = Unit
126
- override fun onRendererPaused() = Unit
127
- override fun shouldDispatchInputToRenderThread(): Boolean = false
128
- override fun getProjectResourceDir(): String = ""
129
- override fun isEditorHint(): Boolean = false
130
- override fun isProjectManagerHint(): Boolean = false
131
- override fun providesRenderView(): Boolean = true
132
- override fun getRenderView(): GodotRenderView = this
133
- override fun getActivity(): Activity? = hostActivity
134
- override fun getGodot(): Godot? = godot
135
- override fun getView(): SurfaceView? = null
136
- override fun startRenderer() = Unit
137
- override fun queueOnRenderThread(runnable: Runnable) = Unit
138
- override fun onActivityPaused() = Unit
139
- override fun onActivityStopped() = Unit
140
- override fun onActivityResumed() = Unit
141
- override fun onActivityStarted() = Unit
142
- override fun onActivityDestroyed() = Unit
143
- override fun getInputHandler(): GodotInputHandler? = inputHandler
144
- override fun configurePointerIcon(a: Int, b: String, c: Float, d: Float) = Unit
145
- override fun setPointerIcon(pointer: Int) = Unit
146
-
16
+ class RTNLibGodot private constructor() {
147
17
  private class WindowSurfaceData(
148
18
  val control: SurfaceControl,
149
19
  width: Int,
@@ -224,8 +94,8 @@ class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView
224
94
 
225
95
  @Synchronized
226
96
  fun init(newActivity: Activity?) {
97
+ hostActivity = newActivity ?: hostActivity
227
98
  if (inited) return
228
- hostActivity = newActivity
229
99
  val currentActivity = hostActivity
230
100
  if (currentActivity == null) {
231
101
  Log.e(TAG, "Activity not set, abort init")
@@ -237,20 +107,19 @@ class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView
237
107
  currentActivity.windowManager.defaultDisplay.getMetrics(metrics)
238
108
  getOrCreateWindowSurface("", metrics.widthPixels, metrics.heightPixels)
239
109
 
240
- GodotLib.setGodotLibImpl(this)
241
- godot = Godot.getInstance(currentActivity).also { it.setActivity(currentActivity) }
242
- val currentGodot = godot ?: return
243
- val runtimePlugins = HashSet<GodotPlugin>().apply {
244
- add(AndroidRuntimePlugin(currentGodot))
245
- addAll(hostPlugins)
246
- }
247
-
248
- if (!currentGodot.initEngine(this, ArrayList(), runtimePlugins)) {
249
- Log.e(TAG, "Unable to initialize Godot engine layer")
250
- return
251
- }
252
-
253
- inputHandler = GodotInputHandler(currentActivity, currentGodot)
110
+ // Embedded creation owns the engine. Do not call Godot.initEngine(), which
111
+ // initializes a second engine through the standalone Android JNI API.
112
+ val context = currentActivity.applicationContext
113
+ initialize(
114
+ context.assets,
115
+ GodotNetUtils(context),
116
+ DirectoryAccessHandler(context),
117
+ FileAccessHandler(context),
118
+ RTNGodotIO(context) { hostActivity },
119
+ checkNotNull(windowData[""]).surface,
120
+ metrics.widthPixels,
121
+ metrics.heightPixels,
122
+ )
254
123
  inited = true
255
124
  }
256
125
 
@@ -261,12 +130,11 @@ class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView
261
130
  }
262
131
  }
263
132
 
133
+ @Deprecated("Standalone Godot Android plugins are not supported by the embedded engine")
264
134
  fun addHostPlugin(plugin: GodotPlugin) {
265
- hostPlugins.add(plugin)
135
+ throw UnsupportedOperationException("Cannot register standalone Android plugin: ${plugin.javaClass.name}")
266
136
  }
267
137
 
268
- fun getHostPlugins(): Set<GodotPlugin> = hostPlugins
269
-
270
138
  private external fun updateWindowNative(name: String, surface: Surface, width: Int, height: Int)
271
139
  private external fun removeWindowNative(name: String)
272
140
 
@@ -299,7 +167,7 @@ class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView
299
167
  companion object {
300
168
  private const val TAG = "LibGodot"
301
169
  private var inited = false
302
- private var hostActivity: Activity? = null
170
+ @Volatile private var hostActivity: Activity? = null
303
171
 
304
172
  private val INSTANCE = RTNLibGodot()
305
173
  private val windowData = HashMap<String, WindowSurfaceData>()
@@ -328,13 +196,10 @@ class RTNLibGodot private constructor() : IGodotLib, GodotHost, GodotRenderView
328
196
  netUtils: GodotNetUtils,
329
197
  directoryAccessHandler: DirectoryAccessHandler,
330
198
  fileAccessHandler: FileAccessHandler,
331
- io: GodotIO,
199
+ io: RTNGodotIO,
332
200
  mainSurface: Surface,
333
201
  width: Int,
334
202
  height: Int,
335
- godot: Godot,
336
- hostActivity: Activity?,
337
- appClassLoader: ClassLoader?,
338
203
  )
339
204
 
340
205
  @JvmStatic
package/app.plugin.js CHANGED
@@ -25,7 +25,7 @@ const {
25
25
  withGradleProperties,
26
26
  withXcodeProject,
27
27
  } = loadExpoConfigPlugins();
28
- const { prebuiltFiles } = require('./package.json');
28
+ const { resolvePrebuiltConfig } = require('./scripts/prebuilt-config');
29
29
 
30
30
  const ANDROID_PROPERTIES = {
31
31
  'android.minSdkVersion': '29',
@@ -36,13 +36,6 @@ const GODOT_ASSET_PATTERN =
36
36
  '!.svn:!.git:!.ds_store:!*.scc:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~';
37
37
  const GODOT_ASSETS_START = '// @generated begin react-native-godot-assets';
38
38
  const GODOT_ASSETS_END = '// @generated end react-native-godot-assets';
39
- const libGodotAndroid = prebuiltFiles.find(
40
- (entry) => entry.name === 'libgodot-android'
41
- );
42
-
43
- if (!libGodotAndroid) {
44
- throw new Error('Missing libgodot-android prebuilt metadata in package.json');
45
- }
46
39
 
47
40
  function setGradleProperty(properties, key, value) {
48
41
  const property = properties.find(
@@ -67,6 +60,9 @@ function isGodotMavenRepository(repository) {
67
60
  }
68
61
 
69
62
  function addGodotMavenRepository(properties, platformProjectRoot) {
63
+ const libGodotAndroid = resolvePrebuiltConfig(
64
+ platformProjectRoot
65
+ ).prebuiltFiles.find((entry) => entry.name === 'libgodot-android');
70
66
  const property = properties.find(
71
67
  (entry) => entry.type === 'property' && entry.key === GODOT_MAVEN_PROPERTY
72
68
  );
@@ -0,0 +1,95 @@
1
+ #pragma once
2
+
3
+ #include <string>
4
+ #include <string_view>
5
+ #include <utility>
6
+ #include <vector>
7
+
8
+ namespace rn_godot {
9
+
10
+ struct AppleRendererSelection {
11
+ std::string_view driver;
12
+ std::string_view method;
13
+ std::string_view error;
14
+ };
15
+
16
+ // Choose before engine creation; an unsupported explicit request never retries.
17
+ constexpr AppleRendererSelection select_apple_renderer(bool simulator,
18
+ std::string_view driver = {}, std::string_view method = {}) {
19
+ if (driver.empty()) {
20
+ driver = method == "gl_compatibility" ? "opengl3" : (simulator ? "opengl3" : "metal");
21
+ }
22
+ const bool opengl = driver.starts_with("opengl3");
23
+ if (method.empty()) {
24
+ method = opengl ? "gl_compatibility" : "mobile";
25
+ }
26
+ if (simulator && driver == "metal") {
27
+ return {driver, method, "Metal is unavailable in this iOS Simulator slice. Use opengl3/gl_compatibility, or an iPhone/iPad device for Metal."};
28
+ }
29
+ if (opengl && method != "gl_compatibility") {
30
+ return {driver, method, "OpenGL rendering requires gl_compatibility."};
31
+ }
32
+ if (driver == "metal" && method == "gl_compatibility") {
33
+ return {driver, method, "Metal rendering requires mobile or forward_plus."};
34
+ }
35
+ return {driver, method, {}};
36
+ }
37
+
38
+ struct AppleRendererArguments {
39
+ std::string requested_driver;
40
+ std::string requested_method;
41
+ std::string driver;
42
+ std::string method;
43
+ std::string error;
44
+ };
45
+
46
+ inline AppleRendererArguments configure_apple_renderer(std::vector<std::string> &args, bool simulator) {
47
+ AppleRendererArguments result;
48
+ std::vector<std::string> normalized;
49
+ bool has_driver = false;
50
+ bool has_method = false;
51
+ for (size_t i = 0; i < args.size(); ++i) {
52
+ bool is_driver = args[i] == "--rendering-driver" || args[i].starts_with("--rendering-driver=");
53
+ bool is_method = args[i] == "--rendering-method" || args[i].starts_with("--rendering-method=");
54
+ if (!is_driver && !is_method) {
55
+ normalized.push_back(args[i]);
56
+ continue;
57
+ }
58
+ const std::string option = is_driver ? "--rendering-driver" : "--rendering-method";
59
+ std::string value;
60
+ if (args[i] == option) {
61
+ if (i + 1 == args.size() || args[i + 1].starts_with("--")) {
62
+ result.error = option + " requires a value.";
63
+ return result;
64
+ }
65
+ value = args[++i];
66
+ } else {
67
+ value = args[i].substr(option.size() + 1);
68
+ }
69
+ if (value.empty()) {
70
+ result.error = option + " requires a value.";
71
+ return result;
72
+ }
73
+ if (is_driver) {
74
+ has_driver = true;
75
+ result.requested_driver = value;
76
+ } else {
77
+ has_method = true;
78
+ result.requested_method = value;
79
+ }
80
+ normalized.insert(normalized.end(), {option, value});
81
+ }
82
+ const auto selection = select_apple_renderer(simulator, result.requested_driver, result.requested_method);
83
+ result.driver = selection.driver;
84
+ result.method = selection.method;
85
+ result.error = selection.error;
86
+ if (!result.error.empty()) {
87
+ return result;
88
+ }
89
+ if (!has_driver) normalized.insert(normalized.end(), {"--rendering-driver", result.driver});
90
+ if (!has_method) normalized.insert(normalized.end(), {"--rendering-method", result.method});
91
+ args = std::move(normalized);
92
+ return result;
93
+ }
94
+
95
+ } // namespace rn_godot
package/cpp/GodotModule.h CHANGED
@@ -28,8 +28,12 @@
28
28
  #include <godot_cpp/classes/godot_instance.hpp>
29
29
  #include <godot_cpp/classes/rendering_native_surface.hpp>
30
30
 
31
+ #include <atomic>
32
+ #include <cstdint>
31
33
  #include <future>
32
34
  #include <mutex>
35
+ #include <optional>
36
+ #include <utility>
33
37
 
34
38
  struct PlatformData {};
35
39
 
@@ -38,17 +42,23 @@ class GodotModule {
38
42
  PlatformData *_data = nullptr;
39
43
 
40
44
  std::mutex _mutex;
45
+ std::atomic<uint64_t> _instanceGeneration{ 0 };
46
+ uint64_t _lastInstanceGeneration = 0; // Godot thread only.
41
47
 
42
48
  std::function<void(const char *, bool)> logFunction;
43
49
 
44
50
  GodotModule(PlatformData *data) :
45
51
  _data(data) {}
46
52
 
53
+ godot::GodotInstance *get_or_create_instance_on_godot_thread(std::vector<std::string> args);
54
+ void destroy_instance_on_godot_thread();
55
+
47
56
  public:
48
57
  static GodotModule *get_singleton();
49
58
 
50
59
  godot::GodotInstance *get_or_create_instance(std::vector<std::string> args);
51
60
 
61
+ // Only use the returned binding on the Godot thread, where Stop is serialized.
52
62
  godot::GodotInstance *get_instance() {
53
63
  std::unique_lock lock(_mutex);
54
64
  return _instance;
@@ -89,7 +99,20 @@ public:
89
99
 
90
100
  void runOnGodotThread(std::function<void()> f, bool wait = false);
91
101
 
92
- void iterate();
102
+ uint64_t get_instance_generation() const {
103
+ return _instanceGeneration.load();
104
+ }
105
+
106
+ void runWithInstance(uint64_t generation, std::function<void()> f) {
107
+ runOnGodotThread([this, generation, f = std::move(f)]() {
108
+ if (generation != 0 && generation == get_instance_generation() &&
109
+ _instance && _instance->is_started()) {
110
+ f();
111
+ }
112
+ });
113
+ }
114
+
115
+ void iterate(std::optional<uint64_t> frameGeneration = std::nullopt);
93
116
 
94
117
  void set_log_callback(std::function<void(const char *, bool)> lf) {
95
118
  logFunction = lf;