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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): the desktop host renders on macOS, through SDL3
esengine0afe3610ff6a
diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 7837fdc32..364eee161 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -159,13 +159,16 @@ programprogram.command('native')- .description('Build the native (embedded-Dawn) host for Android or iOS arm64')- .option('--target <target>', 'android or ios', 'android')+ .description('Build the native (embedded-Dawn) host for Android, iOS or the desktop')+ .option('--target <target>', 'android, ios or macos', 'android').option('--fetch-deps', 'Check out Dawn + QuickJS-ng at the pinned commits, then stop', false).option('--build-deps', 'Build Dawn for every ABI/slice the target needs, then stop (for warming a cache)', false).option('--dawn <dir>', 'Dawn source dir (default: the pinned checkout; or ESTELLA_DAWN_DIR)').option('--dawn-build <dir>', 'Dawn build dir for this target (default: <dawn>/out-<target>, built if absent)').option('--quickjs <dir>', 'QuickJS-ng source dir (default: the pinned checkout; or ESTELLA_QUICKJS_DIR)')+ .option('--sdl <dir>', 'Desktop: SDL3 source dir or install prefix (default: the pinned checkout; or ESTELLA_SDL_DIR)')+ .option('--macos-archs <archs>', 'Desktop: CMAKE_OSX_ARCHITECTURES (arm64, or "arm64;x86_64" for a universal build)')+ .option('--macos-min <version>', 'Desktop: macOS deployment target').option('--abi <abi>', 'Android ABI', 'arm64-v8a').option('--platform <platform>', 'Android platform', 'android-29').option('--ios-min <version>', 'iOS deployment target', '17.0')@@ -196,6 +199,9 @@ programdawn: options.dawn,dawnBuild: options.dawnBuild,quickjs: options.quickjs,+ sdl: options.sdl,+ macosArchs: options.macosArchs,+ macosMin: options.macosMin,abi: options.abi,platform: options.platform,iosMin: options.iosMin,diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 0831f24d8..c24af4616 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -16,7 +16,10 @@ import * as logger from '../utils/logger.js';import { runCommand, getCpuCount, resolvePython } from '../utils/emscripten.js';import { requireSdk, requireNdk, sdkCmake } from '../utils/android.js';import { emitNativeTemplate, writeTemplateIndex, readEngineVersion } from './nativeTemplateEmit.js';-import { fetchNativeDeps, pinnedDep, ensureDawnBuild, dawnLibrary, DAWN_TARGETS } from './nativeDeps.js';+import {+ fetchNativeDeps, pinnedDep, ensureDawnBuild, ensureSdlBuild, dawnLibrary,+ isDesktopTarget, DAWN_TARGETS, MACOS_MIN,+} from './nativeDeps.js';import {ANDROID_ABIS, BYTECODE_FILE, findTemplate, iosTemplateSources, templateStoreDir,} from '../utils/nativeTemplate.js';@@ -307,6 +310,66 @@ function quickjsDir(options) {return options.quickjs || process.env.ESTELLA_QUICKJS_DIR || pinnedDep('quickjs');}+/** SDL's install prefix for a desktop target, built if it is not built yet — the+ * same "nothing has to be passed" rule as {@link dawnPaths}. */+async function sdlPrefix(options, target) {+ const sdlDir = options.sdl || process.env.ESTELLA_SDL_DIR || pinnedDep('sdl');+ if (!sdlDir) {+ throw new Error('SDL not configured. Run `node build-tools/cli.js native --fetch-deps` '+ + '(it checks out the pinned commit), or pass --sdl <src> / set ESTELLA_SDL_DIR.');+ }+ // An install PREFIX passed straight through: a machine that already has SDL3+ // installed can point at it, and there is nothing to build.+ if (existsSync(path.join(sdlDir, 'lib', 'cmake', 'SDL3'))) return sdlDir;+ return ensureSdlBuild({ sdl: sdlDir, target, macosArchs: options.macosArchs });+}++async function buildDesktopHost(options) {+ if (process.platform !== 'darwin') {+ throw new Error('The desktop host builds on macOS only so far (Windows and Linux are S1 too, '+ + 'but their surface kind and font seam are not written yet).');+ }+ const rootDir = config.paths.root;+ const target = 'macos';++ const quickjs = quickjsDir(options);+ if (!quickjs) {+ throw new Error('The desktop host needs QuickJS: run `node build-tools/cli.js native --fetch-deps`, '+ + 'or pass --quickjs <dir> (or set ESTELLA_QUICKJS_DIR).');+ }+ const { dawnDir, dawnBuild } = await dawnPaths(options, target);+ const sdl = await sdlPrefix(options, target);++ const buildDir = path.join(rootDir, DESKTOP_BUILD_DIR[target]);+ await mkdir(buildDir, { recursive: true });+ const genDir = await prepareGenerated(rootDir, buildDir, quickjs);++ const deploymentTarget = options.macosMin || MACOS_MIN;+ logger.step(`Configuring desktop host (macOS ${deploymentTarget})...`);+ await runCommand('cmake', [+ '-S', path.join(rootDir, 'native'),+ '-B', buildDir,+ '-G', 'Ninja',+ `-DCMAKE_OSX_ARCHITECTURES=${options.macosArchs || 'arm64'}`,+ `-DCMAKE_OSX_DEPLOYMENT_TARGET=${deploymentTarget}`,+ '-DCMAKE_BUILD_TYPE=Release',+ '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON',+ `-DESTELLA_DAWN_DIR=${fwd(dawnDir)}`,+ `-DESTELLA_DAWN_BUILD=${fwd(dawnBuild)}`,+ `-DESTELLA_QUICKJS_DIR=${fwd(quickjs)}`,+ `-DESTELLA_SDL_DIR=${fwd(sdl)}`,+ `-DESTELLA_NATIVE_GEN_DIR=${fwd(genDir)}`,+ ], { cwd: rootDir });++ logger.step('Building desktop host...');+ await runCommand('cmake', ['--build', buildDir, '-j', String(getCpuCount())], { cwd: rootDir });++ const exe = path.join(buildDir, 'estella_desktop');+ logger.success(`Desktop host: ${path.relative(rootDir, exe)}`);+ logger.info(`Run an export with: ${path.relative(rootDir, exe)} <exported-project-dir>`);+ return exe;+}+// CMake parses backslashes in -D string values as escapes (F:\estella -> \e), so// hand it forward-slash paths (valid on Windows too).const fwd = (p) => p.replace(/\\/g, '/');@@ -405,6 +468,12 @@ const IOS_SLICES = {};const XCFRAMEWORK = path.join('build/cmake/native-ios', 'Estella.xcframework');+/** Where each desktop OS's host build tree lives — one per OS, as the iOS slices+ * are one per sysroot, because they are different binaries. */+const DESKTOP_BUILD_DIR = {+ macos: 'build/cmake/native-macos',+};+// Rebuild the xcframework from whichever slices exist. A device-only framework is// valid — Xcode then simply has nothing to offer a simulator target.async function assembleXcframework(rootDir, env, genDir) {@@ -676,6 +745,14 @@ async function buildNativeDeps(options) {logger.success(`Dawn built for ${ANDROID_ABIS.join(', ')}`);return;}+ if (isDesktopTarget(target)) {+ // Both of them: SDL is minutes where Dawn is tens of them, but a warm cache+ // missing the small one still makes the next build fetch and configure.+ await dawnPaths(options, target);+ await sdlPrefix(options, target);+ logger.success(`Dawn and SDL built for ${target}`);+ return;+ }const developerDir = await iosDeveloperDir();const env = developerDir ? { DEVELOPER_DIR: developerDir } : undefined;for (const slice of ['ios', 'ios-sim']) {@@ -693,8 +770,18 @@ export async function buildNative(options = {}) {? options.templateIndex : path.join(config.paths.root, options.templateIndex));}const target = (options.target || 'android').toLowerCase();- if (target !== 'ios' && target !== 'android') {- throw new Error(`Unknown --target ${target} (expected android or ios).`);+ if (target !== 'ios' && target !== 'android' && !isDesktopTarget(target)) {+ throw new Error(`Unknown --target ${target} (expected android, ios or macos).`);+ }+ if (isDesktopTarget(target)) {+ // No template emit and no --package yet: those are S3, and a template that+ // claimed to exist before the assembler that reads it would be a version+ // the editor offers and cannot use.+ if (options.templateOnly || options.package) {+ throw new Error(`--${options.package ? 'package' : 'template-only'} is not implemented for `+ + `${target} yet (S3 in docs/REARCH_STEAM.md).`);+ }+ return buildDesktopHost(options);}if (options.templateOnly) return emitFromExistingBuild(target, options);// Packaging is ASSEMBLY: every piece comes from the installed runtime template,diff --git a/build-tools/tasks/nativeDeps.js b/build-tools/tasks/nativeDeps.jsindex 027ec349c..0bdc24496 100644--- a/build-tools/tasks/nativeDeps.js+++ b/build-tools/tasks/nativeDeps.js@@ -30,6 +30,12 @@ export function nativePins(rootDir = config.paths.root) {return manifest.native;}+/** Whether a target is one of the desktop OSes — the ones whose window, event loop+ * and gamepads come from SDL rather than from the OS's own app framework. */+export function isDesktopTarget(target) {+ return target === 'macos';+}+/*** Check `repo` out at `commit` in `dir`, fetching only that commit.*@@ -74,10 +80,56 @@ export async function fetchNativeDeps(options = {}) {const quickjs = await fetchAt(path.join(deps, 'quickjs'), pins.quickjs.repo, pins.quickjs.commit, 'QuickJS-ng');+ // Only the desktop host links SDL, and it is the smallest of the three, so it+ // is fetched unconditionally rather than behind a flag: a dependency you have+ // to remember to ask for is one the next person's build is missing.+ const sdl = await fetchAt(path.join(deps, 'sdl'), pins.sdl.repo, pins.sdl.commit, 'SDL3');+logger.success(`Native dependencies ready in ${path.relative(rootDir, deps) || deps}`);logger.info('Build with: node build-tools/cli.js native (Android)');logger.info(' node build-tools/cli.js native --target ios');- return { dawn, quickjs };+ logger.info(' node build-tools/cli.js native --target macos');+ return { dawn, quickjs, sdl };+}++/**+ * Build and INSTALL SDL for a desktop target, if it is not there already.+ *+ * Installed to a prefix so the host can `find_package(SDL3)` and inherit the+ * frameworks SDL declares for itself; a hand-written copy of that list goes stale+ * the first time SDL adds a subsystem. Static, matching Dawn.+ *+ * @param {object} options `{ sdl, target, buildDir, env }`+ * @returns {Promise<string>} the install prefix.+ */+export async function ensureSdlBuild(options) {+ if (!isDesktopTarget(options.target)) {+ throw new Error(`SDL is a desktop dependency; ${options.target} has its own event loop.`);+ }+ const buildDir = options.buildDir || path.join(options.sdl, `out-${options.target}`);+ const prefix = path.join(buildDir, 'install');+ if (existsSync(path.join(prefix, 'lib', 'libSDL3.a'))) return prefix;++ const cmake = options.cmake || 'cmake';+ logger.step(`Building SDL3 for ${options.target} (once per pin)...`);+ await runCommand(cmake, [+ '-S', options.sdl, '-B', buildDir, '-G', 'Ninja',+ '-DCMAKE_BUILD_TYPE=Release',+ `-DCMAKE_INSTALL_PREFIX=${prefix}`,+ '-DSDL_STATIC=ON', '-DSDL_SHARED=OFF',+ '-DSDL_TESTS=OFF', '-DSDL_EXAMPLES=OFF', '-DSDL_INSTALL_TESTS=OFF',+ // The engine renders through Dawn; SDL is the window, the events and the+ // gamepads. Its own renderers would only be dead code in the binary.+ '-DSDL_RENDER=OFF',+ ...(options.target === 'macos'+ ? [`-DCMAKE_OSX_ARCHITECTURES=${options.macosArchs || 'arm64'}`,+ `-DCMAKE_OSX_DEPLOYMENT_TARGET=${options.macosMin || MACOS_MIN}`]+ : []),+ ], { cwd: options.sdl, env: options.env });+ await runCommand(cmake, ['--build', buildDir, '--target', 'install'],+ { cwd: options.sdl, env: options.env });+ logger.success(`SDL3: ${prefix}`);+ return prefix;}/** The pinned checkout of a dependency, if it is there — what the build falls back@@ -96,11 +148,30 @@ export function pinnedDep(name, rootDir = config.paths.root) {* fetches its own dependencies should be able to build them too.*/export const DAWN_TARGETS = {- android: { out: 'out-android', shared: true },- ios: { out: 'out-ios', sysroot: 'iphoneos' },- 'ios-sim': { out: 'out-ios-sim', sysroot: 'iphonesimulator' },+ android: { out: 'out-android', shared: true, backend: 'vulkan' },+ ios: { out: 'out-ios', sysroot: 'iphoneos', backend: 'metal' },+ 'ios-sim': { out: 'out-ios-sim', sysroot: 'iphonesimulator', backend: 'metal' },+ // Static like iOS, not shared like Android: a depot whose game is ONE+ // executable has no rpath to get wrong (docs/REARCH_STEAM.md §3).+ macos: { out: 'out-macos', backend: 'metal' },};+/**+ * The backend switches, stated per target rather than defaulted off — a target+ * that names its own backend cannot inherit the wrong one from a shared list.+ *+ * OpenGL/GLES and null are off everywhere: the native renderer is WebGPU-only.+ */+function dawnBackendFlags(backend) {+ const on = (which) => `-DDAWN_ENABLE_${which}=${backend === which.toLowerCase() ? 'ON' : 'OFF'}`;+ return [on('METAL'), on('VULKAN'), on('D3D12'),+ '-DDAWN_ENABLE_NULL=OFF', '-DDAWN_ENABLE_OPENGLES=OFF', '-DDAWN_ENABLE_DESKTOP_GL=OFF'];+}++/** The oldest macOS a desktop build runs on: 11.0, the first release with arm64.+ * An arm64 binary claiming 10.15 claims something no machine can check. */+export const MACOS_MIN = '11.0';+/** Where a target's monolithic Dawn library lands, once built. */export function dawnLibrary(dawnBuild, target) {const name = DAWN_TARGETS[target].shared ? 'libwebgpu_dawn.so' : 'libwebgpu_dawn.a';@@ -131,8 +202,7 @@ export async function ensureDawnBuild(options) {const shared = ['-S', options.dawn, '-B', buildDir, '-G', 'Ninja','-DCMAKE_BUILD_TYPE=Release',- '-DDAWN_ENABLE_D3D12=OFF', '-DDAWN_ENABLE_NULL=OFF',- '-DDAWN_ENABLE_OPENGLES=OFF', '-DDAWN_ENABLE_DESKTOP_GL=OFF',+ ...dawnBackendFlags(target.backend),'-DDAWN_BUILD_SAMPLES=OFF', '-DDAWN_BUILD_TESTS=OFF', '-DTINT_BUILD_TESTS=OFF',// Cross-compiling Dawn otherwise wants a host protoc.'-DDAWN_BUILD_PROTOBUF=OFF', '-DTINT_BUILD_IR_BINARY=OFF',@@ -141,24 +211,35 @@ export async function ensureDawnBuild(options) {'-DDAWN_FETCH_DEPENDENCIES=OFF',...(options.ninja ? [`-DCMAKE_MAKE_PROGRAM=${options.ninja}`] : []),];- const perTarget = options.target === 'android'- ? [+ // Shared on Android (the APK ships the .so); static everywhere else, where one+ // binary embeds everything.+ const monolithic = `-DDAWN_BUILD_MONOLITHIC_LIBRARY=${target.shared ? 'SHARED' : 'STATIC'}`;+ let perTarget;+ if (options.target === 'android') {+ perTarget = [`-DCMAKE_TOOLCHAIN_FILE=${path.join(options.ndk, 'build', 'cmake', 'android.toolchain.cmake')}`,`-DANDROID_ABI=${options.abi || 'arm64-v8a'}`,`-DANDROID_PLATFORM=${options.androidPlatform || 'android-29'}`,'-DANDROID_STL=c++_shared',- '-DDAWN_ENABLE_VULKAN=ON', '-DDAWN_ENABLE_METAL=OFF',- // Shared on Android (the APK ships the .so); static on iOS (an app- // embeds it).- '-DDAWN_BUILD_MONOLITHIC_LIBRARY=SHARED',- ]- : [+ monolithic,+ ];+ } else if (options.target === 'macos') {+ // A HOST build: no CMAKE_SYSTEM_NAME, no sysroot, nothing cross-compiled.+ // Intel is a release-time decision (--macos-archs), not a default: it+ // doubles the longest step in the pipeline.+ perTarget = [+ `-DCMAKE_OSX_ARCHITECTURES=${options.macosArchs || 'arm64'}`,+ `-DCMAKE_OSX_DEPLOYMENT_TARGET=${options.macosMin || MACOS_MIN}`,+ monolithic,+ ];+ } else {+ perTarget = ['-DCMAKE_SYSTEM_NAME=iOS', '-DCMAKE_OSX_ARCHITECTURES=arm64',`-DCMAKE_OSX_DEPLOYMENT_TARGET=${options.iosMin || '17.0'}`,`-DCMAKE_OSX_SYSROOT=${target.sysroot}`,- '-DDAWN_ENABLE_METAL=ON', '-DDAWN_ENABLE_VULKAN=OFF',- '-DDAWN_BUILD_MONOLITHIC_LIBRARY=STATIC',+ monolithic,];+ }logger.step(`Building Dawn for ${options.target} (once per pin; this takes a few minutes)...`);await runCommand(cmake, [...shared, ...perTarget], { cwd: options.dawn, env: options.env });diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex a76adeda9..b10a4f85f 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -14,10 +14,28 @@ if(NOT ESTELLA_DAWN_DIR OR NOT ESTELLA_DAWN_BUILD)message(FATAL_ERROR "Set ESTELLA_DAWN_DIR (Dawn source) and ESTELLA_DAWN_BUILD (Dawn arm64 build). See native/README.md.")endif()+# iOS is checked FIRST because it is also APPLE: the desktop branch below would+# otherwise swallow it and try to open an SDL window on a phone.if(CMAKE_SYSTEM_NAME STREQUAL "iOS")set(ESTELLA_IOS ON)-elseif(NOT ANDROID)- message(FATAL_ERROR "Unsupported platform: configure with the NDK toolchain (Android) or -DCMAKE_SYSTEM_NAME=iOS.")+elseif(ANDROID)+ # Its own branch by exclusion; nothing to set.+elseif(APPLE)+ set(ESTELLA_DESKTOP ON)+ set(ESTELLA_MACOS ON)+else()+ message(FATAL_ERROR "Unsupported platform: configure with the NDK toolchain (Android), "+ "-DCMAKE_SYSTEM_NAME=iOS, or run on macOS for the desktop host.")+endif()++# The desktop host is an EXECUTABLE that embeds everything (see docs/REARCH_STEAM.md+# §3): SDL supplies the window, the event loop and the gamepads on all three OSes.+if(ESTELLA_DESKTOP)+ if(NOT ESTELLA_SDL_DIR)+ message(FATAL_ERROR "Set ESTELLA_SDL_DIR (an SDL3 install prefix). "+ "`node build-tools/cli.js native --fetch-deps` fetches it; the build installs it.")+ endif()+ find_package(SDL3 CONFIG REQUIRED PATHS "${ESTELLA_SDL_DIR}" NO_DEFAULT_PATH)endif()set(REPO "${CMAKE_CURRENT_SOURCE_DIR}/..")@@ -28,7 +46,7 @@ set(TP "${REPO}/third_party")# the app embeds everything). Override ESTELLA_DAWN_LIB if your build lays it out# elsewhere. A device build and a simulator build are different target triples, so# each needs its own Dawn — see ESTELLA_IOS_SIMULATOR below.-if(ESTELLA_IOS)+if(ESTELLA_IOS OR ESTELLA_DESKTOP)if(NOT ESTELLA_DAWN_LIB)set(ESTELLA_DAWN_LIB "${ESTELLA_DAWN_BUILD}/src/dawn/native/libwebgpu_dawn.a")endif()@@ -43,10 +61,17 @@ if(NOT EXISTS "${ESTELLA_DAWN_LIB}")message(FATAL_ERROR "Dawn library not found: ${ESTELLA_DAWN_LIB}. Build Dawn for this platform (see native/README.md) or pass -DESTELLA_DAWN_LIB=<path>.")endif()set_target_properties(webgpu_dawn PROPERTIES IMPORTED_LOCATION "${ESTELLA_DAWN_LIB}")-if(ESTELLA_IOS)+if(APPLE AND NOT ANDROID)# Dawn's Metal backend pulls these in; a static Dawn does not carry them along.+ # IOKit is macOS-only — the desktop backend enumerates adapters through the IO+ # registry, which is not a thing an iOS app is allowed to do.+ set(ESTELLA_DAWN_FRAMEWORKS+ "-framework Metal;-framework QuartzCore;-framework Foundation;-framework IOSurface;-framework CoreGraphics")+ if(ESTELLA_MACOS)+ list(APPEND ESTELLA_DAWN_FRAMEWORKS "-framework IOKit" "-framework Cocoa")+ endif()set_target_properties(webgpu_dawn PROPERTIES- INTERFACE_LINK_LIBRARIES "-framework Metal;-framework QuartzCore;-framework Foundation;-framework IOSurface;-framework CoreGraphics")+ INTERFACE_LINK_LIBRARIES "${ESTELLA_DAWN_FRAMEWORKS}")endif()# glm + yoga (the engine's non-emscripten third-party deps).@@ -274,6 +299,21 @@ if(ESTELLA_QUICKJS_DIR)$<TARGET_FILE:estella_dragonbones> $<TARGET_FILE:dragonbones_runtime>$<TARGET_FILE:qjs> $<TARGET_FILE:yogacore> "${ESTELLA_DAWN_LIB}"COMMENT "Merging the iOS host, engine and Dawn into libestella_ios.a")+ elseif(ESTELLA_DESKTOP)+ # An executable, not a library: on desktop there is no app shell to link+ # into — the binary IS the app, and the assembler only renames it and puts+ # the game's files beside it (docs/REARCH_STEAM.md §3).+ add_executable(estella_js_host ${HOST_SOURCES} host/platform/desktop.cpp+ host/platform/apple_common.mm)+ set_target_properties(estella_js_host PROPERTIES OUTPUT_NAME estella_desktop)+ # As on iOS: miniaudio's CoreAudio backend reaches for the Obj-C runtime, so+ # its TU is Objective-C++ on every Apple platform.+ set_source_files_properties(host/media/native_audio.cpp host/media/audio_spectrum.cpp+ PROPERTIES COMPILE_OPTIONS "-x;objective-c++")+ target_link_libraries(estella_js_host esengine estella_physics estella_video estella_spine+ estella_dragonbones qjs SDL3::SDL3+ "-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox"+ "-framework CoreText" "-framework CoreGraphics" "-framework Foundation")else()# Android: plain C++; miniaudio dlopens AAudio/OpenSL at runtime (no extra# link libs). native_audio.cpp's Obj-C paths are __APPLE__-guarded out.diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cppnew file mode 100644index 000000000..1b8358670--- /dev/null+++ b/native/host/platform/desktop.cpp@@ -0,0 +1,305 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file desktop.cpp+ * @brief The desktop glue for the JS host: an SDL3 window, the loose files+ * beside the executable, and a poll loop. One file for Windows, macOS+ * and Linux.+ * @details The mobile siblings (android.cpp / ios.mm) are one file per OS because+ * each OS supplies its own event loop, window and lifecycle, and they+ * agree on nothing. The desktop three DO agree — through SDL — so what+ * would have been three files is this one plus the two things SDL does+ * not do: matching a font file and performing an HTTP request. Those go+ * through a per-OS seam (apple_common.hpp today).+ *+ * Notably NOT here: writable directories. SDL_GetPrefPath answers that+ * on all three, and its answer is the same directory a store's cloud+ * save syncs, so there is nothing per-OS left to decide.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include <SDL3/SDL.h>+#include <SDL3/SDL_main.h>++#include <cstdio>+#include <cstring>+#include <string>+#include <vector>++#include "Host.hpp"++#if defined(__APPLE__)+#include "platform/apple_common.hpp"+#endif++using esengine::u32;+using esengine::u8;+using esengine::WebGPUDevice;++namespace {++/** The window a game opens in before it has said otherwise. 720p: the smallest+ * size every desktop display and every Steam Deck can show without scaling. */+constexpr int kDefaultWidth = 1280;+constexpr int kDefaultHeight = 720;++/** Read a whole file, or an empty vector. */+std::vector<u8> readFileBytes(const std::string& path) {+ SDL_IOStream* io = SDL_IOFromFile(path.c_str(), "rb");+ if (!io) return {};+ const Sint64 size = SDL_GetIOSize(io);+ std::vector<u8> out;+ if (size > 0) {+ out.resize(static_cast<size_t>(size));+ if (SDL_ReadIO(io, out.data(), out.size()) != out.size()) out.clear();+ }+ SDL_CloseIO(io);+ return out;+}++struct DesktopPlatform final : eshost::Platform {+ SDL_Window* window = nullptr;+ /** The CAMetalLayer / HWND / Wayland surface Dawn draws into, from SDL. */+ void* nativeWindow = nullptr;+ /** Where the packaged game's files are — see resolveContentRoot. */+ std::string contentRoot;+ /** SDL_GetPrefPath's directory, kept because every call allocates. */+ std::string prefPath;++ // Loose files in a directory, not an APK's assets or a bundle: that is what a+ // depot ships and what an export already is, so packaging copies rather than+ // repackages.+ std::vector<u8> readAsset(const char* path) override {+ if (contentRoot.empty() || !path) return {};+ return readFileBytes(contentRoot + path);+ }++ /** Regenerable state, under the same per-user root as the saves — a store+ * syncs that root, and a cache that syncs is merely slow where a save that+ * does not is a lost game. */+ std::string cacheDir() override {+ if (prefPath.empty()) return {};+ const std::string dir = prefPath + "cache";+ if (!SDL_CreateDirectory(dir.c_str())) return {};+ return dir;+ }++ std::string dataDir() override { return prefPath; }++ /** The same directory: on desktop the player can open it, which is the whole+ * reason the mobile platforms distinguish a log dir from a private one. */+ std::string logDir() override { return prefPath; }++ std::vector<std::string> publicDirs() override {+ return prefPath.empty() ? std::vector<std::string>{} : std::vector<std::string>{prefPath};+ }++ std::string describe() override {+ std::string out = std::string(SDL_GetPlatform()) + ", ";+ // Version at RUN time, not build time: the first question about a failure+ // on someone else's machine is which OS it was.+ const int v = SDL_GetSystemRAM();+ out += std::to_string(v) + " MB RAM, ";+ out += std::to_string(SDL_GetNumLogicalCPUCores()) + " cores, ";+#if defined(__aarch64__) || defined(_M_ARM64)+ out += "arm64";+#elif defined(__x86_64__) || defined(_M_X64)+ out += "x86_64";+#else+ out += "unknown arch";+#endif+ return out;+ }++ WGPUBackendType backend() const override {+#if defined(__APPLE__)+ return WGPUBackendType_Metal;+#elif defined(_WIN32)+ return WGPUBackendType_D3D12;+#else+ return WGPUBackendType_Vulkan;+#endif+ }++ WebGPUDevice::NativeSurface surface() override {+#if defined(__APPLE__)+ return {WebGPUDevice::NativeWindowKind::MetalLayer, nativeWindow};+#else+#error "The desktop host has only its Apple surface so far — see docs/REARCH_STEAM.md S1."+#endif+ }++ void surfaceSize(u32& width, u32& height) override {+ int w = 0, h = 0;+ if (window) SDL_GetWindowSizeInPixels(window, &w, &h);+ width = static_cast<u32>(w < 0 ? 0 : w);+ height = static_cast<u32>(h < 0 ? 0 : h);+ }++ void log(bool error, const char* message) override {+ SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION,+ error ? SDL_LOG_PRIORITY_ERROR : SDL_LOG_PRIORITY_INFO,+ "[Estella] %s", message);+ }++#if defined(__APPLE__)+ eshost::FontFile loadFont(const std::string& family, u32 codepoint, int style) override {+ return eshost::appleLoadFont(family, codepoint, style);+ }++ void startFetch(const eshost::FetchRequest& req) override { eshost::appleStartFetch(req); }+#endif+};++DesktopPlatform g_platform;++/**+ * Where the game's files are.+ *+ * The argument and the environment variable run an export straight out of the+ * editor's output directory. A SHIPPED game takes the third branch: content+ * beside the executable, put there by the assembler.+ */+std::string resolveContentRoot(int argc, char** argv) {+ auto withSlash = [](std::string p) {+ if (!p.empty() && p.back() != '/' && p.back() != '\\') p += '/';+ return p;+ };+ if (argc > 1 && argv[1] && argv[1][0]) return withSlash(argv[1]);+ if (const char* env = SDL_getenv("ESTELLA_CONTENT"); env && env[0]) return withSlash(env);++ const char* base = SDL_GetBasePath();+ if (!base) return {};+ // `Content/` first, so a bundle that also holds the runtime's own files can+ // keep the game's separate — the layout the macOS .app and the Steam depot use.+ const std::string content = std::string(base) + "Content/";+ return readFileBytes(content + "game.config.json").empty() ? std::string(base) : content;+}++/** The app's name, for the window and for the saves directory.+ *+ * From the executable, which on desktop IS the identity the assembler set.+ * Deliberately not app.config.json: that is the PACKAGER's input, and a runtime+ * reading it too would be a second opinion about this app's name. */+std::string appName(int argc, char** argv) {+ if (argc < 1 || !argv[0] || !argv[0][0]) return "Estella";+ std::string path = argv[0];+ const size_t slash = path.find_last_of("/\\");+ std::string name = slash == std::string::npos ? path : path.substr(slash + 1);+#if defined(_WIN32)+ if (name.size() > 4 && name.compare(name.size() - 4, 4, ".exe") == 0) name.resize(name.size() - 4);+#endif+ return name.empty() ? "Estella" : name;+}++} // namespace++int main(int argc, char** argv) {+ // Video and gamepads; NOT audio — the host's audio is miniaudio, which opens+ // the device itself, and a second audio subsystem would be a second claim on it.+ if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) {+ SDL_Log("SDL_Init failed: %s", SDL_GetError());+ return 1;+ }++ const std::string name = appName(argc, argv);+ g_platform.contentRoot = resolveContentRoot(argc, argv);+ if (char* pref = SDL_GetPrefPath("Estella", name.c_str())) {+ g_platform.prefPath = pref;+ SDL_free(pref);+ }++ SDL_Window* window = SDL_CreateWindow(name.c_str(), kDefaultWidth, kDefaultHeight,+ SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY+ | SDL_WINDOW_METAL);+ if (!window) {+ SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());+ SDL_Quit();+ return 1;+ }+ g_platform.window = window;++#if defined(__APPLE__)+ // Dawn's Metal backend draws into a CAMetalLayer; SDL owns the view that+ // carries it, including its contents scale.+ SDL_MetalView view = SDL_Metal_CreateView(window);+ if (!view) {+ SDL_Log("SDL_Metal_CreateView failed: %s", SDL_GetError());+ SDL_Quit();+ return 1;+ }+ g_platform.nativeWindow = SDL_Metal_GetLayer(view);+#endif++ if (!eshost::boot(g_platform)) {+ SDL_Log("Estella host failed to boot — see the log above.");+ SDL_Quit();+ return 1;+ }++ bool running = true;+ bool pointerDown = false;++ auto handleEvent = [&](const SDL_Event& e) {+ switch (e.type) {+ case SDL_EVENT_QUIT:+ running = false;+ break;+ case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:+ eshost::bindSurface();+ break;+ case SDL_EVENT_WINDOW_MINIMIZED:+ case SDL_EVENT_WINDOW_HIDDEN:+ eshost::surfaceLost();+ eshost::setVisible(false);+ break;+ case SDL_EVENT_WINDOW_RESTORED:+ case SDL_EVENT_WINDOW_SHOWN:+ eshost::setVisible(true);+ eshost::bindSurface();+ break;+ // Mouse as the primary pointer, so a touch-built game is playable.+ // The real desktop surface (other buttons, wheel, keyboard, gamepads)+ // is S2 — Host.hpp takes only touch today.+ case SDL_EVENT_MOUSE_BUTTON_DOWN:+ if (e.button.button == SDL_BUTTON_LEFT) {+ pointerDown = true;+ const float s = SDL_GetWindowPixelDensity(window);+ eshost::touch(0, 0, e.button.x * s, e.button.y * s);+ }+ break;+ case SDL_EVENT_MOUSE_MOTION:+ if (pointerDown) {+ const float s = SDL_GetWindowPixelDensity(window);+ eshost::touch(1, 0, e.motion.x * s, e.motion.y * s);+ }+ break;+ case SDL_EVENT_MOUSE_BUTTON_UP:+ if (e.button.button == SDL_BUTTON_LEFT && pointerDown) {+ pointerDown = false;+ const float s = SDL_GetWindowPixelDensity(window);+ eshost::touch(2, 0, e.button.x * s, e.button.y * s);+ }+ break;+ default:+ break;+ }+ };++ while (running) {+ SDL_Event e;+ // A hidden or minimized window has no surface to present to, so the loop+ // blocks for an event rather than spinning at the display's refresh rate.+ if (!eshost::surfaceBound() && SDL_WaitEvent(&e)) handleEvent(e);+ while (SDL_PollEvent(&e)) handleEvent(e);+ if (running && eshost::surfaceBound()) eshost::frame();+ if (eshost::quitRequested()) running = false;+ }++ SDL_Quit();+ return 0;+}diff --git a/toolchain.manifest.json b/toolchain.manifest.jsonindex 553cc683a..55bf77d3f 100644--- a/toolchain.manifest.json+++ b/toolchain.manifest.json@@ -44,6 +44,17 @@"quickjs": {"repo": "https://github.com/quickjs-ng/quickjs","commit": "3d3cf3d86b66551403745a5b06acbed2b0f31dfd"+ },+ "sdl": {+ "$comment": [+ "The desktop window, event loop, gamepads and IME (release-3.4.14). Desktop only:",+ "iOS and Android already have an OS event loop the host drives, and adding a second",+ "one there would be a rewrite of two working platforms to no end.",+ "Pinned to the tag's COMMIT, like the other two — a tag is a moving ref, and a",+ "runtime template other people install has to rebuild to the same bytes."+ ],+ "repo": "https://github.com/libsdl-org/SDL",+ "commit": "147a8ee32dbf9ac02f3794964490687b6bbda1bc"}},"cmake": {