Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): PhysX runs on Windows, Linux and Android hosts, beside Jolt

yhh6eeef6b4035e
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index fd4fe8e63..80044da20 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -81,6 +81,11 @@ export const MODULE_BINDING_HEADERS = [
export const NATIVE_BINDING_HEADERS = [...ENGINE_BINDING_HEADERS, ...MODULE_BINDING_HEADERS];
+// The PhysX backend's copy of the 3D physics surface: `physics3d_*` as `physx3d_*`,
+// behind the define the host build sets when it links PhysX (native/CMakeLists.txt).
+// The SDK maps the module id onto the same prefix (ecs/bridge/nativeSideModules.ts).
+export const PHYSX_ALIAS = 'physics3d_=physx3d_:ES_ENABLE_PHYSX';
+
// Generate the QuickJS wrappers for the engine's binding ENTRY POINTS — the same
// declarations embind registers on the web, so the SDK reaches the engine by the
// same names on both platforms and nothing is bound twice by hand. The bodies are
@@ -97,6 +102,11 @@ async function generateNativeFunctionBindings(rootDir, genDir, python) {
'--native-functions', ...NATIVE_BINDING_HEADERS.map(abs),
'--native-functions-output', out,
'--native-shim', 'esn_shim.hpp',
+ // PhysX answers the same 3D physics surface as Jolt and links beside it, so
+ // its copy of the surface is renamed (the header below is force-included
+ // into its TUs) and wrapped a second time from the same declarations.
+ '--native-functions-alias', PHYSX_ALIAS,
+ '--native-functions-alias-header', path.join(genDir, 'PhysX3DRename.generated.hpp'),
], { cwd: rootDir });
// The TS engine surface: the CORE headers only. It is committed (the SDK compiles
// without running EHT), so it is refreshed here rather than updated by hand —
diff --git a/cmake/PhysX.cmake b/cmake/PhysX.cmake
new file mode 100644
index 000000000..17edb7ce8
--- /dev/null
+++ b/cmake/PhysX.cmake
@@ -0,0 +1,50 @@
+# SPDX-License-Identifier: Apache-2.0
+# The vendored PhysX 5 CPU SDK as one static library, `physx`.
+#
+# One definition for every build that links it: the web side module
+# (third_party/CMakeLists.txt) and the native hosts (native/CMakeLists.txt). The
+# vendored tree carries no CMake of its own we could reuse — NVIDIA's generator
+# is a Python front-end over per-platform presets — so the sources are globbed,
+# minus the parts no Estella build consumes.
+#
+# The caller adds what is platform-specific on top (the web's SIMD flags).
+
+function(es_add_physx_library PX_ROOT)
+ if(TARGET physx)
+ return()
+ endif()
+ file(GLOB_RECURSE PHYSX_SOURCES "${PX_ROOT}/source/*.cpp")
+ # Remote debugging (PVD) is off in a release build, and the vehicle SDK has
+ # no consumer here yet.
+ list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/source/(pvd|physxvehicle|immediatemode)/")
+ if(WIN32)
+ list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/unix/")
+ else()
+ list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/windows/")
+ endif()
+ add_library(physx STATIC ${PHYSX_SOURCES})
+ file(GLOB_RECURSE _PX_HEADERS LIST_DIRECTORIES false "${PX_ROOT}/source/*.h")
+ set(_PX_PRIVATE_DIRS "")
+ # Every directory holding a header, and the ones above it: files include
+ # both "Foo.h" and "omnipvd/Foo.h".
+ foreach(_h ${_PX_HEADERS})
+ get_filename_component(_d "${_h}" DIRECTORY)
+ while(NOT _d STREQUAL "${PX_ROOT}/source" AND NOT _d STREQUAL "${PX_ROOT}")
+ list(APPEND _PX_PRIVATE_DIRS "${_d}")
+ get_filename_component(_d "${_d}" DIRECTORY)
+ endwhile()
+ endforeach()
+ list(REMOVE_DUPLICATES _PX_PRIVATE_DIRS)
+ target_include_directories(physx PUBLIC ${PX_ROOT}/include PRIVATE ${_PX_PRIVATE_DIRS})
+ target_compile_features(physx PUBLIC cxx_std_17)
+ target_compile_definitions(physx PUBLIC
+ PX_PHYSX_STATIC_LIB NDEBUG PX_SUPPORT_PVD=0 PX_SUPPORT_OMNI_PVD=0
+ DISABLE_CUDA_PHYSX PX_PUBLIC_RELEASE=1)
+ if(MSVC)
+ # The SDK is warning-clean on NVIDIA's own flags, not ours; it is vendored
+ # and not ours to fix.
+ target_compile_options(physx PRIVATE /w)
+ else()
+ target_compile_options(physx PRIVATE -w -fno-strict-aliasing)
+ endif()
+endfunction()
diff --git a/desktop b/desktop
index 3167d2202..51b098ef1 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 3167d2202136666577ae33b76ec5d5553c950705
+Subproject commit 51b098ef1d904ba7be21edec07603d76756521cd
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index b68cd95dc..b6962bd96 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -57,11 +57,17 @@ threshold, a 0.005 sleep threshold, 6 position and 1 velocity iterations, and a
- A character climbs onto a dynamic body no taller than its step height. A taller
one is pushed, with no more force than its push strength.
-What it costs: the PhysX web module is 3.6 MB (1.15 MB gzipped), against Jolt's
+What it costs: the PhysX web module is 3.5 MB (1.14 MB gzipped), against Jolt's
1.3 MB, and it loads only in a project that chose it. A chaotic scene (a ball
glancing off the edge of a hinged door) ends differently on the two solvers, as
-it would between any two engines. Native builds (desktop, Android) compile Jolt
-in and run it either way for now; they log that once at startup.
+it would between any two engines.
+
+Native builds for Windows, Linux and Android compile both solvers into
+the app and run the one the project chose, so a native game and its web build use
+the same solver. Carrying PhysX makes every native app larger whichever solver it
+uses: 4 MB on the Windows executable, and 2 MB of an Android download (4.7 MB
+installed, per ABI). macOS and iOS builds include only Jolt for now. A PhysX
+project there runs on Jolt and logs that once at startup.
## Bodies
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
index 2eb13093d..61b634133 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
@@ -47,9 +47,12 @@ PhysX 按 Unity 的默认值设置:投影高斯-赛德尔求解、patch 摩擦
- 角色保留半径十分之一的皮肤厚度(Unity 推荐的 skin width),所以比 Jolt 角色站得略高。
- 角色会走上不高于台阶高度的动态刚体;更高的会被推开,推力不超过它的推力强度。
-代价:PhysX 的 Web 模块 3.6 MB(gzip 1.15 MB),Jolt 是 1.3 MB;只有选了它的项目才加载。
+代价:PhysX 的 Web 模块 3.5 MB(gzip 1.14 MB),Jolt 是 1.3 MB;只有选了它的项目才加载。
混沌的场景(比如球擦过铰链门的边缘)在两个求解器上的结果会不同,任何两个引擎之间都会这样。
-原生包(桌面、Android)目前编进的是 Jolt,两种设置都运行 Jolt,启动时会记一条日志说明。
+Windows、Linux 和 Android 的原生包把两个求解器都编进应用,运行项目选的那个,
+所以原生游戏和它的 Web 版用的是同一个求解器。带上 PhysX 会让每个原生应用都变大,不管它用哪个求解器:
+Windows 可执行文件大约多 4 MB,Android 下载包大约多 2 MB(每个 ABI 安装后多 4.7 MB)。
+macOS 和 iOS 包目前只编进了 Jolt,选了 PhysX 的项目在这两个平台上运行 Jolt,启动时会记一条日志说明。
## 刚体
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 2a480a3bd..cc37e4347 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -295,6 +295,50 @@ if(ESTELLA_QUICKJS_DIR)
message(FATAL_ERROR "Missing ${NATIVE_FN_BINDINGS} — generate it via `cli native --quickjs`.")
endif()
+ # PhysX, the second 3D solver a project can pick (Project Settings → Physics →
+ # 3D solver), linked BESIDE Jolt rather than instead of it: which one runs is
+ # the project's choice at boot, and a host binary is shared by every game.
+ # Both implement the one physics3d_* surface, so PhysX's TUs are compiled with
+ # a generated rename header (physics3d_init → physx3d_init, every name the
+ # header declares) and the wrappers bind that copy as es_physx3d_*, from the
+ # same declarations — the SDK maps the module id onto that prefix
+ # (sdk/src/ecs/bridge/nativeSideModules.ts). Off on Apple platforms: PhysX 5
+ # dropped macOS/iOS from its supported set and it has not been built on a Mac
+ # here, so a PhysX project there runs on Jolt and is told so.
+ if(APPLE)
+ set(_physx_default OFF)
+ else()
+ set(_physx_default ON)
+ endif()
+ option(ESTELLA_PHYSX "Link PhysX beside Jolt as the per-project 3D solver" ${_physx_default})
+ if(ESTELLA_PHYSX)
+ set(PHYSX_RENAME "${ESTELLA_NATIVE_GEN_DIR}/PhysX3DRename.generated.hpp")
+ if(NOT EXISTS "${PHYSX_RENAME}")
+ message(FATAL_ERROR "Missing ${PHYSX_RENAME} — generate it via `cli native`, "
+ "or configure with -DESTELLA_PHYSX=OFF.")
+ endif()
+ include("${REPO}/cmake/PhysX.cmake")
+ es_add_physx_library("${TP}/physx")
+ if(NOT MSVC)
+ # As on the web: PhysX uses neither, and dropping them is 0.5 MB of the
+ # Android library. Kept at the host's -O3 (as Jolt is): -Os saves another
+ # 0.45 MB compressed and costs the solver its speed on the device.
+ target_compile_options(physx PUBLIC -fno-exceptions -fno-rtti)
+ endif()
+ set(_PXM "${SRC}/esengine/bindings/modules/physics3d_physx")
+ add_library(estella_physics3d_physx STATIC
+ "${_PXM}/PhysXModuleEntry.cpp" "${_PXM}/PhysXQueries.cpp" "${_PXM}/PhysXJoints.cpp")
+ target_include_directories(estella_physics3d_physx PUBLIC "${SRC}")
+ target_link_libraries(estella_physics3d_physx PUBLIC physx)
+ if(MSVC)
+ target_compile_options(estella_physics3d_physx PRIVATE "/FI${PHYSX_RENAME}")
+ else()
+ target_compile_options(estella_physics3d_physx PRIVATE -include "${PHYSX_RENAME}")
+ endif()
+ # INTERFACE: what turns the es_physx3d_* wrappers on is linking this.
+ target_compile_definitions(estella_physics3d_physx INTERFACE ES_ENABLE_PHYSX)
+ endif()
+
# QuickJS-ng interpreter — core is just these four C files.
add_library(qjs STATIC
"${ESTELLA_QUICKJS_DIR}/quickjs.c" "${ESTELLA_QUICKJS_DIR}/libregexp.c"
@@ -468,6 +512,9 @@ if(ESTELLA_QUICKJS_DIR)
target_compile_definitions(estella_js_host PRIVATE ESTELLA_DESKTOP)
target_link_libraries(estella_js_host esengine estella_physics estella_physics3d
estella_video estella_spine estella_dragonbones esjs_engine SDL3::SDL3)
+ if(TARGET estella_physics3d_physx)
+ target_link_libraries(estella_js_host estella_physics3d_physx)
+ endif()
if(ESTELLA_V8_RUNTIME)
# V8 is a set of DLLs plus its Intl data; the exe finds them beside it.
add_custom_command(TARGET estella_js_host POST_BUILD
@@ -518,6 +565,9 @@ if(ESTELLA_QUICKJS_DIR)
target_link_libraries(estella_js_host esengine estella_physics estella_physics3d
estella_video estella_spine
estella_dragonbones esjs_engine native_app_glue android log)
+ if(TARGET estella_physics3d_physx)
+ target_link_libraries(estella_js_host estella_physics3d_physx)
+ endif()
set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")
if(ESJS_ENGINE STREQUAL "v8")
# The host links libv8android.so by name; the template takes it from
diff --git a/sdk/src/ecs/bridge/nativeSideModules.ts b/sdk/src/ecs/bridge/nativeSideModules.ts
index 79bba9378..ac9691cb1 100644
--- a/sdk/src/ecs/bridge/nativeSideModules.ts
+++ b/sdk/src/ecs/bridge/nativeSideModules.ts
@@ -49,10 +49,9 @@ const SPINE_PROBES = SPINE_VERSIONS.reduce<Partial<Record<SideModuleId, string>>
export const NATIVE_SIDE_MODULE_PROBES: Partial<Record<SideModuleId, string>> = {
physics: 'es_physics_init',
physics3d: 'es_physics3d_init',
- // A native host compiles Jolt in and not PhysX yet. Both answer the same
- // physics3d_* surface, so a PhysX project still gets its 3D world, on Jolt,
- // and is told so once rather than losing physics.
- 'physics3d:physx': 'es_physics3d_init',
+ // PhysX links beside Jolt, its copy of the same surface renamed (see
+ // NATIVE_PREFIX_ALIASES): the probe is that copy's first entry point.
+ 'physics3d:physx': 'es_physx3d_init',
videodec: 'es_video_open',
// One entry, not one per version: the DragonBones format is frozen, so unlike
// Spine there is no "which runtime did this binary link" question to ask.
@@ -60,6 +59,17 @@ export const NATIVE_SIDE_MODULE_PROBES: Partial<Record<SideModuleId, string>> =
...SPINE_PROBES,
};
+/**
+ * A module whose C surface the host binds under another prefix. PhysX and Jolt
+ * implement the one `physics3d_*` surface and share a binary, so the host's build
+ * renames PhysX's copy to `physx3d_*` (build-tools/tasks/native.js, PHYSX_ALIAS)
+ * and this maps the emscripten names the SDK calls back onto it:
+ * `_physics3d_step` → `es_physx3d_step`.
+ */
+export const NATIVE_PREFIX_ALIASES: Partial<Record<SideModuleId, readonly [from: string, to: string]>> = {
+ 'physics3d:physx': ['physics3d_', 'physx3d_'],
+};
+
/** The host global that reports the linked Spine runtime (38 / 41 / 42 / 43). */
export const SPINE_VERSION_BINDING = 'es_spine_runtimeVersion';
@@ -97,8 +107,9 @@ function writeUtf8(heap: NativeHeap, str: string): number {
* carries it keeps it (`_es_video_open` → `es_video_open`) — the same rule the
* generator applies when it registers the wrapper.
*/
-function hostGlobal(exportName: string): string {
- const name = exportName.slice(1);
+function hostGlobal(exportName: string, alias?: readonly [string, string]): string {
+ let name = exportName.slice(1);
+ if (alias && name.startsWith(alias[0])) name = alias[1] + name.slice(alias[0].length);
return name.startsWith('es_') ? name : `es_${name}`;
}
@@ -107,7 +118,9 @@ function hostGlobal(exportName: string): string {
* the host globals — plus the heap views, since a caller writes its buffers there
* before passing an offset.
*/
-function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideModule {
+function nativeCModule(
+ scope: Record<string, unknown>, heap: NativeHeap, alias?: readonly [string, string],
+): SideModule {
const resolved: Record<string, unknown> = {
...heap,
/**
@@ -117,7 +130,7 @@ function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideMo
* nothing left to convert — the argument types are the caller's statement about
* a surface that already agrees with them.
*/
- cwrap: (ident: string): unknown => scope[hostGlobal(`_${ident}`)],
+ cwrap: (ident: string): unknown => scope[hostGlobal(`_${ident}`, alias)],
/** The heap's string helpers, in the same terms emscripten states them. */
UTF8ToString: (ptr: number): string => readUtf8(heap, ptr),
stringToNewUTF8: (str: string): number => writeUtf8(heap, str),
@@ -126,7 +139,7 @@ function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideMo
get(target, prop): unknown {
if (prop in target) return Reflect.get(target, prop);
if (typeof prop !== 'string' || !prop.startsWith('_')) return undefined;
- const fn = scope[hostGlobal(prop)];
+ const fn = scope[hostGlobal(prop, alias)];
if (typeof fn !== 'function') return undefined;
// Remembered, so repeat calls are a plain property read (and the
// bridge's per-property guard wrapper keeps working).
@@ -136,7 +149,7 @@ function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideMo
has(target, prop): boolean {
if (prop in target) return true;
return typeof prop === 'string' && prop.startsWith('_')
- && typeof scope[hostGlobal(prop)] === 'function';
+ && typeof scope[hostGlobal(prop, alias)] === 'function';
},
}) as SideModule;
}
@@ -150,12 +163,18 @@ export function createNativeSideModules(
scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
): SideModuleHost {
const heap = createNativeHeap(scope);
- return createSideModuleHost(async (_descriptor, id): Promise<SideModule> => {
- const probe = NATIVE_SIDE_MODULE_PROBES[id];
- if (id === 'physics3d:physx') {
+ return createSideModuleHost(async (_descriptor, requested): Promise<SideModule> => {
+ let id = requested;
+ // A host built without PhysX (macOS and iOS for now, or -DESTELLA_PHYSX=OFF) still
+ // links Jolt, which answers the same surface: the project keeps its 3D
+ // world, on the other solver, and is told so once rather than losing it.
+ if (id === 'physics3d:physx' && typeof scope[NATIVE_SIDE_MODULE_PROBES[id]!] !== 'function'
+ && typeof scope[NATIVE_SIDE_MODULE_PROBES.physics3d!] === 'function') {
log.warn('sidemodule', 'this native host has no PhysX compiled in: the 3D world runs on Jolt, '
+ 'through the same interface, and a solver difference from the web build is expected');
+ id = 'physics3d';
}
+ const probe = NATIVE_SIDE_MODULE_PROBES[id];
if (!probe) {
throw new SideModuleAbsent(id, 'a native host has no side modules beyond the '
+ 'subsystems it compiles in (KTX2, for one, is decoded in C++)');
@@ -185,6 +204,6 @@ export function createNativeSideModules(
);
}
log.info('sidemodule', `${id}: native (compiled into the host)`);
- return nativeCModule(scope, heap);
+ return nativeCModule(scope, heap, NATIVE_PREFIX_ALIASES[id]);
});
}
diff --git a/sdk/tests/native-side-modules.test.ts b/sdk/tests/native-side-modules.test.ts
index 6347198af..58775da9e 100644
--- a/sdk/tests/native-side-modules.test.ts
+++ b/sdk/tests/native-side-modules.test.ts
@@ -10,7 +10,7 @@
// Driven against a mock host scope — the marshalling is what these check, not Box2D.
import { describe, it, expect, vi } from 'vitest';
import {
- createNativeSideModules, NATIVE_SIDE_MODULE_PROBES, SPINE_VERSION_BINDING,
+ createNativeSideModules, NATIVE_SIDE_MODULE_PROBES, NATIVE_PREFIX_ALIASES, SPINE_VERSION_BINDING,
} from '../src/ecs/bridge/nativeSideModules';
import { HEAP_BINDINGS } from '../src/ecs/bridge/nativeHeap';
import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
@@ -220,3 +220,54 @@ describe('spine on a native host', () => {
mod._free(ptr);
});
});
+
+describe('3D physics on a native host: Jolt and PhysX side by side', () => {
+ /** A host with Jolt's es_physics3d_* globals and, optionally, PhysX's renamed copy. */
+ function physics3dHost(physx: boolean) {
+ const { scope } = mockNativeHost({ physics: false });
+ const calls: string[] = [];
+ for (const prefix of physx ? ['physics3d', 'physx3d'] : ['physics3d']) {
+ for (const name of ['init', 'step', 'addBox']) {
+ scope[`es_${prefix}_${name}`] = () => { calls.push(`${prefix}_${name}`); return 7; };
+ }
+ }
+ return { scope, calls };
+ }
+
+ it('answers the PhysX project with the physx3d_* copy, under the names the SDK calls', async () => {
+ const { scope, calls } = physics3dHost(true);
+ const mod = (await createNativeSideModules(scope).acquire('physics3d:physx')) as unknown as {
+ _physics3d_init(...a: number[]): void; _physics3d_addBox(...a: number[]): number;
+ cwrap(ident: string): (...a: unknown[]) => unknown;
+ };
+ mod._physics3d_init(0, -9.81, 0, 1024);
+ expect(mod._physics3d_addBox(1)).toBe(7);
+ (mod.cwrap('physics3d_step') as (...a: unknown[]) => unknown)(1 / 60, 1);
+ expect(calls).toEqual(['physx3d_init', 'physx3d_addBox', 'physx3d_step']);
+ expect(NATIVE_PREFIX_ALIASES['physics3d:physx']).toEqual(['physics3d_', 'physx3d_']);
+ });
+
+ it('answers the Jolt project with Jolt in the same binary', async () => {
+ const { scope, calls } = physics3dHost(true);
+ const mod = (await createNativeSideModules(scope).acquire('physics3d')) as unknown as {
+ _physics3d_init(...a: number[]): void;
+ };
+ mod._physics3d_init(0, -9.81, 0, 1024);
+ expect(calls).toEqual(['physics3d_init']);
+ });
+
+ it('runs a PhysX project on Jolt, and says so, on a host built without PhysX', async () => {
+ const { scope, calls } = physics3dHost(false);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const mod = (await createNativeSideModules(scope).acquire('physics3d:physx')) as unknown as {
+ _physics3d_init(...a: number[]): void;
+ };
+ expect(mod).not.toBeNull();
+ mod._physics3d_init(0, -9.81, 0, 1024);
+ expect(calls).toEqual(['physics3d_init']);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
index da405ead7..e7c90bc27 100644
--- a/third_party/CMakeLists.txt
+++ b/third_party/CMakeLists.txt
@@ -105,37 +105,8 @@ endif()
# tree is a dozen targets whose only reason to be apart is DLL packaging, and no
# two of its headers share a name, so one include set serves every file.
if(ES_ENABLE_PHYSX)
- set(_PX ${CMAKE_CURRENT_SOURCE_DIR}/physx)
- file(GLOB_RECURSE PHYSX_SOURCES "${_PX}/source/*.cpp")
- # Remote debugging (PVD) is off in a release build, and the vehicle SDK has
- # no consumer here yet.
- list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/source/(pvd|physxvehicle|immediatemode)/")
- if(WIN32)
- list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/unix/")
- else()
- list(FILTER PHYSX_SOURCES EXCLUDE REGEX "/windows/")
- endif()
- add_library(physx STATIC ${PHYSX_SOURCES})
- file(GLOB_RECURSE _PX_HEADERS LIST_DIRECTORIES false "${_PX}/source/*.h")
- set(_PX_PRIVATE_DIRS "")
- # Every directory holding a header, and the ones above it: files include
- # both "Foo.h" and "omnipvd/Foo.h".
- foreach(_h ${_PX_HEADERS})
- get_filename_component(_d "${_h}" DIRECTORY)
- while(NOT _d STREQUAL "${_PX}/source" AND NOT _d STREQUAL "${_PX}")
- list(APPEND _PX_PRIVATE_DIRS "${_d}")
- get_filename_component(_d "${_d}" DIRECTORY)
- endwhile()
- endforeach()
- list(REMOVE_DUPLICATES _PX_PRIVATE_DIRS)
- target_include_directories(physx PUBLIC ${_PX}/include PRIVATE ${_PX_PRIVATE_DIRS})
- target_compile_features(physx PUBLIC cxx_std_17)
- target_compile_definitions(physx PUBLIC
- PX_PHYSX_STATIC_LIB NDEBUG PX_SUPPORT_PVD=0 PX_SUPPORT_OMNI_PVD=0
- DISABLE_CUDA_PHYSX PX_PUBLIC_RELEASE=1)
- if(NOT MSVC)
- target_compile_options(physx PRIVATE -w -fno-strict-aliasing)
- endif()
+ include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/PhysX.cmake)
+ es_add_physx_library(${CMAKE_CURRENT_SOURCE_DIR}/physx)
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
# The SSE2 path, which emscripten lowers onto wasm SIMD (the flags above
# carry -msse2). No LTO: measured, it made the module 130 KB larger.
diff --git a/third_party/physx/ESTELLA_PATCHES.md b/third_party/physx/ESTELLA_PATCHES.md
index b4409361f..e7758d66b 100644
--- a/third_party/physx/ESTELLA_PATCHES.md
+++ b/third_party/physx/ESTELLA_PATCHES.md
@@ -11,7 +11,8 @@ library by `third_party/CMakeLists.txt` (`ES_ENABLE_PHYSX`), with PVD off.
## Local patches
Upstream compiles for emscripten in name only: a wasm build still takes the
-Linux x86 paths. Each change is marked `ESTELLA` in the source.
+Linux x86 paths. Android (bionic) takes the Linux paths too, and lacks a few of
+the pthread calls they make. Each change is marked `ESTELLA` in the source.
| File | Change |
|---|---|
@@ -19,9 +20,10 @@ Linux x86 paths. Each change is marked `ESTELLA` in the source.
| `include/foundation/PxThread.h` | `PxSpinLockPause()` is empty under emscripten (no `nop`) |
| `include/foundation/PxHash.h` | the `size_t` hash overload also under emscripten (`size_t` is its own type on wasm32) |
| `source/foundation/unix/FdUnixAtomic.cpp` | `PAUSE()` empty under emscripten |
-| `source/foundation/unix/FdUnixThread.cpp` | spin pause and `yieldProcessor` empty under emscripten |
-| `source/foundation/unix/FdUnixMutex.cpp` | no mutex priority protocol under emscripten |
+| `source/foundation/unix/FdUnixThread.cpp` | spin pause and `yieldProcessor` empty under emscripten; on Android no `<bits/local_lim.h>` and no `pthread_cancel` (PhysX runs with no worker threads) |
+| `source/foundation/unix/FdUnixMutex.cpp` | no mutex priority protocol under emscripten or on Android (bionic has no `PTHREAD_PRIO_PROTECT` or `pthread_mutexattr_setprioceiling`) |
| `source/foundation/FdTempAllocator.cpp` | the size cast before `PxHighestSetBit` (ambiguous on wasm32) |
To update: replace `include/` and `source/` from the new tag, drop the same GPU
-directories, reapply the table, and run `node tools/check-physics3d-physx.mjs`.
+directories, reapply the table, and run `node tools/check-physics3d-physx.mjs`. The native
+hosts build the same tree (cmake/PhysX.cmake): rebuild one with `cli native`.
diff --git a/third_party/physx/source/foundation/unix/FdUnixMutex.cpp b/third_party/physx/source/foundation/unix/FdUnixMutex.cpp
index 64a824903..0b69e5d7f 100644
--- a/third_party/physx/source/foundation/unix/FdUnixMutex.cpp
+++ b/third_party/physx/source/foundation/unix/FdUnixMutex.cpp
@@ -26,8 +26,10 @@ PX_FORCE_INLINE bool isLegalProtocol(const int mutexProtocol)
return
(
(PTHREAD_PRIO_NONE == mutexProtocol) ||
- (PTHREAD_PRIO_INHERIT == mutexProtocol) ||
- ((PTHREAD_PRIO_PROTECT == mutexProtocol) && ((sched_getscheduler(0) == SCHED_FIFO) || (sched_getscheduler(0) == SCHED_RR)))
+ (PTHREAD_PRIO_INHERIT == mutexProtocol)
+#if !defined(__ANDROID__) // ESTELLA: bionic has no priority-ceiling mutexes
+ || ((PTHREAD_PRIO_PROTECT == mutexProtocol) && ((sched_getscheduler(0) == SCHED_FIFO) || (sched_getscheduler(0) == SCHED_RR)))
+#endif
);
}
@@ -68,7 +70,7 @@ PxMutexImpl::PxMutexImpl()
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
-#if PX_LINUX && !PX_EMSCRIPTEN // ESTELLA: no priority protocols without threads
+#if PX_LINUX && !PX_EMSCRIPTEN && !defined(__ANDROID__) // ESTELLA: no priority protocols without threads, none in bionic
pthread_mutexattr_setprotocol(&attr, gMutexProtocol);
pthread_mutexattr_setprioceiling(&attr, 0);
#endif
diff --git a/third_party/physx/source/foundation/unix/FdUnixThread.cpp b/third_party/physx/source/foundation/unix/FdUnixThread.cpp
index 45169b6d9..9ccfa204d 100644
--- a/third_party/physx/source/foundation/unix/FdUnixThread.cpp
+++ b/third_party/physx/source/foundation/unix/FdUnixThread.cpp
@@ -9,7 +9,7 @@
#include "foundation/PxThread.h"
#include <math.h>
-#if !PX_APPLE_FAMILY && !defined(__CYGWIN__) && !PX_EMSCRIPTEN
+#if !PX_APPLE_FAMILY && !defined(__CYGWIN__) && !PX_EMSCRIPTEN && !defined(__ANDROID__) // ESTELLA: bionic has it in <limits.h>
#include <bits/local_lim.h> // PTHREAD_STACK_MIN
#endif
#include <stdio.h>
@@ -225,8 +225,10 @@ __attribute__((noreturn))
void PxThreadImpl::kill()
{
+#if !defined(__ANDROID__) // ESTELLA: bionic has no pthread_cancel; Estella runs PhysX with no worker threads
if(getThread(this)->state == ePxThreadStarted)
pthread_cancel(getThread(this)->thread);
+#endif
getThread(this)->state = ePxThreadStopped;
}
diff --git a/tools/check-native-bindings.mjs b/tools/check-native-bindings.mjs
index fd173f6dd..5e8852b63 100644
--- a/tools/check-native-bindings.mjs
+++ b/tools/check-native-bindings.mjs
@@ -28,7 +28,7 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SRC = path.join(ROOT, 'src');
const BINDINGS = path.join(SRC, 'esengine', 'bindings');
-const { NATIVE_BINDING_HEADERS } = await import('../build-tools/tasks/native.js');
+const { NATIVE_BINDING_HEADERS, PHYSX_ALIAS } = await import('../build-tools/tasks/native.js');
let failed = false;
const fail = (msg) => { console.error(msg); failed = true; };
@@ -46,6 +46,7 @@ if (failed) {
// 2. The generator runs.
const out = mkdtempSync(path.join(tmpdir(), 'estella-nfb-'));
const generated = path.join(out, 'NativeFunctionBindings.generated.cpp');
+const renames = path.join(out, 'PhysX3DRename.generated.hpp');
// `python` is not a command macOS ships; `python3` is. Asking the same resolver
// the build asks is why this gate can run on a developer's machine at all — it
// was CI-only on the belief that it could not.
@@ -62,6 +63,8 @@ try {
'--native-functions', ...abs,
'--native-functions-output', generated,
'--native-shim', 'esn_shim.hpp',
+ '--native-functions-alias', PHYSX_ALIAS,
+ '--native-functions-alias-header', renames,
], { cwd: ROOT, stdio: 'pipe' });
} catch (e) {
console.error('EHT failed to generate the native entry-point bindings:');
@@ -78,7 +81,23 @@ const includes = [...text.matchAll(/^#include\s+"([^"]+)"/gm)].map((m) => m[1])
for (const inc of includes) {
if (!existsSync(path.join(SRC, inc))) fail(`generated #include does not resolve: ${inc}`);
}
+
+// 4. The PhysX copy of the 3D surface is the whole surface: every physics3d_*
+// wrapper has its physx3d_* twin, and every declared name is renamed (one left
+// out would collide with Jolt's symbol in the host link).
+const joltWrapped = new Set([...text.matchAll(/setFunction\(global, "es_physics3d_(\w+)"/g)].map((m) => m[1]));
+const physxWrapped = new Set([...text.matchAll(/setFunction\(global, "es_physx3d_(\w+)"/g)].map((m) => m[1]));
+for (const name of joltWrapped) {
+ if (!physxWrapped.has(name)) fail(`physics3d_${name} has no physx3d_ twin in the generated wrappers`);
+}
+if (joltWrapped.size === 0) fail('no physics3d_* wrappers were generated at all');
+const renameText = readFileSync(renames, 'utf8');
+const header = readFileSync(path.join(BINDINGS, 'modules/physics3d/Physics3DBindings.hpp'), 'utf8');
+for (const [, name] of header.matchAll(/\b(physics3d_\w+)\s*\(/g)) {
+ if (!renameText.includes(`#define ${name} physx3d_`)) fail(`${name} is not renamed for the PhysX build`);
+}
rmSync(out, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
if (failed) process.exit(1);
-console.log(`native bindings OK: ${abs.length} headers, ${includes.length} generated include(s) resolve.`);
+console.log(`native bindings OK: ${abs.length} headers, ${includes.length} generated include(s) resolve, `
+ + `${physxWrapped.size} PhysX twins.`);
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index ecbf8e05f..af1988262 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -14,6 +14,7 @@ from .generators import (
PtrLayoutGenerator, EditorAPIGenerator, NativeBindingsGenerator, AotComponentsGenerator,
NativeFunctionsGenerator,
)
+from .generators.native_functions import Alias
def _write_lf(path, text):
@@ -41,7 +42,16 @@ def _emit_native_functions(args) -> int:
include = '/'.join(parts[len(parts) - 1 - parts[::-1].index('src') + 1:])
headers.append((include, path.read_text(encoding='utf-8')))
- gen = NativeFunctionsGenerator(headers, shim_header=args.native_shim)
+ try:
+ aliases = [Alias.parse(spec) for spec in (args.native_functions_alias or [])]
+ except ValueError as err:
+ print(f"[FAIL] --native-functions-alias: {err}")
+ return 1
+ gen = NativeFunctionsGenerator(headers, shim_header=args.native_shim, aliases=aliases)
+ if args.native_functions_alias_header is not None:
+ args.native_functions_alias_header.parent.mkdir(parents=True, exist_ok=True)
+ print(f"Generating: {args.native_functions_alias_header}")
+ _write_lf(args.native_functions_alias_header, gen.generate_alias_header())
if args.native_functions_output is not None:
content = gen.generate()
args.native_functions_output.parent.mkdir(parents=True, exist_ok=True)
@@ -121,6 +131,13 @@ def main() -> int:
help='Where to write the generated wrappers (.cpp)')
parser.add_argument('--native-functions-ts', type=Path, default=None,
help='Also write the TS-side native engine API (.ts)')
+ # A second implementation of one C surface in the same binary (PhysX beside
+ # Jolt): <src>=<dst>:<GATE> wraps every <src>* entry point again as <dst>*,
+ # behind GATE, and the alias header renames that implementation's symbols.
+ parser.add_argument('--native-functions-alias', type=str, action='append', default=None,
+ help='Also wrap <src>* entry points as <dst>* behind GATE: <src>=<dst>:<GATE>')
+ parser.add_argument('--native-functions-alias-header', type=Path, default=None,
+ help='Write the #define rename header for the aliases (.hpp)')
args = parser.parse_args()
print("EHT - ESEngine Header Tool")
diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.py
index 8dc0259d6..16e4b7793 100644
--- a/tools/eht/generators/native_functions.py
+++ b/tools/eht/generators/native_functions.py
@@ -108,6 +108,36 @@ class Function(NamedTuple):
# C entry points (`extern "C"`) are not in namespace esengine, so the wrapper
# calls them unqualified.
extern_c: bool = False
+ # The declaration as the header spells it, so an alias can be declared with the
+ # exact same signature (see Alias).
+ decl: str = ''
+
+
+class Alias(NamedTuple):
+ """A second copy of a C surface, under another prefix.
+
+ Two implementations of ONE header can share a binary only if their symbols
+ differ: the 3D physics surface is answered by Jolt as ``physics3d_*`` and by
+ PhysX as ``physx3d_*`` (its TUs compiled with the rename header this emits).
+ The aliased wrappers are derived from the same declarations, so the second
+ backend cannot drift from the first — it is the same list under a new name,
+ behind the gate the build defines when it links that backend.
+ """
+ src: str # prefix in the header, e.g. 'physics3d_'
+ dst: str # prefix of the second implementation, e.g. 'physx3d_'
+ gate: str # the define the build sets when it links it, e.g. 'ES_ENABLE_PHYSX'
+
+ @staticmethod
+ def parse(spec: str) -> 'Alias':
+ # 'physics3d_=physx3d_:ES_ENABLE_PHYSX'
+ names, _, gate = spec.partition(':')
+ src, _, dst = names.partition('=')
+ if not src or not dst or not gate:
+ raise ValueError(f'alias "{spec}" is not <src>=<dst>:<GATE>')
+ return Alias(src, dst, gate)
+
+ def rename(self, text: str) -> str:
+ return re.sub(r'\b' + re.escape(self.src) + r'(?=\w)', self.dst, text)
class Skipped(NamedTuple):
@@ -193,7 +223,7 @@ def parse_header(text: str) -> Tuple[List[Function], List[Skipped]]:
skipped.append(Skipped(name, reason))
continue
functions.append(Function(name, ret, params, guards_at(match.start()),
- heap_return, extern_c))
+ heap_return, extern_c, match.group(0)))
return functions, skipped
@@ -271,10 +301,12 @@ def _qualify(cpp_type: str) -> str:
class NativeFunctionsGenerator:
"""Emit ``es_<name>`` native wrappers for parsed binding declarations."""
- def __init__(self, headers: List[Tuple[str, str]], shim_header: str = 'esn_shim.hpp'):
+ def __init__(self, headers: List[Tuple[str, str]], shim_header: str = 'esn_shim.hpp',
+ aliases: Optional[List[Alias]] = None):
# headers: (include path as the generated TU should spell it, source text)
self.headers = headers
self.shim_header = shim_header
+ self.aliases = aliases or []
self.skipped: List[Skipped] = []
self.emitted: List[str] = []
@@ -489,6 +521,26 @@ class NativeFunctionsGenerator:
self.skipped.extend(skipped)
lines.append('')
+ # The aliased copies: declared here (the header declares only the original
+ # names), then wrapped and registered like any other entry point.
+ for alias in self.aliases:
+ copies = [fn for fn in functions if fn.extern_c and fn.name.startswith(alias.src)]
+ if not copies:
+ raise ValueError(f'alias {alias.src}->{alias.dst}: no extern "C" entry point '
+ f'starts with {alias.src}')
+ lines.append(f'#ifdef {alias.gate}')
+ lines.append('extern "C" {')
+ lines.extend(alias.rename(fn.decl) for fn in copies)
+ lines.append('}')
+ lines.append('#endif')
+ lines.append('')
+ functions = functions + [fn._replace(
+ name=alias.rename(fn.name),
+ guards=fn.guards + (alias.gate,),
+ heap_return=alias.rename(fn.heap_return) if fn.heap_return else None,
+ decl=alias.rename(fn.decl),
+ ) for fn in copies]
+
for fn in sorted(functions, key=lambda f: f.name):
self.emitted.append(fn.name)
lines.extend(self._wrapper(fn))
@@ -503,3 +555,25 @@ class NativeFunctionsGenerator:
lines.append('}')
lines.append('')
return '\n'.join(lines)
+
+ def generate_alias_header(self) -> str:
+ """``#define <src>name <dst>name`` for every C name an alias renames — what
+ the second implementation's TUs are compiled with (forced include), so the
+ header they share declares and defines the renamed symbols. Every name the
+ header declares, the skipped ones too: a symbol left unrenamed would clash
+ with the first implementation at link time."""
+ lines = [
+ '// Auto-generated by EHT (native_functions) — DO NOT EDIT.',
+ '// Force-included into a second implementation of a C surface, so its',
+ '// symbols do not collide with the first one linked beside it.',
+ '#pragma once',
+ '',
+ ]
+ for alias in self.aliases:
+ names = set()
+ for _, text in self.headers:
+ names.update(re.findall(r'\b(' + re.escape(alias.src) + r'\w+)\s*\(', text))
+ for name in sorted(names):
+ lines.append(f'#define {name} {alias.rename(name)}')
+ lines.append('')
+ return '\n'.join(lines)
diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjs
index 7bb59aa43..42f880218 100644
--- a/tools/releaseGate.mjs
+++ b/tools/releaseGate.mjs
@@ -153,6 +153,20 @@ export const CRITERIA = [
'tests/aot/test_aot_conformance.cpp',
],
},
+ {
+ id: 'a-native-game-runs-the-solver-its-project-chose',
+ says: 'a native app runs the 3D solver (Jolt or PhysX) its project chose, not the other one under its name',
+ // Both solvers answer one interface and a host links both, so the failure
+ // is silent: a PhysX project that reached Jolt still simulates. The run must
+ // say which module it acquired, and the character's skin (PhysX's, not
+ // Jolt's) must show in where it stands.
+ answeredBy: 'node tools/verify-native-physx.mjs',
+ needs: [
+ 'tools/verify-native-physx.mjs',
+ 'sdk/src/ecs/bridge/nativeSideModules.ts',
+ 'examples/physics-3d/project.esproject',
+ ],
+ },
{
id: 'a-web-game-runs-its-systems-as-machine-code',
says: 'an exported web game loads its compiled systems and dispatches to them',
diff --git a/tools/verify-native-physx.mjs b/tools/verify-native-physx.mjs
new file mode 100644
index 000000000..b70f5d512
--- /dev/null
+++ b/tools/verify-native-physx.mjs
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file verify-native-physx.mjs — a native app runs the 3D solver its project chose.
+ *
+ * A native host links Jolt and PhysX side by side (PhysX's copy of the one
+ * physics3d_* surface renamed to physx3d_*), and the SDK picks between them from
+ * the project's `features.physics.backend3d`. The quiet failure is the fallback:
+ * a host that lost its PhysX copy, or a mapping that no longer reaches it, still
+ * runs the scene, on Jolt, and everything downstream looks fine.
+ *
+ * So examples/physics-3d is exported twice for this machine's desktop template,
+ * once per solver, and run hidden at a fixed 1/60. Held:
+ * - each run says it acquired the module it asked for, and the PhysX run never
+ * says it fell back;
+ * - the bodies that settle (stacked crates, the chain, the lift, the jointed
+ * arm) end where both solvers agree they rest;
+ * - the character does NOT agree: PhysX keeps a skin of a tenth of its radius
+ * (Unity's), Jolt none, so the PhysX hero stands higher. That difference is
+ * the proof the second run was PhysX and not Jolt answering under its name.
+ *
+ * node tools/verify-native-physx.mjs
+ */
+import { spawnSync } from 'node:child_process';
+import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { installedTemplateDir } from '../build-tools/utils/nativeTemplate.js';
+import { desktopExecutableIn } from '../build-tools/utils/desktopApp.js';
+import { requireNativeHostSuccess } from './lib/nativeHostResult.mjs';
+import { templateEmbedsBundle } from './lib/nativeBytecode.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const PROJECT = path.join(ROOT, 'examples', 'physics-3d');
+const FRAMES = 360;
+/** Bodies at rest by frame 360 on both solvers, in scene units. */
+const SETTLED = ['Crate1', 'Crate2', 'ChainBall', 'Lift', 'UpperArm'];
+const SETTLED_TOLERANCE = 0.5;
+/** PhysX's skin is radius/10; the example's hero has radius 30, so 3 units. */
+const SKIN_MIN = 1.5;
+
+const version = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
+const os = process.platform === 'darwin' ? 'macos'
+ : process.platform === 'win32' ? 'windows' : 'linux';
+
+function unanswered(why, fix) {
+ console.log(`native physx: ${why} — did NOT run.`);
+ if (fix) console.log(` ${fix}`);
+ process.exit(2);
+}
+
+function fail(what, detail) {
+ console.error(`✗ native physx: ${what}`);
+ if (detail) console.error(detail.split('\n').map((l) => ` ${l}`).join('\n'));
+ process.exit(1);
+}
+
+if (os === 'macos') unanswered('macOS hosts link Jolt only (PhysX 5 dropped Apple platforms)');
+const template = process.env.NATIVE_TEMPLATE || installedTemplateDir(version, os);
+if (!template || !existsSync(template)) {
+ unanswered(`no ${os} runtime template for v${version}`, `build one with: node build-tools/cli.js native --target ${os}`);
+}
+// The template embeds the SDK: one built before an SDK edit answers for the old one.
+const bundle = path.join(ROOT, 'sdk', 'dist', 'index.native.bundled.js');
+if (!existsSync(bundle) || !templateEmbedsBundle(template, readFileSync(bundle))) {
+ unanswered(`the ${os} template embeds a different SDK from sdk/dist`,
+ `pnpm --filter ./sdk build && node build-tools/cli.js native --target ${os}`);
+}
+
+const NAMES = [...SETTLED, 'Hero'];
+const PROBE = `
+import { defineSystem, Query, Transform, Name, addSystemToSchedule, Schedule } from 'esengine';
+let frame = 0;
+const NAMES = new Set(${JSON.stringify(NAMES)});
+addSystemToSchedule(Schedule.Update, defineSystem([Query(Transform, Name)], (rows) => {
+ if (++frame !== ${FRAMES - 2}) return;
+ const out: Record<string, number[]> = {};
+ for (const [, t, name] of rows) {
+ if (!NAMES.has(name.value)) continue;
+ const p = t.worldPosition;
+ out[name.value] = [p.x, p.y, p.z];
+ }
+ console.log('PHYSX_PROBE ' + JSON.stringify(out));
+}, { name: 'NativePhysXProbe' }));
+`;
+
+/** Export the example on `backend` and run it; answers its log and the probe. */
+function play(backend) {
+ const work = mkdtempSync(path.join(tmpdir(), `estella-native-physx-${backend}-`));
+ try {
+ const proj = path.join(work, 'project');
+ const out = path.join(work, 'out');
+ cpSync(PROJECT, proj, { recursive: true });
+ const manifest = path.join(proj, 'project.esproject');
+ const p = JSON.parse(readFileSync(manifest, 'utf8'));
+ p.features = { ...(p.features ?? {}), physics: { ...(p.features?.physics ?? {}), backend3d: backend } };
+ writeFileSync(manifest, JSON.stringify(p, null, 2));
+ writeFileSync(path.join(proj, 'src', 'nativePhysXProbe.ts'), PROBE);
+ const main = path.join(proj, 'src', 'main.ts');
+ writeFileSync(main, `${readFileSync(main, 'utf8')}\nimport './nativePhysXProbe';\n`);
+
+ const exported = spawnSync(process.execPath, [
+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', proj,
+ '--platform', 'desktop', '--out', out, '--template', template, '--no-aot',
+ ], { encoding: 'utf8', cwd: ROOT });
+ if (exported.status !== 0) fail(`the ${backend} export failed`, `${exported.stdout}${exported.stderr}`.trim().slice(-800));
+ const exe = desktopExecutableIn(out, os);
+ if (exe === null) fail(`the ${backend} export assembled no app under ${out}`);
+
+ const run = spawnSync(exe, [], {
+ encoding: 'utf8', timeout: 120_000, cwd: path.dirname(exe),
+ env: {
+ ...process.env,
+ ESTELLA_BENCH_FRAMES: String(FRAMES), ESTELLA_BENCH_WARMUP: '0',
+ ESTELLA_BENCH_DT: String(1 / 60), ESTELLA_BENCH_QUIT: '1',
+ ESTELLA_HIDDEN_WINDOW: process.env.ESTELLA_HIDDEN_WINDOW ?? '1',
+ },
+ });
+ requireNativeHostSuccess(run, `${backend} run`);
+ const log = `${run.stdout ?? ''}${run.stderr ?? ''}`;
+ const line = log.split(/\r?\n/).find((l) => l.includes('PHYSX_PROBE '));
+ if (!line) fail(`the ${backend} run printed no probe — did the scene boot?`, log.slice(-1500));
+ return { log, at: JSON.parse(line.slice(line.indexOf('PHYSX_PROBE ') + 12)) };
+ } finally {
+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }
+}
+
+const jolt = play('jolt');
+const physx = play('physx');
+
+if (!/\[sidemodule\] physics3d: native/.test(jolt.log)) fail('the Jolt run did not acquire physics3d', jolt.log.slice(-1500));
+if (/no PhysX compiled in/.test(physx.log)) {
+ fail('the PhysX run fell back to Jolt: this host has no physx3d_* copy (configured with -DESTELLA_PHYSX=OFF?)');
+}
+if (!/\[sidemodule\] physics3d:physx: native/.test(physx.log)) fail('the PhysX run did not acquire physics3d:physx', physx.log.slice(-1500));
+
+for (const name of NAMES) {
+ if (!jolt.at[name] || !physx.at[name]) fail(`${name} is missing from a probe`, JSON.stringify({ jolt: jolt.at, physx: physx.at }));
+}
+for (const name of SETTLED) {
+ const [a, b] = [jolt.at[name], physx.at[name]];
+ const d = Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
+ if (!(d <= SETTLED_TOLERANCE)) fail(`${name} rests ${d.toFixed(3)} apart on the two solvers`, `jolt ${a}\nphysx ${b}`);
+}
+const lift = physx.at.Hero[1] - jolt.at.Hero[1];
+if (!(lift >= SKIN_MIN)) {
+ fail(`the PhysX hero stands ${lift.toFixed(3)} above the Jolt one, and PhysX's skin is ${SKIN_MIN}+ — `
+ + 'did Jolt answer the PhysX run?');
+}
+console.log(`native physx: the ${os} host runs each project's solver — ${SETTLED.length} settled bodies agree, `
+ + `the PhysX character stands ${lift.toFixed(2)} higher (its skin).`);