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.

refactor(export): unify screen orientation into one project-wide setting

yhha92f64765633
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index e68c28cf9..26e2710eb 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -30,6 +30,7 @@ import { exportWeChat } from './exportWeChat';
import { exportPlayable } from './exportPlayable';
import type { OnExportProgress } from './exportProgress';
import { ESENGINE_EXTERNAL } from './esengineResolve';
+import { orientationCss, orientationOverlayHtml, orientationLockScript, type ScreenOrientation } from './orientationHtml';
export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable';
@@ -89,7 +90,10 @@ export interface ExportGameResult {
errors: string[];
}
-function indexHtml(title: string): string {
+/** The web host page. `orientation` pins the canvas to a screen orientation (rotate-
+ * to-fit overlay + best-effort lock) — set for the mobile-facing web target, omitted
+ * for desktop (the Electron shell sizes its own window). */
+function indexHtml(title: string, orientation?: ScreenOrientation): string {
return `<!doctype html>
<html lang="en">
<head>
@@ -105,10 +109,13 @@ function indexHtml(title: string): string {
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #0e121b; }
#canvas { display: block; width: 100%; height: 100%; touch-action: none; }
+ ${orientation ? orientationCss(orientation) : ''}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
+ ${orientation ? orientationOverlayHtml(orientation) : ''}
+ ${orientation ? orientationLockScript(orientation) : ''}
<script type="module" src="./game.js"></script>
</body>
</html>
@@ -124,7 +131,8 @@ function slugify(title: string): string {
* payload (./app) over a stable, fetch-enabled `game://` scheme and show it in a
* window. Mirrors the editor's estella:// scheme (file:// blocks fetch of sibling
* assets + wasm streaming, which the runtime needs). */
-function desktopMain(title: string): string {
+function desktopMain(title: string, orientation: ScreenOrientation): string {
+ const [winW, winH] = orientation === 'portrait' ? [720, 1280] : [1280, 720];
return `'use strict';
// Generated by Estella exportGame — the desktop shell for this game.
const { app, protocol, BrowserWindow, net } = require('electron');
@@ -151,8 +159,8 @@ protocol.registerSchemesAsPrivileged([
function createWindow() {
const win = new BrowserWindow({
- width: 1280,
- height: 720,
+ width: ${winW},
+ height: ${winH},
backgroundColor: '#0e121b',
title: ${JSON.stringify(title)},
webPreferences: { contextIsolation: true, sandbox: true },
@@ -230,9 +238,9 @@ The installer is written to \`installer/\`. Build each OS's installer on that OS
}
/** Stage the Electron shell around the web payload already built under `<absOut>/app`. */
-async function stageDesktopApp(absOut: string, title: string, appId?: string, productName?: string): Promise<void> {
+async function stageDesktopApp(absOut: string, title: string, orientation: ScreenOrientation, appId?: string, productName?: string): Promise<void> {
const display = productName || title;
- await writeFile(path.join(absOut, 'main.cjs'), desktopMain(display));
+ await writeFile(path.join(absOut, 'main.cjs'), desktopMain(display, orientation));
await writeFile(path.join(absOut, 'package.json'), desktopPackageJson(title, appId, productName));
await writeFile(path.join(absOut, 'README.md'), desktopReadme(display));
}
@@ -276,9 +284,12 @@ export async function exportGame(opts: {
desktopAppId?: string;
/** Desktop product/display name (Project Settings); default the project title. */
desktopProductName?: string;
- /** WeChat appid / orientation (Project Settings → Packaging → WeChat). */
+ /** WeChat appid (Project Settings → Packaging → WeChat). */
wechatAppid?: string;
- wechatOrientation?: 'portrait' | 'landscape';
+ /** Project-wide screen orientation (format.ts resolveOrientation) — consumed by
+ * EVERY target: WeChat game.json, the web/playable rotate hint, the desktop
+ * window's aspect. Default landscape (the engine's 1920×1080 Canvas aspect). */
+ orientation?: ScreenOrientation;
/** Per-phase progress (build log). */
onProgress?: OnExportProgress;
/** Shipping config: minify the bundles, no sourcemap. Default off (dev). */
@@ -291,6 +302,10 @@ export async function exportGame(opts: {
}): Promise<ExportGameResult> {
const platform = opts.platform ?? 'web';
const title = opts.title ?? 'Game';
+ // One orientation for every target; default landscape (the engine's 1920×1080 Canvas
+ // aspect) so a caller that omits it still ships consistently. The IPC handler resolves
+ // it from the manifest (explicit setting, else the design resolution's aspect).
+ const orientation: ScreenOrientation = opts.orientation ?? 'landscape';
const progress = opts.onProgress ?? (() => {});
const scenes = await discoverProjectScenes(opts.root, opts.entryScene, opts.scenesDir, opts.excludeScenes);
@@ -306,7 +321,7 @@ export async function exportGame(opts: {
outDir: opts.outDir,
title,
appid: opts.wechatAppid,
- orientation: opts.wechatOrientation,
+ orientation,
ySortLayers: opts.ySortLayers,
colorSpace: opts.colorSpace,
minify: opts.minify,
@@ -330,6 +345,7 @@ export async function exportGame(opts: {
wasmDir: opts.wasmDir,
outDir: opts.outDir,
title,
+ orientation,
minify: opts.minify,
ySortLayers: opts.ySortLayers,
colorSpace: opts.colorSpace,
@@ -392,9 +408,10 @@ export async function exportGame(opts: {
if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(payloadDir, 'wasm'), { recursive: true });
else errors.push(`wasm runtime dir not found: ${opts.wasmDir}`);
- // 5. Host page + entry-scene config.
+ // 5. Host page + entry-scene config. Web pins orientation (rotate-to-fit overlay);
+ // desktop omits it — the Electron shell sizes its own window to the orientation.
progress({ phase: 'Writing host page' });
- await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title));
+ await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, platform === 'web' ? orientation : undefined));
await writeFile(
path.join(payloadDir, 'game.config.json'),
JSON.stringify(
@@ -408,7 +425,7 @@ export async function exportGame(opts: {
);
// 6. Desktop: wrap the payload in a runnable Electron app.
- if (platform === 'desktop') { progress({ phase: 'Staging Electron app' }); await stageDesktopApp(absOut, title, opts.desktopAppId, opts.desktopProductName); }
+ if (platform === 'desktop') { progress({ phase: 'Staging Electron app' }); await stageDesktopApp(absOut, title, orientation, opts.desktopAppId, opts.desktopProductName); }
return { ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length, warnings, errors };
}
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index a122a23d6..fc112708a 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -21,6 +21,7 @@ import path from 'node:path';
import { cookAssets } from './cookAssets';
import type { OnExportProgress } from './exportProgress';
import { esengineAlias } from './esengineResolve';
+import { orientationCss, orientationOverlayHtml, orientationLockScript, type ScreenOrientation } from './orientationHtml';
import {
sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,
spineModuleId, SIDE_MODULE_FILE, type SpineVersion,
@@ -53,7 +54,7 @@ const mimeOf = (p: string): string => MIME[path.extname(p).slice(1).toLowerCase(
/** Escape `</script` so inlined content can't close the host <script> early. */
const inlineSafe = (s: string): string => s.replace(/<\/script/gi, '<\\/script');
-function indexHtml(title: string, globals: string, bundle: string): string {
+function indexHtml(title: string, globals: string, bundle: string, orientation: ScreenOrientation): string {
return `<!doctype html>
<html lang="en">
<head>
@@ -64,10 +65,13 @@ function indexHtml(title: string, globals: string, bundle: string): string {
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #0e121b; }
#canvas { display: block; width: 100%; height: 100%; touch-action: none; }
+ ${orientationCss(orientation)}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
+ ${orientationOverlayHtml(orientation)}
+ ${orientationLockScript(orientation)}
<script>${inlineSafe(globals)}</script>
<script>${inlineSafe(bundle)}</script>
</body>
@@ -143,6 +147,9 @@ export async function exportPlayable(opts: {
wasmDir: string;
outDir: string;
title?: string;
+ /** Screen orientation (format.ts resolveOrientation) → rotate-to-fit overlay +
+ * best-effort lock in the single-file HTML. Default landscape. */
+ orientation?: ScreenOrientation;
minify?: boolean;
/** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
ySortLayers?: number;
@@ -151,6 +158,7 @@ export async function exportPlayable(opts: {
onProgress?: OnExportProgress;
}): Promise<ExportPlayableResult> {
const title = opts.title ?? 'Game';
+ const orientation: ScreenOrientation = opts.orientation ?? 'landscape';
const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(opts.root, opts.outDir);
const progress = opts.onProgress ?? (() => {});
const warnings: string[] = [];
@@ -265,7 +273,7 @@ export async function exportPlayable(opts: {
`window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};` +
`window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};`;
const outFile = path.join(absOut, 'index.html');
- await writeFile(outFile, indexHtml(title, globals, bundle));
+ await writeFile(outFile, indexHtml(title, globals, bundle, orientation));
await rm(cookDir, { recursive: true, force: true });
const bytes = (await stat(outFile)).size;
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index f5f1a5b43..04acea9d8 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -35,7 +35,7 @@ import { ensureSdkTypes } from './syncSdkTypes';
import { installCrashCapture, logsDir } from './resilience';
import { mcpMode, startMcpEndpoint } from './mcpEndpoint';
import { checkForUpdate } from './updateCheck';
-import { resolveLayout, resolveScripts } from '../src/project/format';
+import { resolveLayout, resolveScripts, resolveOrientation } from '../src/project/format';
import type { WorkspaceState } from '../src/project/format';
// Enable WebGPU in the renderer so the viewport's WebGPU backend (Settings →
@@ -641,7 +641,9 @@ ipcMain.handle(
desktopAppId: plat?.desktop?.appId,
desktopProductName: plat?.desktop?.productName,
wechatAppid: plat?.wechat?.appid,
- wechatOrientation: plat?.wechat?.orientation,
+ // One project-wide orientation for every target: the explicit packaging
+ // setting, else derived from the design resolution's aspect.
+ orientation: resolveOrientation(manifest),
minify: opts?.minify,
sourcemap: opts?.sourcemap,
compressTextures: opts?.compressTextures,
diff --git a/desktop/electron/orientationHtml.ts b/desktop/electron/orientationHtml.ts
new file mode 100644
index 000000000..3f93f202f
--- /dev/null
+++ b/desktop/electron/orientationHtml.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file orientationHtml.ts — the shared web/playable orientation pin. Both the web
+ * export (exportGame) and the single-file playable export (exportPlayable)
+ * ship the SAME rotate-to-fit behavior for the ONE project-wide orientation
+ * (format.ts resolveOrientation): in the wrong device orientation the canvas
+ * is hidden and a "rotate your device" overlay shows; screen.orientation.lock()
+ * is attempted best-effort (it only takes in fullscreen / on some browsers, so
+ * the CSS overlay is the universal fallback). WeChat handles orientation itself
+ * via game.json deviceOrientation, and desktop sizes its window instead — this
+ * is only the browser surfaces.
+ */
+export type ScreenOrientation = 'portrait' | 'landscape';
+
+/** CSS pinning the canvas to `orientation`: the `#rotate-hint` overlay replaces the
+ * canvas whenever the device is turned the wrong way. */
+export function orientationCss(orientation: ScreenOrientation): string {
+ const wrong = orientation === 'landscape' ? 'portrait' : 'landscape';
+ return (
+ '#rotate-hint{display:none;position:fixed;inset:0;z-index:10;flex-direction:column;' +
+ 'align-items:center;justify-content:center;gap:16px;background:#0e121b;color:#c7d0e0;' +
+ "font:600 15px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;text-align:center;padding:24px;}" +
+ '#rotate-hint .rotate-glyph{font-size:44px;animation:rotate-nudge 1.8s ease-in-out infinite;}' +
+ '@keyframes rotate-nudge{0%,55%{transform:rotate(0)}75%,100%{transform:rotate(-90deg)}}' +
+ `@media (orientation:${wrong}){#canvas{display:none!important;}#rotate-hint{display:flex;}}`
+ );
+}
+
+/** The overlay markup shown in the wrong orientation — sits alongside the canvas. */
+export function orientationOverlayHtml(orientation: ScreenOrientation): string {
+ return `<div id="rotate-hint" role="alert"><div class="rotate-glyph">📱</div><p>Rotate your device to ${orientation}</p></div>`;
+}
+
+/** Best-effort orientation lock. Silently ignored where unsupported (the CSS overlay
+ * covers those cases); a raw <script> so both the web and inlined-playable pages use it. */
+export function orientationLockScript(orientation: ScreenOrientation): string {
+ return `<script>try{var o=screen.orientation;o&&o.lock&&o.lock(${JSON.stringify(orientation)}).catch(function(){});}catch(e){}</script>`;
+}
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index e3e97b80a..eba919e96 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -55,7 +55,6 @@ export const settingsMessages = defineMessages({
'set.group.solver': { en: 'Solver', zh: '求解器' },
'set.group.wechat': { en: 'WeChat', zh: '微信' },
'set.group.desktop': { en: 'Desktop', zh: '桌面' },
- 'set.group.playable': { en: 'Playable', zh: 'Playable' },
// — Editor settings —
'set.appearance.language': { en: 'Language', zh: '语言' },
@@ -104,6 +103,11 @@ export const settingsMessages = defineMessages({
zh: '新建 Canvas 实体使用的参考分辨率;创建后每个 Canvas 保留自己的值。',
},
'set.project.display.height': { en: 'Height', zh: '高度' },
+ 'set.project.display.orientation': { en: 'Orientation', zh: '屏幕方向' },
+ 'set.project.display.orientation.desc': {
+ en: 'Screen orientation for every export target (WeChat, playable, web, desktop). Defaults to the design resolution’s aspect — override to lock a specific orientation.',
+ zh: '所有导出目标(微信、Playable、Web、桌面)的屏幕方向。默认取设计分辨率的宽高比 — 可覆盖以锁定特定方向。',
+ },
'set.project.rendering.sortingLayers': { en: 'Layer names', zh: '层名称' },
'set.project.rendering.sortingLayers.desc': {
en: 'Name render sorting layers (lowest first); a render `layer` field then picks from them instead of a raw number.',
@@ -182,7 +186,6 @@ export const settingsMessages = defineMessages({
en: 'Your WeChat MiniGame appid — written into project.config.json on export.',
zh: '微信小游戏的 appid——导出时写入 project.config.json。',
},
- 'set.project.packaging.orientation': { en: 'Orientation', zh: '屏幕方向' },
'set.orientation.portrait': { en: 'Portrait', zh: '竖屏' },
'set.orientation.landscape': { en: 'Landscape', zh: '横屏' },
'set.project.packaging.desktop.appId': { en: 'App ID', zh: 'App ID' },
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index f8af71f93..b57459ab8 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -25,7 +25,8 @@ import { confirmDiscard } from './discardGuard';
import { t } from '@/i18n';
import { assetTypeOf } from '@/project/assetMeta';
import type { AssetType } from '@/types';
-import { resolveLayout, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution } from './format';
+import { resolveLayout, orientationFromDesignResolution, resolveOrientation, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation } from './format';
+import { useEditorMode } from '@/store/editorModeStore';
/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
function normalizeLayers(layers?: string[]): string[] {
@@ -330,6 +331,9 @@ class ProjectStoreImpl {
currentScene: null,
},
});
+ // Seed the device-preview orientation from the project so the editor opens
+ // matching the shipped orientation; the viewport toggle can still override it.
+ useEditorMode.setState({ orientation: resolveOrientation(opened.manifest) });
}
/** Load the project's last-opened scene (or `<scenes>/main.esscene`) into the world. */
@@ -1221,7 +1225,14 @@ class ProjectStoreImpl {
}
}
- /** Per-platform packaging config (appid / app id / orientation), or {}. */
+ /** The project's effective screen orientation — the explicit packaging setting, else
+ * derived from the design resolution's aspect. Drives the export targets and the
+ * editor's device preview; the segmented control reflects this resolved value. */
+ resolvedOrientation(): ScreenOrientation {
+ return this.state?.packaging?.orientation ?? orientationFromDesignResolution(this.designResolution());
+ }
+
+ /** Per-platform packaging config (appid / app id), or {}. */
platformPackaging(): NonNullable<ProjectPackaging['platforms']> {
return this.state?.packaging?.platforms ?? {};
}
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index e9ac5ce1e..49c9d4ec0 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -98,10 +98,11 @@ export interface ProjectFeatures {
}
export type ScreenOrientation = 'portrait' | 'landscape';
-/** Per-platform packaging config (the platform-specific Project Settings pages). */
-export interface WeChatPackaging { appid?: string; orientation?: ScreenOrientation; }
+/** Per-platform packaging config (the platform-specific Project Settings pages).
+ * Orientation is NOT here — it is one project-wide {@link ProjectPackaging.orientation}
+ * consumed by every target (a landscape build is landscape everywhere). */
+export interface WeChatPackaging { appid?: string; }
export interface DesktopPackaging { appId?: string; productName?: string; }
-export interface PlayablePackaging { orientation?: ScreenOrientation; }
/** Persisted Package Project settings (UE's ProjectPackagingSettings analog) —
* committed with the project so the build dialog restores the last target/config
@@ -111,6 +112,11 @@ export interface ProjectPackaging {
config?: 'development' | 'shipping';
sourceMaps?: boolean;
openFolder?: boolean;
+ /** Screen orientation for EVERY export target (WeChat game.json deviceOrientation,
+ * the web/playable rotate-to-fit hint, the desktop window's aspect). Absent ⇒
+ * derived from the design resolution's aspect (see {@link resolveOrientation}) —
+ * so a landscape design ships landscape with zero config. */
+ orientation?: ScreenOrientation;
/** Cook PNGs to GPU-ready KTX2 (Basis Universal). */
compressTextures?: boolean;
/** Cook WAV sources to MP3 (per-asset Import Settings can override). */
@@ -123,8 +129,8 @@ export interface ProjectPackaging {
excludeScenes?: string[];
/** Per-platform output-dir overrides (else the per-platform default). */
outDir?: Partial<Record<'web' | 'desktop' | 'wechat' | 'playable', string>>;
- /** Per-platform packaging config (appid, app id, orientation, …). */
- platforms?: { wechat?: WeChatPackaging; desktop?: DesktopPackaging; playable?: PlayablePackaging };
+ /** Per-platform packaging config (appid, app id, …). */
+ platforms?: { wechat?: WeChatPackaging; desktop?: DesktopPackaging };
}
/** Committed project identity + config (`project.esproject`). */
@@ -306,6 +312,12 @@ export function parseManifest(raw: unknown): ProjectManifest {
if (p.config === 'development' || p.config === 'shipping') pkg.config = p.config;
if (typeof p.sourceMaps === 'boolean') pkg.sourceMaps = p.sourceMaps;
if (typeof p.openFolder === 'boolean') pkg.openFolder = p.openFolder;
+ // Project-wide orientation. `orientation` is authoritative; a project written by
+ // an older editor carried it per-platform (packaging.platforms.{wechat|playable}
+ // .orientation) — hoist the first legacy value found (below) as a migration, then
+ // it re-persists at the top level on the next write.
+ let orientation: ScreenOrientation | undefined =
+ p.orientation === 'portrait' || p.orientation === 'landscape' ? p.orientation : undefined;
if (Array.isArray(p.excludeScenes)) {
const ex = p.excludeScenes.filter((s): s is string => typeof s === 'string' && s !== '');
if (ex.length > 0) pkg.excludeScenes = ex;
@@ -325,7 +337,8 @@ export function parseManifest(raw: unknown): ProjectManifest {
if (wx && typeof wx === 'object') {
const w: WeChatPackaging = {};
if (typeof wx.appid === 'string') w.appid = wx.appid;
- if (wx.orientation === 'portrait' || wx.orientation === 'landscape') w.orientation = wx.orientation;
+ // Legacy per-platform orientation → the project-wide field (WeChat first).
+ if (!orientation && (wx.orientation === 'portrait' || wx.orientation === 'landscape')) orientation = wx.orientation;
if (Object.keys(w).length > 0) platforms.wechat = w;
}
const dt = pl.desktop as Record<string, unknown> | undefined;
@@ -335,14 +348,15 @@ export function parseManifest(raw: unknown): ProjectManifest {
if (typeof dt.productName === 'string') d.productName = dt.productName;
if (Object.keys(d).length > 0) platforms.desktop = d;
}
+ // Legacy playable.orientation (its only field) also migrates; the platform
+ // block itself is gone (playable has no per-platform config anymore).
const pa = pl.playable as Record<string, unknown> | undefined;
- if (pa && typeof pa === 'object') {
- const a: PlayablePackaging = {};
- if (pa.orientation === 'portrait' || pa.orientation === 'landscape') a.orientation = pa.orientation;
- if (Object.keys(a).length > 0) platforms.playable = a;
+ if (!orientation && pa && typeof pa === 'object' && (pa.orientation === 'portrait' || pa.orientation === 'landscape')) {
+ orientation = pa.orientation;
}
if (Object.keys(platforms).length > 0) pkg.platforms = platforms;
}
+ if (orientation) pkg.orientation = orientation;
if (Object.keys(pkg).length > 0) manifest.packaging = pkg;
}
return manifest;
@@ -353,6 +367,21 @@ export function resolveLayout(manifest: Pick<ProjectManifest, 'layout'>): Projec
return { ...DEFAULT_LAYOUT, ...(manifest.layout ?? {}) };
}
+/** The orientation a design resolution implies: landscape when at least as wide as
+ * tall (matches the engine's 1920×1080 Canvas default), portrait otherwise. */
+export function orientationFromDesignResolution(dr?: DesignResolution): ScreenOrientation {
+ const width = dr?.width ?? 1920;
+ const height = dr?.height ?? 1080;
+ return width >= height ? 'landscape' : 'portrait';
+}
+
+/** Effective screen orientation for every export target: the explicit project
+ * setting when set, else derived from the design resolution's aspect. One value,
+ * read by WeChat/playable/web/desktop alike — the single source of truth. */
+export function resolveOrientation(manifest: Pick<ProjectManifest, 'packaging' | 'designResolution'>): ScreenOrientation {
+ return manifest.packaging?.orientation ?? orientationFromDesignResolution(manifest.designResolution);
+}
+
/** Default script entries — the convention most projects follow without config. */
export const DEFAULT_SCRIPTS: Required<ProjectScripts> = {
register: 'src/components.ts',
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index d74d96163..2e5382808 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -11,9 +11,16 @@ import { settingsRegistry } from './registry';
import { ProjectStore } from '@/project/ProjectStore';
import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
+import { useEditorMode } from '@/store/editorModeStore';
+import type { ScreenOrientation } from '@/project/format';
import { t } from '@/i18n';
-// ── Display (design/reference resolution; seeds new Canvas entities) ──
+const ORIENTATION = [
+ { value: 'portrait', label: t('set.orientation.portrait') },
+ { value: 'landscape', label: t('set.orientation.landscape') },
+];
+
+// ── Display (design/reference resolution + orientation; screen shape) ──
settingsRegistry.registerSection({ id: 'display', label: t('set.section.display'), category: 'project', order: 0 });
settingsRegistry.register({
@@ -39,6 +46,26 @@ settingsRegistry.register({
},
});
+// Project-wide screen orientation — one value every export target reads (WeChat
+// game.json, the web/playable rotate hint, the desktop window aspect). Shown as the
+// resolved value (explicit, else derived from the design resolution's aspect); the
+// segmented control's default is only the fallback before a project loads.
+settingsRegistry.register({
+ id: 'project.display.orientation',
+ type: 'enum', scope: 'project', section: 'display', group: t('set.group.designResolution'),
+ label: t('set.project.display.orientation'),
+ description: t('set.project.display.orientation.desc'),
+ options: ORIENTATION, segmented: true, default: 'landscape',
+ bind: {
+ get: () => ProjectStore.resolvedOrientation(),
+ set: (v) => {
+ void ProjectStore.setPackaging({ orientation: v as ScreenOrientation });
+ // Keep the editor's device preview in lockstep with the shipped orientation.
+ useEditorMode.setState({ orientation: v as ScreenOrientation });
+ },
+ },
+});
+
// ── Physics (the enable flag = UE Plugins-Browser analog; gravity = Project Settings) ──
settingsRegistry.registerSection({ id: 'physics', label: t('set.section.physics'), category: 'project', order: 1 });
@@ -175,11 +202,6 @@ settingsRegistry.register({
// ── Packaging (per-platform Project Settings; read by the export, persisted to project.esproject) ──
settingsRegistry.registerSection({ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 3 });
-const ORIENTATION = [
- { value: 'portrait', label: t('set.orientation.portrait') },
- { value: 'landscape', label: t('set.orientation.landscape') },
-];
-
settingsRegistry.register({
id: 'project.packaging.wechat.appid',
type: 'string', scope: 'project', section: 'packaging', group: t('set.group.wechat'),
@@ -192,16 +214,6 @@ settingsRegistry.register({
},
});
-settingsRegistry.register({
- id: 'project.packaging.wechat.orientation',
- type: 'enum', scope: 'project', section: 'packaging', group: t('set.group.wechat'),
- label: t('set.project.packaging.orientation'), options: ORIENTATION, segmented: true, default: 'portrait',
- bind: {
- get: () => ProjectStore.platformPackaging().wechat?.orientation ?? 'portrait',
- set: (v) => void ProjectStore.setPlatformPackaging('wechat', { orientation: v as 'portrait' | 'landscape' }),
- },
-});
-
settingsRegistry.register({
id: 'project.packaging.desktop.appId',
type: 'string', scope: 'project', section: 'packaging', group: t('set.group.desktop'),
@@ -226,16 +238,6 @@ settingsRegistry.register({
},
});
-settingsRegistry.register({
- id: 'project.packaging.playable.orientation',
- type: 'enum', scope: 'project', section: 'packaging', group: t('set.group.playable'),
- label: t('set.project.packaging.orientation'), options: ORIENTATION, segmented: true, default: 'portrait',
- bind: {
- get: () => ProjectStore.platformPackaging().playable?.orientation ?? 'portrait',
- set: (v) => void ProjectStore.setPlatformPackaging('playable', { orientation: v as 'portrait' | 'landscape' }),
- },
-});
-
settingsRegistry.register({
id: 'project.physics.gravityY',
type: 'number',
diff --git a/desktop/tests/export-desktop.test.ts b/desktop/tests/export-desktop.test.ts
index 1e68c7615..4f2d2a4cf 100644
--- a/desktop/tests/export-desktop.test.ts
+++ b/desktop/tests/export-desktop.test.ts
@@ -82,6 +82,11 @@ describe('exportGame (desktop)', () => {
expect(main).toContain('registerSchemesAsPrivileged');
expect(main).toContain("SCHEME = 'game'");
expect(main).toContain('://app/index.html'); // window loads the payload over the scheme
+ // Default landscape ⇒ 1280×720 window; the desktop page carries NO rotate overlay
+ // (a resizable desktop window isn't a phone — orientation is the window aspect).
+ expect(main).toContain('width: 1280');
+ expect(main).toContain('height: 720');
+ expect(readFileSync(path.join(app, 'index.html'), 'utf8')).not.toContain('rotate-hint');
const pkg = JSON.parse(readFileSync(path.join(out, 'package.json'), 'utf8'));
expect(pkg.main).toBe('main.cjs');
@@ -113,4 +118,17 @@ describe('exportGame (desktop)', () => {
expect(existsSync(path.join(webOut, 'app'))).toBe(false);
expect(existsSync(path.join(webOut, 'main.cjs'))).toBe(false);
}, 60_000);
+
+ it('sizes the desktop window to a portrait orientation', async () => {
+ const pOut = path.join(root, 'dist-desktop-portrait');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: pOut, title: 'Portrait Game', platform: 'desktop', orientation: 'portrait',
+ });
+ expect(res.ok).toBe(true);
+ const main = readFileSync(path.join(pOut, 'main.cjs'), 'utf8');
+ expect(main).toContain('width: 720');
+ expect(main).toContain('height: 1280');
+ }, 60_000);
});
diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.ts
index 05ca039e3..ffcbf455c 100644
--- a/desktop/tests/export-game.test.ts
+++ b/desktop/tests/export-game.test.ts
@@ -97,6 +97,10 @@ describe('exportGame', () => {
expect(html).toContain('importmap');
expect(html).toContain('./sdk/index.js');
expect(html).toContain('./game.js');
+ // Web pins orientation (default landscape ⇒ rotate-to-fit overlay + best-effort lock).
+ expect(html).toContain('id="rotate-hint"');
+ expect(html).toContain('Rotate your device to landscape');
+ expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
}, 60_000);
diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.ts
index 3e5def9d7..4b136d0ac 100644
--- a/desktop/tests/export-playable.test.ts
+++ b/desktop/tests/export-playable.test.ts
@@ -92,6 +92,26 @@ describe('exportGame (playable)', () => {
expect(html).toContain('"main"'); // first scene name
expect(html).toContain('__GAME_SCENES__');
expect(html).toContain('<title>Playable Demo</title>');
+ // Orientation pin: no explicit setting ⇒ landscape default (rotate-to-fit + lock).
+ expect(html).toContain('id="rotate-hint"');
+ expect(html).toContain('Rotate your device to landscape');
+ expect(html).toContain('@media (orientation:portrait)'); // hide canvas when wrong way
+ expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
+ }, 60_000);
+
+ it('pins the single file to an explicit portrait orientation', async () => {
+ const o = path.join(root, 'dist-playable-portrait');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, title: 'Playable Demo', platform: 'playable', orientation: 'portrait',
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('Rotate your device to portrait');
+ expect(html).toContain('@media (orientation:landscape)'); // hide canvas when wrong way
+ expect(html).toMatch(/screen\.orientation[\s\S]*lock\("portrait"\)/);
}, 60_000);
});
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index aef658a5b..63af7f3e0 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -65,7 +65,7 @@ describe('exportGame (wechat)', () => {
title: 'My Game',
platform: 'wechat',
wechatAppid: 'wxTEST0123456789',
- wechatOrientation: 'landscape',
+ orientation: 'landscape',
});
expect(res.ok).toBe(true);
diff --git a/desktop/tests/project-packaging.test.ts b/desktop/tests/project-packaging.test.ts
index 5397108fc..da74c473b 100644
--- a/desktop/tests/project-packaging.test.ts
+++ b/desktop/tests/project-packaging.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { parseManifest } from '../src/project/format';
+import { parseManifest, resolveOrientation, orientationFromDesignResolution } from '../src/project/format';
describe('parseManifest — packaging', () => {
it('parses a valid packaging section', () => {
@@ -45,21 +45,75 @@ describe('parseManifest — packaging', () => {
name: 'X',
packaging: {
platforms: {
- wechat: { appid: 'wx123', orientation: 'landscape', junk: 1 },
+ wechat: { appid: 'wx123', junk: 1 },
desktop: { appId: 'com.x.y', productName: 'Y', extra: 'z' },
- playable: { orientation: 'portrait' },
},
},
});
expect(m.packaging?.platforms).toEqual({
- wechat: { appid: 'wx123', orientation: 'landscape' },
+ wechat: { appid: 'wx123' },
desktop: { appId: 'com.x.y', productName: 'Y' },
- playable: { orientation: 'portrait' },
});
});
+});
+
+describe('parseManifest — orientation (unified, project-wide)', () => {
+ it('parses a top-level orientation', () => {
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'landscape' } }).packaging?.orientation).toBe('landscape');
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'portrait' } }).packaging?.orientation).toBe('portrait');
+ });
+
+ it('drops an invalid top-level orientation', () => {
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'diagonal' } }).packaging).toBeUndefined();
+ });
+
+ it('migrates a legacy wechat.orientation to the top level, dropping the per-platform field', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { wechat: { appid: 'wx1', orientation: 'landscape' } } },
+ });
+ expect(m.packaging?.orientation).toBe('landscape');
+ expect(m.packaging?.platforms).toEqual({ wechat: { appid: 'wx1' } }); // orientation hoisted out
+ });
+
+ it('migrates a legacy playable.orientation and drops the (now-empty) playable block', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { playable: { orientation: 'portrait' } } },
+ });
+ expect(m.packaging?.orientation).toBe('portrait');
+ expect(m.packaging?.platforms).toBeUndefined(); // playable had only orientation → gone
+ });
+
+ it('prefers an explicit top-level orientation over a legacy per-platform one', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { orientation: 'portrait', platforms: { wechat: { orientation: 'landscape' } } },
+ });
+ expect(m.packaging?.orientation).toBe('portrait');
+ });
+
+ it('prefers wechat over playable when both legacy fields are present', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { wechat: { orientation: 'landscape' }, playable: { orientation: 'portrait' } } },
+ });
+ expect(m.packaging?.orientation).toBe('landscape');
+ });
+});
+
+describe('resolveOrientation / orientationFromDesignResolution', () => {
+ it('derives orientation from the design resolution aspect', () => {
+ expect(orientationFromDesignResolution({ width: 1920, height: 1080 })).toBe('landscape');
+ expect(orientationFromDesignResolution({ width: 1080, height: 1920 })).toBe('portrait');
+ expect(orientationFromDesignResolution({ width: 800, height: 800 })).toBe('landscape'); // square ⇒ landscape
+ expect(orientationFromDesignResolution(undefined)).toBe('landscape'); // engine default 1920×1080
+ });
- it('drops invalid orientation + empty platform objects', () => {
- const m = parseManifest({ name: 'X', packaging: { platforms: { wechat: { orientation: 'diagonal' }, desktop: {} } } });
- expect(m.packaging).toBeUndefined(); // nothing valid survives
+ it('resolves the explicit setting first, else derives from the design resolution', () => {
+ expect(resolveOrientation({ packaging: { orientation: 'portrait' }, designResolution: { width: 1920, height: 1080 } })).toBe('portrait');
+ expect(resolveOrientation({ designResolution: { width: 1080, height: 1920 } })).toBe('portrait');
+ expect(resolveOrientation({ designResolution: { width: 1280, height: 720 } })).toBe('landscape');
+ expect(resolveOrientation({})).toBe('landscape'); // no packaging, no design res
});
});
diff --git a/docs/astro/src/content/docs/guides/build-export.mdx b/docs/astro/src/content/docs/guides/build-export.mdx
index 75c2aa261..75cd7ecc8 100644
--- a/docs/astro/src/content/docs/guides/build-export.mdx
+++ b/docs/astro/src/content/docs/guides/build-export.mdx
@@ -116,9 +116,18 @@ The Package dialog also drives what the **cook** does to your assets:
Per-target metadata lives in **Project Settings → Packaging** and is saved with the
project:
-- **WeChat** — AppID and screen orientation.
+- **WeChat** — AppID.
- **Desktop** — application id and product name (used to name the installer).
-- **Playable** — orientation.
+
+### Screen orientation
+
+Orientation is **one project-wide setting**, not per-target: **Project Settings →
+Display → Orientation** (portrait or landscape), right beside the design resolution.
+Every target honors it — the WeChat `game.json` `deviceOrientation`, the web and
+playable builds' rotate-to-fit prompt (and a best-effort `screen.orientation.lock`),
+and the desktop window's aspect. Left unset, it's **derived from the design
+resolution's aspect** (wider-or-square ⇒ landscape, taller ⇒ portrait), so a
+landscape design ships landscape everywhere with zero configuration.
See [The Editor](/docs/guides/editor/) for the settings UI.
diff --git a/docs/astro/src/content/docs/guides/editor.mdx b/docs/astro/src/content/docs/guides/editor.mdx
index a9106b8f4..84df43c3b 100644
--- a/docs/astro/src/content/docs/guides/editor.mdx
+++ b/docs/astro/src/content/docs/guides/editor.mdx
@@ -225,11 +225,14 @@ Open settings with **Ctrl / ⌘ + ,** or the Activity Bar's gear. Settings are g
snapping, gizmos), **Keyboard Shortcuts** (every shortcut below is rebindable
here), and Console.
- **Project** (saved into `project.esproject`):
+ - **Display** — the design resolution new Canvases seed from, and the project-wide
+ **screen orientation** (every export target honors it; unset ⇒ derived from the
+ design resolution's aspect).
- **Physics** — enable, gravity, sixteen collision-layer names and a 16×16 collision
matrix, plus solver tuning (fixed timestep, sub-steps, contact Hz/damping/push
speed, sleeping, continuous collision). See [Physics](/docs/guides/physics/).
- **Rendering** — named sorting layers that populate the inspector's layer dropdown.
- - **Packaging** — per-platform settings for WeChat, Desktop, and Playable exports.
+ - **Packaging** — per-target metadata: WeChat AppID, Desktop app id / product name.
### Editor language
diff --git a/docs/astro/src/content/docs/guides/wechat.mdx b/docs/astro/src/content/docs/guides/wechat.mdx
index d71ba6805..7b0cb46af 100644
--- a/docs/astro/src/content/docs/guides/wechat.mdx
+++ b/docs/astro/src/content/docs/guides/wechat.mdx
@@ -34,7 +34,9 @@ node build-tools/cli.js build -t videodec-wechat # video (MPEG-1 wasm decoder)
<Steps>
-1. In **Project Settings → Packaging → WeChat**, set your AppID and orientation.
+1. In **Project Settings → Packaging → WeChat**, set your AppID. Screen orientation
+ is project-wide — set it once in **Project Settings → Display → Orientation** (it
+ drives the `game.json` `deviceOrientation` below).
2. Open **File → Build…**, pick the **WeChat** platform in the Package Project
dialog, review the **Scenes in build** list, and click **Package**. Estella
diff --git a/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx b/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
index ce0accf0b..15128a6bc 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
@@ -98,9 +98,12 @@ node build-tools/cli.js build -t playable
每个目标的元数据在 **项目设置 → 打包(Packaging)** 里,并随项目保存:
-- **微信** —— AppID 和屏幕朝向。
+- **微信** —— AppID。
- **桌面** —— 应用 id 和产品名(用于命名安装包)。
-- **Playable** —— 朝向。
+
+### 屏幕方向
+
+方向是**一个项目级设置**,而非逐平台:**项目设置 → 显示(Display) → 屏幕方向**(竖屏或横屏),就在设计分辨率旁边。所有目标都遵循它——微信 `game.json` 的 `deviceOrientation`、Web 与 Playable 构建的"请旋转设备"提示(以及尽力而为的 `screen.orientation.lock`)、桌面窗口的宽高比。留空则**从设计分辨率的宽高比推导**(更宽或方形 ⇒ 横屏,更高 ⇒ 竖屏),因此横屏设计零配置即在各处横屏发布。
设置界面见 [编辑器](/docs/zh-cn/guides/editor/)。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/editor.mdx b/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
index a116b9765..72ac4a6ab 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
@@ -186,10 +186,12 @@ Details 是选中项的检视器。它列出实体上的每个组件及其字段
- **编辑器** — 外观(**语言**、强调色、UI 缩放)、视口(网格、吸附、gizmo)、**键盘快捷键**(下面每个快捷键
都能在这里重绑)、控制台。
- **项目**(存进 `project.esproject`):
+ - **显示** — 新建 Canvas 播种用的设计分辨率,以及项目级的**屏幕方向**(所有导出目标都遵循它;
+ 留空则从设计分辨率的宽高比推导)。
- **物理** — 启用、重力、十六个碰撞层名字和一个 16×16 碰撞矩阵,以及解算器调参(固定时间步、
子步、接触 Hz/阻尼/推出速度、允许睡眠、连续碰撞)。见 [物理](/docs/zh-cn/guides/physics/)。
- **渲染** — 命名排序层,填充检视器里的层下拉。
- - **打包** — 微信、桌面、Playable 导出的每平台设置。
+ - **打包** — 每目标元数据:微信 AppID、桌面应用 id / 产品名。
### 编辑器语言
diff --git a/docs/astro/src/content/docs/zh-cn/guides/wechat.mdx b/docs/astro/src/content/docs/zh-cn/guides/wechat.mdx
index 36cdb10f1..314eebade 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/wechat.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/wechat.mdx
@@ -31,7 +31,7 @@ node build-tools/cli.js build -t videodec-wechat # 视频(MPEG-1 wasm 解码
<Steps>
-1. 在**项目设置 → 打包 → 微信**中,填写 AppID 与横竖屏方向。
+1. 在**项目设置 → 打包 → 微信**中,填写 AppID。屏幕方向是项目级设置——在**项目设置 → 显示 → 屏幕方向**里设一次即可(它驱动下面 `game.json` 的 `deviceOrientation`)。
2. 打开**文件 → 构建…**,在 Package Project 对话框里选 **WeChat** 平台,
检查**构建场景**列表,点击 **Package**。Estella 会烘焙资源,把 SDK 与你的