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): the Windows half of the desktop seam

esengine505f6e6521b5
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index 3ffca6100..b09db6f84 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -325,13 +325,22 @@ async function sdlPrefix(options, target) {
return ensureSdlBuild({ sdl: sdlDir, target, macosArchs: options.macosArchs });
}
+/** The desktop target this machine can build: a desktop host is never cross-compiled,
+ * because its window, its GPU backend and its font stack are all the host OS's. */
+function hostDesktopTarget() {
+ if (process.platform === 'darwin') return 'macos';
+ if (process.platform === 'win32') return 'windows';
+ throw new Error(`The desktop host has no ${process.platform} support yet `
+ + '(its surface kind and font seam are not written) — see docs/REARCH_STEAM.md S3c.');
+}
+
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 target = hostDesktopTarget();
+ if (options.target && options.target.toLowerCase() !== target) {
+ throw new Error(`Cannot build the ${options.target} host on ${process.platform}: a desktop `
+ + 'host is not cross-compiled — its window, GPU backend and font stack are the host OS\'s.');
+ }
const quickjs = quickjsDir(options);
if (!quickjs) {
@@ -346,13 +355,15 @@ async function buildDesktopHost(options) {
const genDir = await prepareGenerated(rootDir, buildDir, quickjs);
const deploymentTarget = options.macosMin || MACOS_MIN;
- logger.step(`Configuring desktop host (macOS ${deploymentTarget})...`);
+ logger.step(`Configuring desktop host (${target})...`);
await runCommand('cmake', [
'-S', path.join(rootDir, 'native'),
'-B', buildDir,
'-G', 'Ninja',
- `-DCMAKE_OSX_ARCHITECTURES=${options.macosArchs || 'arm64'}`,
- `-DCMAKE_OSX_DEPLOYMENT_TARGET=${deploymentTarget}`,
+ ...(target === 'macos'
+ ? [`-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)}`,
@@ -365,7 +376,7 @@ async function buildDesktopHost(options) {
logger.step('Building desktop host...');
await runCommand('cmake', ['--build', buildDir, '-j', String(getCpuCount())], { cwd: rootDir });
- const exe = path.join(buildDir, 'estella_desktop');
+ const exe = path.join(buildDir, target === 'windows' ? 'estella_desktop.exe' : 'estella_desktop');
logger.success(`Desktop host: ${path.relative(rootDir, exe)}`);
// Same rule as the other two: the compiled half is project-independent, so it
@@ -479,6 +490,7 @@ const XCFRAMEWORK = path.join('build/cmake/native-ios', 'Estella.xcframework');
* are one per sysroot, because they are different binaries. */
const DESKTOP_BUILD_DIR = {
macos: 'build/cmake/native-macos',
+ windows: 'build/cmake/native-windows',
};
// Rebuild the xcframework from whichever slices exist. A device-only framework is
diff --git a/build-tools/tasks/nativeDeps.js b/build-tools/tasks/nativeDeps.js
index 0bdc24496..1f7cc3c21 100644
--- a/build-tools/tasks/nativeDeps.js
+++ b/build-tools/tasks/nativeDeps.js
@@ -33,7 +33,7 @@ export function nativePins(rootDir = config.paths.root) {
/** 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';
+ return target === 'macos' || target === 'windows';
}
/**
@@ -89,6 +89,7 @@ export async function fetchNativeDeps(options = {}) {
logger.info('Build with: node build-tools/cli.js native (Android)');
logger.info(' node build-tools/cli.js native --target ios');
logger.info(' node build-tools/cli.js native --target macos');
+ logger.info(' node build-tools/cli.js native --target windows (from a vcvars64 shell)');
return { dawn, quickjs, sdl };
}
@@ -108,7 +109,9 @@ export async function ensureSdlBuild(options) {
}
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;
+ // The package config, not the library: its name differs per toolchain
+ // (libSDL3.a, SDL3-static.lib) and this is what find_package looks for anyway.
+ if (existsSync(path.join(prefix, 'lib', 'cmake', 'SDL3'))) return prefix;
const cmake = options.cmake || 'cmake';
logger.step(`Building SDL3 for ${options.target} (once per pin)...`);
@@ -154,6 +157,7 @@ export const DAWN_TARGETS = {
// 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' },
+ windows: { out: 'out-windows', backend: 'd3d12' },
};
/**
@@ -172,10 +176,12 @@ function dawnBackendFlags(backend) {
* 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. */
+/** Where a target's monolithic Dawn library lands, once built. MSVC names a static
+ * library `<name>.lib` and puts a multi-config build under its configuration. */
export function dawnLibrary(dawnBuild, target) {
- const name = DAWN_TARGETS[target].shared ? 'libwebgpu_dawn.so' : 'libwebgpu_dawn.a';
- return path.join(dawnBuild, 'src', 'dawn', 'native', name);
+ const dir = path.join(dawnBuild, 'src', 'dawn', 'native');
+ if (target === 'windows') return path.join(dir, 'webgpu_dawn.lib');
+ return path.join(dir, DAWN_TARGETS[target].shared ? 'libwebgpu_dawn.so' : 'libwebgpu_dawn.a');
}
/** Dawn's build directory for a target. Android's is per-ABI — an emulator build
@@ -223,6 +229,10 @@ export async function ensureDawnBuild(options) {
'-DANDROID_STL=c++_shared',
monolithic,
];
+ } else if (options.target === 'windows') {
+ // Nothing to cross-compile and no sysroot; the toolchain comes from the
+ // environment, which on Windows means a shell that has run vcvars64.
+ perTarget = [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
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 7d14c3111..8871b2d3d 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -116,7 +116,7 @@ export function androidTemplateSources(dir: string): {
bytecode: string;
};
-export function desktopTemplateSources(dir: string): {
+export function desktopTemplateSources(dir: string, platform?: NativePlatform): {
/** The runtime binary; the assembler renames it to the app. */
executable: string;
infoPlistIn: string;
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index e841d1fd4..af80409dc 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -95,26 +95,33 @@ export function templateLayout(platform, options = {}) {
},
];
}
- if (platform === 'macos') {
+ if (platform === 'macos' || platform === 'windows') {
+ const exe = platform === 'windows' ? 'estella_desktop.exe' : 'estella_desktop';
+ const buildDir = `build/cmake/native-${platform}`;
// The shortest layout of the three, because a desktop build embeds
// everything: Dawn and SDL are linked statically, so the runtime is one
// executable and there is no second file to find at run time.
return [
{
- rel: 'estella_desktop', strip: true,
- from: (ctx) => path.join(ctx.root, 'build/cmake/native-macos', 'estella_desktop'),
+ // MSVC leaves debug info in a separate .pdb, so there is nothing to
+ // strip out of the executable — and no signature to invalidate.
+ rel: exe, strip: platform === 'macos',
+ from: (ctx) => path.join(ctx.root, buildDir, exe),
},
// Beside the game's own files, not in a directory of its own: the host
// reads it through Platform::readAsset, which is one namespace — the
// same one the APK's assets/ is.
{
rel: BYTECODE_FILE, optional: true, releaseRequired: true,
- from: (ctx) => path.join(ctx.root, 'build/cmake/native-macos', 'gen', BYTECODE_FILE),
+ from: (ctx) => path.join(ctx.root, buildDir, 'gen', BYTECODE_FILE),
},
- {
+ // The bundle description macOS wants; Windows has no counterpart, and
+ // an entry every consumer would have to check for is worse than a
+ // layout that differs where the platforms do.
+ ...(platform === 'macos' ? [{
rel: 'Info.plist.in',
from: (ctx) => path.join(ctx.root, 'native', 'desktop', 'Info.plist.in'),
- },
+ }] : []),
{ rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },
];
}
@@ -422,9 +429,9 @@ export function iosTemplateSources(dir) {
/** The desktop equivalent — the runtime binary and the three files the assembler
* composes an app bundle from. */
-export function desktopTemplateSources(dir) {
+export function desktopTemplateSources(dir, platform = 'macos') {
return {
- executable: path.join(dir, 'estella_desktop'),
+ executable: path.join(dir, platform === 'windows' ? 'estella_desktop.exe' : 'estella_desktop'),
infoPlistIn: path.join(dir, 'Info.plist.in'),
icon: path.join(dir, DEFAULT_ICON),
bytecode: path.join(dir, BYTECODE_FILE),
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 9dad66702..4449cf172 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -23,9 +23,12 @@ elseif(ANDROID)
elseif(APPLE)
set(ESTELLA_DESKTOP ON)
set(ESTELLA_MACOS ON)
+elseif(WIN32)
+ set(ESTELLA_DESKTOP ON)
+ set(ESTELLA_WINDOWS 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.")
+ "-DCMAKE_SYSTEM_NAME=iOS, or run on macOS/Windows for the desktop host.")
endif()
# The desktop host is an EXECUTABLE that embeds everything (see docs/REARCH_STEAM.md
@@ -48,7 +51,12 @@ set(TP "${REPO}/third_party")
# each needs its own Dawn — see ESTELLA_IOS_SIMULATOR below.
if(ESTELLA_IOS OR ESTELLA_DESKTOP)
if(NOT ESTELLA_DAWN_LIB)
- set(ESTELLA_DAWN_LIB "${ESTELLA_DAWN_BUILD}/src/dawn/native/libwebgpu_dawn.a")
+ # MSVC names a static library <name>.lib; everyone else lib<name>.a.
+ if(ESTELLA_WINDOWS)
+ set(ESTELLA_DAWN_LIB "${ESTELLA_DAWN_BUILD}/src/dawn/native/webgpu_dawn.lib")
+ else()
+ set(ESTELLA_DAWN_LIB "${ESTELLA_DAWN_BUILD}/src/dawn/native/libwebgpu_dawn.a")
+ endif()
endif()
add_library(webgpu_dawn STATIC IMPORTED)
else()
@@ -304,17 +312,32 @@ if(ESTELLA_QUICKJS_DIR)
# 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).
+ #
+ # One glue TU (desktop.cpp) plus the per-OS half SDL does not cover: the
+ # font match and the HTTP request.
+ if(ESTELLA_WINDOWS)
+ set(DESKTOP_OS_SOURCES host/platform/windows_common.cpp)
+ else()
+ set(DESKTOP_OS_SOURCES host/platform/apple_common.mm)
+ endif()
add_executable(estella_js_host ${HOST_SOURCES} host/platform/desktop.cpp
- host/platform/apple_common.mm)
+ ${DESKTOP_OS_SOURCES})
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")
+ estella_dragonbones qjs SDL3::SDL3)
+ if(ESTELLA_WINDOWS)
+ # Dawn's D3D12 backend, DirectWrite for the font match, WinHTTP for the
+ # fetch. miniaudio reaches WASAPI through the COM headers it includes.
+ target_link_libraries(estella_js_host d3d12 dxgi dxguid dwrite winhttp)
+ else()
+ # 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
+ "-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox"
+ "-framework CoreText" "-framework CoreGraphics" "-framework Foundation")
+ endif()
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.cpp
index e684b938d..791dd6b62 100644
--- a/native/host/platform/desktop.cpp
+++ b/native/host/platform/desktop.cpp
@@ -36,6 +36,8 @@
#if defined(__APPLE__)
#include "platform/apple_common.hpp"
+#elif defined(_WIN32)
+#include "platform/windows_common.hpp"
#endif
using esengine::u32;
@@ -97,6 +99,8 @@ struct DesktopPlatform final : eshost::Platform {
SDL_Window* window = nullptr;
/** The CAMetalLayer / HWND / Wayland surface Dawn draws into, from SDL. */
void* nativeWindow = nullptr;
+ /** Win32 only: the HWND's HINSTANCE, which the surface descriptor also wants. */
+ void* windowInstance = nullptr;
/** Where the packaged game's files are — see resolveContentRoot. */
std::string contentRoot;
/** SDL_GetPrefPath's directory, kept because every call allocates. */
@@ -160,8 +164,10 @@ struct DesktopPlatform final : eshost::Platform {
WebGPUDevice::NativeSurface surface() override {
#if defined(__APPLE__)
return {WebGPUDevice::NativeWindowKind::MetalLayer, nativeWindow};
+#elif defined(_WIN32)
+ return {WebGPUDevice::NativeWindowKind::Win32Hwnd, nativeWindow, windowInstance};
#else
-#error "The desktop host has only its Apple surface so far — see docs/REARCH_STEAM.md S1."
+#error "The desktop host has no Linux surface yet — see docs/REARCH_STEAM.md S3c."
#endif
}
@@ -219,6 +225,12 @@ struct DesktopPlatform final : eshost::Platform {
}
void startFetch(const eshost::FetchRequest& req) override { eshost::appleStartFetch(req); }
+#elif defined(_WIN32)
+ eshost::FontFile loadFont(const std::string& family, u32 codepoint, int style) override {
+ return eshost::windowsLoadFont(family, codepoint, style);
+ }
+
+ void startFetch(const eshost::FetchRequest& req) override { eshost::windowsStartFetch(req); }
#endif
};
@@ -283,9 +295,13 @@ int main(int argc, char** argv) {
SDL_free(pref);
}
- SDL_Window* window = SDL_CreateWindow(name.c_str(), kDefaultWidth, kDefaultHeight,
- SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY
- | SDL_WINDOW_METAL);
+ // SDL_WINDOW_METAL only where Metal is the backend: elsewhere it is a request
+ // for a surface the platform does not have, and window creation fails.
+ SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY;
+#if defined(__APPLE__)
+ flags |= SDL_WINDOW_METAL;
+#endif
+ SDL_Window* window = SDL_CreateWindow(name.c_str(), kDefaultWidth, kDefaultHeight, flags);
if (!window) {
SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());
SDL_Quit();
@@ -303,6 +319,17 @@ int main(int argc, char** argv) {
return 1;
}
g_platform.nativeWindow = SDL_Metal_GetLayer(view);
+#elif defined(_WIN32)
+ // D3D12 draws straight into the window, so there is no view to make: the
+ // HWND and its HINSTANCE are what the surface descriptor asks for.
+ SDL_PropertiesID props = SDL_GetWindowProperties(window);
+ g_platform.nativeWindow = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
+ g_platform.windowInstance = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_INSTANCE_POINTER, nullptr);
+ if (!g_platform.nativeWindow) {
+ SDL_Log("SDL gave no HWND for the window — cannot create a D3D12 surface.");
+ SDL_Quit();
+ return 1;
+ }
#endif
if (!eshost::boot(g_platform)) {
diff --git a/native/host/platform/windows_common.cpp b/native/host/platform/windows_common.cpp
new file mode 100644
index 000000000..b73c5dc75
--- /dev/null
+++ b/native/host/platform/windows_common.cpp
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file windows_common.cpp
+ * @brief DirectWrite font matching and WinHTTP fetching. See the header.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "platform/windows_common.hpp"
+
+#include <windows.h>
+#include <dwrite.h>
+#include <winhttp.h>
+
+#include <thread>
+#include <vector>
+
+#include "media/glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC
+
+namespace eshost {
+namespace {
+
+using esengine::u8;
+using esengine::u32;
+
+std::wstring widen(const std::string& text) {
+ if (text.empty()) return {};
+ const int n = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), (int)text.size(), nullptr, 0);
+ std::wstring out((size_t)n, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, text.c_str(), (int)text.size(), out.data(), n);
+ return out;
+}
+
+std::string narrow(const std::wstring& text) {
+ if (text.empty()) return {};
+ const int n = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(),
+ nullptr, 0, nullptr, nullptr);
+ std::string out((size_t)n, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(), out.data(), n, nullptr, nullptr);
+ return out;
+}
+
+/** The process-wide DirectWrite factory. Created once: the factory is the
+ * expensive part and the system font collection hangs off it. */
+IDWriteFactory* factory() {
+ static IDWriteFactory* f = [] {
+ IDWriteFactory* created = nullptr;
+ DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
+ reinterpret_cast<IUnknown**>(&created));
+ return created;
+ }();
+ return f;
+}
+
+/** The file behind a font face, and which face inside it. A collection (.ttc)
+ * holds several, so the index has to travel with the bytes. */
+bool readFaceFile(IDWriteFontFace* face, FontFile& out) {
+ UINT32 fileCount = 0;
+ if (FAILED(face->GetFiles(&fileCount, nullptr)) || fileCount == 0) return false;
+ std::vector<IDWriteFontFile*> files(fileCount, nullptr);
+ if (FAILED(face->GetFiles(&fileCount, files.data()))) return false;
+
+ bool ok = false;
+ const void* key = nullptr;
+ UINT32 keySize = 0;
+ IDWriteFontFileLoader* loader = nullptr;
+ if (SUCCEEDED(files[0]->GetReferenceKey(&key, &keySize))
+ && SUCCEEDED(files[0]->GetLoader(&loader)) && loader) {
+ IDWriteLocalFontFileLoader* local = nullptr;
+ if (SUCCEEDED(loader->QueryInterface(__uuidof(IDWriteLocalFontFileLoader),
+ reinterpret_cast<void**>(&local))) && local) {
+ UINT32 length = 0;
+ if (SUCCEEDED(local->GetFilePathLengthFromKey(key, keySize, &length))) {
+ std::wstring path(length + 1, L'\0');
+ if (SUCCEEDED(local->GetFilePathFromKey(key, keySize, path.data(), length + 1))) {
+ path.resize(length);
+ if (HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ,
+ nullptr, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, nullptr);
+ handle != INVALID_HANDLE_VALUE) {
+ LARGE_INTEGER size{};
+ if (GetFileSizeEx(handle, &size) && size.QuadPart > 0) {
+ out.bytes.resize((size_t)size.QuadPart);
+ DWORD read = 0;
+ ok = ReadFile(handle, out.bytes.data(), (DWORD)out.bytes.size(), &read, nullptr)
+ && read == out.bytes.size();
+ }
+ CloseHandle(handle);
+ }
+ if (ok) {
+ out.path = narrow(path);
+ out.faceIndex = (int)face->GetIndex();
+ }
+ }
+ }
+ local->Release();
+ }
+ loader->Release();
+ }
+ for (IDWriteFontFile* file : files) if (file) file->Release();
+ return ok;
+}
+
+} // namespace
+
+FontFile windowsLoadFont(const std::string& family, u32 codepoint, int style) {
+ FontFile out;
+ IDWriteFactory* dw = factory();
+ if (!dw) return out;
+
+ IDWriteFontCollection* collection = nullptr;
+ if (FAILED(dw->GetSystemFontCollection(&collection, FALSE)) || !collection) return out;
+
+ const DWRITE_FONT_WEIGHT weight = (style & GLYPH_BOLD)
+ ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
+ const DWRITE_FONT_STYLE slant = (style & GLYPH_ITALIC)
+ ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
+
+ // Segoe UI is the system font, and the fallback when the family is unknown —
+ // the same role Helvetica plays on Apple.
+ const std::wstring wanted = widen(family.empty() ? "Segoe UI" : family);
+ UINT32 index = 0;
+ BOOL exists = FALSE;
+ if (FAILED(collection->FindFamilyName(wanted.c_str(), &index, &exists)) || !exists) {
+ collection->FindFamilyName(L"Segoe UI", &index, &exists);
+ }
+ if (!exists) { collection->Release(); return out; }
+
+ IDWriteFontFamily* fam = nullptr;
+ if (FAILED(collection->GetFontFamily(index, &fam)) || !fam) { collection->Release(); return out; }
+
+ IDWriteFont* font = nullptr;
+ if (FAILED(fam->GetFirstMatchingFont(weight, DWRITE_FONT_STRETCH_NORMAL, slant, &font)) || !font) {
+ fam->Release();
+ collection->Release();
+ return out;
+ }
+
+ // A family with no real bold or italic face leaves the trait unmet; the
+ // rasterizer then synthesizes it, as a browser does for the same family.
+ out.syntheticBold = (style & GLYPH_BOLD) && font->GetWeight() < DWRITE_FONT_WEIGHT_SEMI_BOLD;
+ out.syntheticItalic = (style & GLYPH_ITALIC) && font->GetStyle() == DWRITE_FONT_STYLE_NORMAL;
+
+ // Does this face cover the codepoint? If not, let DirectWrite find one that
+ // does — the CJK fallback, which is the whole reason this is platform code.
+ if (codepoint) {
+ BOOL has = FALSE;
+ if (SUCCEEDED(font->HasCharacter(codepoint, &has)) && !has) {
+ for (UINT32 i = 0; i < collection->GetFontFamilyCount(); ++i) {
+ IDWriteFontFamily* candidate = nullptr;
+ if (FAILED(collection->GetFontFamily(i, &candidate)) || !candidate) continue;
+ IDWriteFont* other = nullptr;
+ if (SUCCEEDED(candidate->GetFirstMatchingFont(weight, DWRITE_FONT_STRETCH_NORMAL,
+ slant, &other)) && other) {
+ BOOL covers = FALSE;
+ if (SUCCEEDED(other->HasCharacter(codepoint, &covers)) && covers) {
+ font->Release();
+ font = other;
+ candidate->Release();
+ break;
+ }
+ other->Release();
+ }
+ candidate->Release();
+ }
+ }
+ }
+
+ IDWriteFontFace* face = nullptr;
+ if (SUCCEEDED(font->CreateFontFace(&face)) && face) {
+ if (!readFaceFile(face, out)) out.path.clear();
+ face->Release();
+ }
+ font->Release();
+ fam->Release();
+ collection->Release();
+ return out;
+}
+
+void windowsStartFetch(const FetchRequest& req) {
+ // A detached thread per request, as NSURLSession's completion queue is on
+ // Apple: WinHTTP's synchronous API is the simple one, and the reply reaches
+ // JS through deliverFetch, which is thread-safe by contract.
+ std::thread([req]() {
+ FetchResult result;
+ result.id = req.id;
+ result.isText = req.wantText;
+
+ const std::wstring url = widen(req.url);
+ URL_COMPONENTS parts{};
+ parts.dwStructSize = sizeof(parts);
+ wchar_t host[256]{};
+ wchar_t path[4096]{};
+ parts.lpszHostName = host;
+ parts.dwHostNameLength = (DWORD)std::size(host);
+ parts.lpszUrlPath = path;
+ parts.dwUrlPathLength = (DWORD)std::size(path);
+ if (!WinHttpCrackUrl(url.c_str(), (DWORD)url.size(), 0, &parts)) {
+ result.error = "invalid url";
+ deliverFetch(std::move(result));
+ return;
+ }
+
+ HINTERNET session = WinHttpOpen(L"Estella", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
+ WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ HINTERNET connection = session
+ ? WinHttpConnect(session, host, parts.nPort, 0) : nullptr;
+ const DWORD flags = parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0;
+ HINTERNET request = connection
+ ? WinHttpOpenRequest(connection, widen(req.method.empty() ? "GET" : req.method).c_str(),
+ path, nullptr, WINHTTP_NO_REFERER,
+ WINHTTP_DEFAULT_ACCEPT_TYPES, flags)
+ : nullptr;
+ if (!request) {
+ result.error = "connection failed";
+ if (connection) WinHttpCloseHandle(connection);
+ if (session) WinHttpCloseHandle(session);
+ deliverFetch(std::move(result));
+ return;
+ }
+
+ for (const auto& [name, value] : req.headers) {
+ const std::wstring header = widen(name + ": " + value);
+ WinHttpAddRequestHeaders(request, header.c_str(), (DWORD)header.size(),
+ WINHTTP_ADDREQ_FLAG_ADD);
+ }
+
+ const bool sent = WinHttpSendRequest(
+ request, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
+ req.body.empty() ? WINHTTP_NO_REQUEST_DATA : (LPVOID)req.body.data(),
+ (DWORD)req.body.size(), (DWORD)req.body.size(), 0) != FALSE;
+ if (!sent || !WinHttpReceiveResponse(request, nullptr)) {
+ result.error = "request failed";
+ } else {
+ DWORD status = 0, size = sizeof(status);
+ WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX);
+ result.status = (int)status;
+ result.ok = status >= 200 && status < 300;
+
+ DWORD available = 0;
+ while (WinHttpQueryDataAvailable(request, &available) && available > 0) {
+ const size_t at = result.body.size();
+ result.body.resize(at + available);
+ DWORD read = 0;
+ if (!WinHttpReadData(request, result.body.data() + at, available, &read)) break;
+ result.body.resize(at + read);
+ }
+ }
+
+ WinHttpCloseHandle(request);
+ WinHttpCloseHandle(connection);
+ WinHttpCloseHandle(session);
+ deliverFetch(std::move(result));
+ }).detach();
+}
+
+} // namespace eshost
diff --git a/native/host/platform/windows_common.hpp b/native/host/platform/windows_common.hpp
new file mode 100644
index 000000000..471c8faa2
--- /dev/null
+++ b/native/host/platform/windows_common.hpp
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file windows_common.hpp
+ * @brief The two halves of the platform seam SDL does not cover on Windows:
+ * matching a font file (DirectWrite) and performing an HTTP request
+ * (WinHTTP). The Apple sibling is apple_common.hpp.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include <string>
+
+#include "Host.hpp"
+
+namespace eshost {
+
+/** A font file for @p family covering @p codepoint, with @p style's bold/italic
+ * bits applied — implements Platform::loadFont.
+ *
+ * DirectWrite resolves the family and finds a face covering the codepoint: the
+ * CJK fallback, without a hard-coded path. */
+FontFile windowsLoadFont(const std::string& family, esengine::u32 codepoint, int style);
+
+/** Run @p req on a WinHTTP worker thread and hand the reply to deliverFetch —
+ * see Platform::startFetch. TLS is the OS's, which is why this is platform code. */
+void windowsStartFetch(const FetchRequest& req);
+
+} // namespace eshost
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 4930e694d..b6b589d72 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -283,6 +283,17 @@ bool WebGPUDevice::configureSurface(const NativeSurface& window, u32 width, u32
surface_ = wgpuInstanceCreateSurface(instance_, &sd);
break;
}
+ case NativeWindowKind::Win32Hwnd: {
+#if defined(_WIN32)
+ WGPUSurfaceSourceWindowsHWND win32{};
+ win32.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
+ win32.hinstance = window.instance;
+ win32.hwnd = window.handle;
+ sd.nextInChain = &win32.chain;
+ surface_ = wgpuInstanceCreateSurface(instance_, &sd);
+#endif
+ break;
+ }
}
if (!surface_) {
ES_LOG_ERROR("WebGPUDevice::configureSurface(native): surface creation failed");
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index f184eed0d..3f9a064a7 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -190,14 +190,18 @@ public:
bool configureSurface(const char* selector, u32 width, u32 height);
#endif
- /** The kind of native window a non-emscripten (iOS/Android) host draws into. */
- enum class NativeWindowKind { MetalLayer, AndroidWindow };
+ /** The kind of native window a non-emscripten host draws into. */
+ enum class NativeWindowKind { MetalLayer, AndroidWindow, Win32Hwnd };
- /** A `CAMetalLayer*` / `ANativeWindow*` for a native-C++ build; compiled out of
- * the wasm build, where the host injects an already-built surface instead. */
+ /** A `CAMetalLayer*` / `ANativeWindow*` / `HWND` for a native-C++ build;
+ * compiled out of the wasm build, where the host injects an already-built
+ * surface instead. */
struct NativeSurface {
NativeWindowKind kind;
void* handle;
+ /** Win32 only: the `HINSTANCE` the window belongs to, which the surface
+ * descriptor asks for beside the HWND. */
+ void* instance = nullptr;
};
#if !defined(__EMSCRIPTEN__)