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(engine): the device's battery and heat lower the frame cap and the quality level, by a policy the project names

yhh7eb7232e0fb8
diff --git a/desktop b/desktop
index a0e29f128..d2400b4db 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit a0e29f12827d4e7dfafa38cb05eadd72479a0f99
+Subproject commit d2400b4dbe59cc10b284e475c60b2cc60a6b5162
diff --git a/docs/astro/src/content/docs/performance/quality-levels.mdx b/docs/astro/src/content/docs/performance/quality-levels.mdx
index 3fa6802e0..b191aa8d7 100644
--- a/docs/astro/src/content/docs/performance/quality-levels.mdx
+++ b/docs/astro/src/content/docs/performance/quality-levels.mdx
@@ -68,6 +68,26 @@ Shown when the mode is Auto. Each row names a level and the conditions a device
**GPU contains**, **Max RAM** and **Max cores**, all of which must hold. The first row that matches decides the level. A
row with no condition would match every device, so it must have one.
+## Saving power
+
+A long session on a phone is heat and battery, and the frame is where both go. Turn on **Save power when the battery is low or the device is hot** (`QualityConfig.power`) and the engine
+watches the device every few seconds: while it is saving it lowers the frame cap and puts a ceiling on the quality level, and when the device recovers it puts both back. Off (the default), the device
+is not watched and nothing changes.
+
+| Setting | What it does |
+|---|---|
+| **Battery below** (`lowBattery`) | Saves while the battery is under this share and not charging. Default 20%; 0 never saves for the battery. |
+| **Thermal pressure** (`thermal`) | Saves when the platform reports pressure of this level or worse: Serious (default), Critical, or Never. |
+| **Frame cap while saving** (`fps`) | Frames a second while saving. Default 30. A cap the game already set lower is kept. |
+| **Level ceiling while saving** (`ceiling`) | No level above this while saving; a level already under it is left. Default Medium. |
+
+At Critical thermal pressure it goes further: the cap is halved (never under 15) and the level is held at Low (`severe: 'never'` turns that off). What a platform does not report never triggers
+anything: a browser with no battery API saves nothing for the battery, and most browsers report no heat at all (Chromium reports the battery and the processor's pressure; the WeChat mini-game
+platform reports the battery). `Device.power()` gives a game the same numbers (`level`, `charging`, `thermal`, each `null` where the platform does not say), and `Quality`'s report names `power-saver`
+among its limitations while it is holding the level down. The cap is put back only if the game has not changed it itself since.
+
+For a still screen (a menu, a card table) the better saving is to draw nothing: see render-on-demand in the same page of the editor's settings.
+
## In code
The same settings are `QualityConfig` — `QualityController`, `parseQualityConfig`, `resolveQualityProfile` and
diff --git a/docs/astro/src/content/docs/zh-cn/performance/quality-levels.mdx b/docs/astro/src/content/docs/zh-cn/performance/quality-levels.mdx
index b9aeaf94a..72e7a05f7 100644
--- a/docs/astro/src/content/docs/zh-cn/performance/quality-levels.mdx
+++ b/docs/astro/src/content/docs/zh-cn/performance/quality-levels.mdx
@@ -58,6 +58,21 @@ import { Aside } from '@astrojs/starlight/components';
模式为自动时显示。每行写一个档位和设备必须满足的条件:**型号包含**、**GPU 包含**、**内存上限**、**核心上限**,全部成立才算。
第一条匹配的规则决定档位。没有任何条件的规则会匹配所有设备,所以必须至少有一个条件。
+## 省电与降温
+
+手机上玩得久,就是发热和耗电,而这两样都花在画面这一帧上。打开 **电量低或设备发烫时降低开销**(`QualityConfig.power`)后,引擎每隔几秒看一眼设备:处于省电状态时,降低帧率上限并给画质档位设一个上限,设备恢复后再放回。关闭(默认)时不监测设备,什么都不变。
+
+| 设置 | 作用 |
+|---|---|
+| **电量低于**(`lowBattery`) | 电量低于该比例且没在充电时省电。默认 20%;0 表示不因电量省电。 |
+| **发热压力**(`thermal`) | 平台报告压力达到该级别或更高时省电:严重(默认)、危急、不因发热。 |
+| **省电时的帧率上限**(`fps`) | 省电时每秒最多画多少帧,默认 30。游戏已设得更低的上限保持不变。 |
+| **省电时的画质上限**(`ceiling`) | 省电时画质不超过该档;本来更低的档位不动。默认中。 |
+
+发热压力达到危急时更进一步:帧率上限减半(不低于 15),画质固定为低(`severe: 'never'` 可关闭这一步)。平台没报告的项不会触发任何事:没有电池接口的浏览器不会因电量省电,多数浏览器完全不报告温度(Chromium 报告电量和处理器压力;微信小游戏平台报告电量)。`Device.power()` 把同样的数字给游戏(`level`、`charging`、`thermal`,平台没说的为 `null`),`Quality` 的报告在压低档位期间会在限制里列出 `power-saver`。帧率上限只在游戏自己没有改动过它的情况下才放回。
+
+静止的画面(菜单、牌桌)更好的省法是什么都不画:见编辑器同一页设置里的"按需渲染"。
+
## 在代码里
同样的设置就是 `QualityConfig`——`QualityController`、`parseQualityConfig`、`resolveQualityProfile` 和 `defaultQualityProfile`
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 356a15ae1..82debbab7 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2710,
+ "experimental": 2715,
"deprecated": 3
},
- "total": 2996,
+ "total": 3001,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index e3e5354b8..5f5c689de 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1958 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1963 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3185,7 +3185,7 @@ prefab: string
## Device — const @experimental
```
-{ capabilities: () => DeviceCapabilities; state: () => DeviceState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
+{ capabilities: () => DeviceCapabilities; state: () => DeviceState; power: () => PowerState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
```
## DeviceCapabilities — interface @experimental
@@ -7477,6 +7477,35 @@ size: { x: number; y: number; z?: number; }
weight: number
```
+## PowerDecision — interface @experimental
+```
+ceiling: PowerLevel | null
+fps: number
+reason: "none" | "battery" | "thermal" | "critical"
+saving: boolean
+```
+
+## PowerLevel — type @experimental
+```
+'low' | 'medium' | 'high'
+```
+
+## PowerPolicy — interface @experimental
+```
+ceiling: PowerLevel | undefined
+fps: number | undefined
+lowBattery: number | undefined
+severe: "critical" | "never" | undefined
+thermal: "critical" | "serious" | "never" | undefined
+```
+
+## PowerState — interface @experimental
+```
+charging: boolean | null
+level: number | null
+thermal: "critical" | "serious" | "nominal" | "fair" | null
+```
+
## PreSceneDrawCallback — type @experimental
```
(info: PreSceneDrawInfo) => void
@@ -7809,6 +7838,7 @@ asyncShaderCompile: boolean | undefined
deviceRules: DeviceQualityRule[] | undefined
dynamicResolution: boolean | undefined
mode: QualityMode | undefined
+power: PowerPolicy | undefined
prewarmShaders: boolean | undefined
prewarmTimeoutMs: number | undefined
profiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined
@@ -7824,6 +7854,7 @@ profile: Readonly<QualityProfile>
renderScale: number
report: () => QualityReport
sample: (frameMs: number, gpuMs?: number) => void
+setCeiling: (level: QualityLevel | null) => void
setLimitation: (reason: string, active: boolean) => void
setMode: (mode: QualityMode) => void
static new (config: QualityConfig, device_?: DeviceQualityInfo): QualityController
@@ -13922,6 +13953,11 @@ Plugin
(category: string, message: string, data?: unknown): void
```
+## decidePower — function @experimental
+```
+(state: PowerState, policy: PowerPolicy): PowerDecision
+```
+
## decodeImageBitmap — function @experimental
```
(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d68d303ec..64c6d3a91 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1977 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1982 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3193,7 +3193,7 @@ prefab: string
## Device — const @experimental
```
-{ capabilities: () => DeviceCapabilities; state: () => DeviceState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
+{ capabilities: () => DeviceCapabilities; state: () => DeviceState; power: () => PowerState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
```
## DeviceCapabilities — interface @experimental
@@ -7680,6 +7680,35 @@ size: { x: number; y: number; z?: number; }
weight: number
```
+## PowerDecision — interface @experimental
+```
+ceiling: PowerLevel | null
+fps: number
+reason: "none" | "battery" | "thermal" | "critical"
+saving: boolean
+```
+
+## PowerLevel — type @experimental
+```
+'low' | 'medium' | 'high'
+```
+
+## PowerPolicy — interface @experimental
+```
+ceiling: PowerLevel | undefined
+fps: number | undefined
+lowBattery: number | undefined
+severe: "critical" | "never" | undefined
+thermal: "critical" | "serious" | "never" | undefined
+```
+
+## PowerState — interface @experimental
+```
+charging: boolean | null
+level: number | null
+thermal: "critical" | "serious" | "nominal" | "fair" | null
+```
+
## PreSceneDrawCallback — type @experimental
```
(info: PreSceneDrawInfo) => void
@@ -8012,6 +8041,7 @@ asyncShaderCompile: boolean | undefined
deviceRules: DeviceQualityRule[] | undefined
dynamicResolution: boolean | undefined
mode: QualityMode | undefined
+power: PowerPolicy | undefined
prewarmShaders: boolean | undefined
prewarmTimeoutMs: number | undefined
profiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined
@@ -8027,6 +8057,7 @@ profile: Readonly<QualityProfile>
renderScale: number
report: () => QualityReport
sample: (frameMs: number, gpuMs?: number) => void
+setCeiling: (level: QualityLevel | null) => void
setLimitation: (reason: string, active: boolean) => void
setMode: (mode: QualityMode) => void
static new (config: QualityConfig, device_?: DeviceQualityInfo): QualityController
@@ -14175,6 +14206,11 @@ Plugin
(category: string, message: string, data?: unknown): void
```
+## decidePower — function @experimental
+```
+(state: PowerState, policy: PowerPolicy): PowerDecision
+```
+
## decodeImageBitmap — function @experimental
```
(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index b84796d42..488325be3 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1957 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1962 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3180,7 +3180,7 @@ prefab: string
## Device — const @experimental
```
-{ capabilities: () => DeviceCapabilities; state: () => DeviceState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
+{ capabilities: () => DeviceCapabilities; state: () => DeviceState; power: () => PowerState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
```
## DeviceCapabilities — interface @experimental
@@ -7472,6 +7472,35 @@ size: { x: number; y: number; z?: number; }
weight: number
```
+## PowerDecision — interface @experimental
+```
+ceiling: PowerLevel | null
+fps: number
+reason: "none" | "battery" | "thermal" | "critical"
+saving: boolean
+```
+
+## PowerLevel — type @experimental
+```
+'low' | 'medium' | 'high'
+```
+
+## PowerPolicy — interface @experimental
+```
+ceiling: PowerLevel | undefined
+fps: number | undefined
+lowBattery: number | undefined
+severe: "critical" | "never" | undefined
+thermal: "critical" | "serious" | "never" | undefined
+```
+
+## PowerState — interface @experimental
+```
+charging: boolean | null
+level: number | null
+thermal: "critical" | "serious" | "nominal" | "fair" | null
+```
+
## PreSceneDrawCallback — type @experimental
```
(info: PreSceneDrawInfo) => void
@@ -7804,6 +7833,7 @@ asyncShaderCompile: boolean | undefined
deviceRules: DeviceQualityRule[] | undefined
dynamicResolution: boolean | undefined
mode: QualityMode | undefined
+power: PowerPolicy | undefined
prewarmShaders: boolean | undefined
prewarmTimeoutMs: number | undefined
profiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined
@@ -7819,6 +7849,7 @@ profile: Readonly<QualityProfile>
renderScale: number
report: () => QualityReport
sample: (frameMs: number, gpuMs?: number) => void
+setCeiling: (level: QualityLevel | null) => void
setLimitation: (reason: string, active: boolean) => void
setMode: (mode: QualityMode) => void
static new (config: QualityConfig, device_?: DeviceQualityInfo): QualityController
@@ -13917,6 +13948,11 @@ Plugin
(category: string, message: string, data?: unknown): void
```
+## decidePower — function @experimental
+```
+(state: PowerState, policy: PowerPolicy): PowerDecision
+```
+
## decodeImageBitmap — function @experimental
```
(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d7f121fa3..22696d291 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1979 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1984 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3180,7 +3180,7 @@ prefab: string
## Device — const @experimental
```
-{ capabilities: () => DeviceCapabilities; state: () => DeviceState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
+{ capabilities: () => DeviceCapabilities; state: () => DeviceState; power: () => PowerState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
```
## DeviceCapabilities — interface @experimental
@@ -5938,6 +5938,7 @@ createInnerAudioContext: () => MiniGameInnerAudioContext
createInterstitialAd: ((opts: { adUnitId: string; }) => MiniGameInterstitialAd) | undefined
createRewardedVideoAd: ((opts: { adUnitId: string; }) => MiniGameRewardedVideoAd) | undefined
env: { USER_DATA_PATH?: string; } | undefined
+getBatteryInfoSync: (() => { level: number; isCharging: boolean; }) | undefined
getDeviceInfo: (() => MiniGameSystemInfo) | undefined
getFileSystemManager: () => MiniGameFileSystemManager
getGameRecorder: (() => MiniGameWxRecorder) | undefined
@@ -7766,6 +7767,35 @@ size: { x: number; y: number; z?: number; }
weight: number
```
+## PowerDecision — interface @experimental
+```
+ceiling: PowerLevel | null
+fps: number
+reason: "none" | "battery" | "thermal" | "critical"
+saving: boolean
+```
+
+## PowerLevel — type @experimental
+```
+'low' | 'medium' | 'high'
+```
+
+## PowerPolicy — interface @experimental
+```
+ceiling: PowerLevel | undefined
+fps: number | undefined
+lowBattery: number | undefined
+severe: "critical" | "never" | undefined
+thermal: "critical" | "serious" | "never" | undefined
+```
+
+## PowerState — interface @experimental
+```
+charging: boolean | null
+level: number | null
+thermal: "critical" | "serious" | "nominal" | "fair" | null
+```
+
## PreSceneDrawCallback — type @experimental
```
(info: PreSceneDrawInfo) => void
@@ -8098,6 +8128,7 @@ asyncShaderCompile: boolean | undefined
deviceRules: DeviceQualityRule[] | undefined
dynamicResolution: boolean | undefined
mode: QualityMode | undefined
+power: PowerPolicy | undefined
prewarmShaders: boolean | undefined
prewarmTimeoutMs: number | undefined
profiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined
@@ -8113,6 +8144,7 @@ profile: Readonly<QualityProfile>
renderScale: number
report: () => QualityReport
sample: (frameMs: number, gpuMs?: number) => void
+setCeiling: (level: QualityLevel | null) => void
setLimitation: (reason: string, active: boolean) => void
setMode: (mode: QualityMode) => void
static new (config: QualityConfig, device_?: DeviceQualityInfo): QualityController
@@ -14222,6 +14254,11 @@ Plugin
(category: string, message: string, data?: unknown): void
```
+## decidePower — function @experimental
+```
+(state: PowerState, policy: PowerPolicy): PowerDecision
+```
+
## decodeImageBitmap — function @experimental
```
(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b58fe14bc..f129e63af 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1970 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1975 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3180,7 +3180,7 @@ prefab: string
## Device — const @experimental
```
-{ capabilities: () => DeviceCapabilities; state: () => DeviceState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
+{ capabilities: () => DeviceCapabilities; state: () => DeviceState; power: () => PowerState; motion: { start: (options?: MotionOptions) => Promise<DeviceResult>; stop: () => Promise<DeviceResult>; onChange: (handler: (sample: MotionSample) => void) => () => void; }; vibrate: (options?: VibrationOptions) => Promise<DeviceResult>; keepScreenOn: (enabled: boolean) => Promise<DeviceResult>; fullscreen: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; pointerLock: (enabled: boolean, target?: unknown) => Promise<DeviceResult>; onChange: (handler: (state: DeviceState) => void) => () => void; dispose: () => void; }
```
## DeviceCapabilities — interface @experimental
@@ -7479,6 +7479,35 @@ size: { x: number; y: number; z?: number; }
weight: number
```
+## PowerDecision — interface @experimental
+```
+ceiling: PowerLevel | null
+fps: number
+reason: "none" | "battery" | "thermal" | "critical"
+saving: boolean
+```
+
+## PowerLevel — type @experimental
+```
+'low' | 'medium' | 'high'
+```
+
+## PowerPolicy — interface @experimental
+```
+ceiling: PowerLevel | undefined
+fps: number | undefined
+lowBattery: number | undefined
+severe: "critical" | "never" | undefined
+thermal: "critical" | "serious" | "never" | undefined
+```
+
+## PowerState — interface @experimental
+```
+charging: boolean | null
+level: number | null
+thermal: "critical" | "serious" | "nominal" | "fair" | null
+```
+
## PreSceneDrawCallback — type @experimental
```
(info: PreSceneDrawInfo) => void
@@ -7811,6 +7840,7 @@ asyncShaderCompile: boolean | undefined
deviceRules: DeviceQualityRule[] | undefined
dynamicResolution: boolean | undefined
mode: QualityMode | undefined
+power: PowerPolicy | undefined
prewarmShaders: boolean | undefined
prewarmTimeoutMs: number | undefined
profiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefined
@@ -7826,6 +7856,7 @@ profile: Readonly<QualityProfile>
renderScale: number
report: () => QualityReport
sample: (frameMs: number, gpuMs?: number) => void
+setCeiling: (level: QualityLevel | null) => void
setLimitation: (reason: string, active: boolean) => void
setMode: (mode: QualityMode) => void
static new (config: QualityConfig, device_?: DeviceQualityInfo): QualityController
@@ -13949,6 +13980,11 @@ Plugin
(category: string, message: string, data?: unknown): void
```
+## decidePower — function @experimental
+```
+(state: PowerState, policy: PowerPolicy): PowerDecision
+```
+
## decodeImageBitmap — function @experimental
```
(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 10e0bbc63..9cb212778 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -348,6 +348,7 @@ export type { PathStyle, PathFill, PathStroke, PathColor, LineJoin, LineCap } fr
export { setPath, clearPath } from './render/pathRenderer';
export { RainShelter, RainUpright, uprightOf, uprightRects, drynessOf, maskRects, shelterMaskSizeOf, ellipseStripsOf, type RainShelterData, type RainUprightData, type Upright, type Shelter, type MaskRect } from './render/rainShelter';
export { Footsteps, StepSurface, StepKind, surfaceAt, footAt, stampLook, type FootstepsData, type StepSurfaceData } from './render/footsteps';
+export { decidePower, type PowerPolicy, type PowerDecision, type PowerLevel } from './render/power';
export { SwayPusher, nearestPushers, SWAY_PUSHERS, type SwayPusherData, type PushValue } from './render/swayPush';
export { FogOfWar, ExploredGrid, fanDistances, exploredToString, exploredFromString, type FogOfWarData } from './render/fogOfWar';
export { SightViewer, SightTarget, segmentBlocked, seesPoint, sightRingOf, ringContains, currentSightRings, type SightViewerData, type SightTargetData, type SightRing, type SightPoint } from './render/sight';
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 8c77eedef..d9e8289f9 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -393,4 +393,4 @@ export type { AotHost } from './ecs/aot/installAot';
export type { AotManifest, AotSystemDecl } from './ecs/aot/AotSystems';
export { Device } from './device';
-export type { DeviceResult, DeviceRequestStatus, DeviceCapabilities, DeviceState, MotionOptions, MotionSample, MotionRate, VibrationOptions, VibrationIntensity } from './device';
+export type { DeviceResult, DeviceRequestStatus, DeviceCapabilities, DeviceState, PowerState, MotionOptions, MotionSample, MotionRate, VibrationOptions, VibrationIntensity } from './device';
diff --git a/sdk/src/device/index.ts b/sdk/src/device/index.ts
index 0590a4697..4d495f939 100644
--- a/sdk/src/device/index.ts
+++ b/sdk/src/device/index.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { getPlatform, isPlatformInitialized } from '../platform/base';
import { unavailableDevice } from './core';
-import { deviceFailure, type DeviceBackend, type DeviceResult, type MotionOptions, type MotionSample, type DeviceState, type VibrationOptions } from './types';
+import { NO_POWER_STATE, deviceFailure, type DeviceBackend, type PowerState, type DeviceResult, type MotionOptions, type MotionSample, type DeviceState, type VibrationOptions } from './types';
export type * from './types';
const unavailable = unavailableDevice();
function backend(): DeviceBackend {
@@ -15,6 +15,8 @@ function invoke(call: (device: DeviceBackend) => Promise<DeviceResult>): Promise
export const Device = {
capabilities: () => backend().capabilities(),
state: () => backend().state(),
+ /** The battery and the processor's heat as far as the platform has said (a null is a thing it does not say). */
+ power: (): PowerState => backend().power?.() ?? NO_POWER_STATE,
motion: {
start: (options?: MotionOptions) => invoke(d => d.startMotion(options)),
stop: () => invoke(d => d.stopMotion()),
diff --git a/sdk/src/device/minigame.ts b/sdk/src/device/minigame.ts
index e90db3e6e..17d2405f2 100644
--- a/sdk/src/device/minigame.ts
+++ b/sdk/src/device/minigame.ts
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { DeviceEvents, emptyMotion } from './core';
-import { DEVICE_OK, DEVICE_UNAVAILABLE, NO_DEVICE_CAPABILITIES, deviceFailure,
- type DeviceBackend, type DeviceResult, type MotionOptions, type VibrationOptions } from './types';
+import { DEVICE_OK, DEVICE_UNAVAILABLE, NO_DEVICE_CAPABILITIES, NO_POWER_STATE, deviceFailure,
+ type DeviceBackend, type DeviceResult, type MotionOptions, type PowerState, type VibrationOptions } from './types';
import type { Vec3 } from '../types';
interface Callbacks { success?(): void; fail?(error: { errMsg?: string }): void }
@@ -19,6 +19,8 @@ export interface MiniGameDeviceHost {
vibrateShort?(options: Callbacks & { type: 'light' | 'medium' | 'heavy' }): void;
vibrateLong?(options: Callbacks): void;
setKeepScreenOn?(options: Callbacks & { keepScreenOn: boolean }): void;
+ /** The battery as the mini-game platform reports it: level 0 to 100. */
+ getBatteryInfoSync?(): { level: number; isCharging: boolean };
onHide?(handler: () => void): void;
offHide?(handler: () => void): void;
onShow?(handler: () => void): void;
@@ -36,6 +38,12 @@ export class MiniGameDevice implements DeviceBackend {
constructor(private readonly host: MiniGameDeviceHost, private readonly now: () => number = () => Date.now()) {
host.onHide?.(this.hide); host.onShow?.(this.show);
}
+ power(): PowerState {
+ try {
+ const info = this.host.getBatteryInfoSync?.();
+ return info ? { level: Math.min(Math.max(info.level / 100, 0), 1), charging: !!info.isCharging, thermal: null } : NO_POWER_STATE;
+ } catch { return NO_POWER_STATE; }
+ }
capabilities() {
const h = this.host;
return { ...NO_DEVICE_CAPABILITIES,
diff --git a/sdk/src/device/types.ts b/sdk/src/device/types.ts
index 1fb6f0870..ec05781ac 100644
--- a/sdk/src/device/types.ts
+++ b/sdk/src/device/types.ts
@@ -34,7 +34,18 @@ export interface MotionSample {
export type VibrationIntensity = 'light' | 'medium' | 'heavy';
export interface VibrationOptions { duration?: 'short' | 'long'; intensity?: VibrationIntensity }
export interface DeviceState { fullscreen: boolean; pointerLocked: boolean; screenOn: boolean; motionActive: boolean }
+/** How much the device has left to give: the battery and how hot it runs. A null is a thing this platform does not say, which is not the same as nothing being wrong. */
+export interface PowerState {
+ /** The battery's charge, 0 to 1. */
+ level: number | null;
+ charging: boolean | null;
+ /** Thermal pressure on the processor, as the platform reports it. */
+ thermal: 'nominal' | 'fair' | 'serious' | 'critical' | null;
+}
+export const NO_POWER_STATE: PowerState = { level: null, charging: null, thermal: null };
export interface DeviceBackend {
+ /** The device's battery and thermal state, from what the platform has told it so far. Absent on a backend that cannot know. */
+ power?(): PowerState;
capabilities(): DeviceCapabilities;
state(): DeviceState;
startMotion(options?: MotionOptions): Promise<DeviceResult>;
diff --git a/sdk/src/device/web.ts b/sdk/src/device/web.ts
index b94e16aa9..eacfaf8ba 100644
--- a/sdk/src/device/web.ts
+++ b/sdk/src/device/web.ts
@@ -2,11 +2,14 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { DeviceEvents, emptyMotion } from './core';
import { DEVICE_OK, DEVICE_UNAVAILABLE, deviceFailure, type DeviceBackend, type DeviceCapabilities, type DeviceResult,
- type MotionOptions, type VibrationOptions } from './types';
+ type MotionOptions, type PowerState, type VibrationOptions } from './types';
type PermissionEvent = { requestPermission?: () => Promise<string> };
type WakeSentinel = { released: boolean; release(): Promise<void>; addEventListener(type: string, listener: () => void): void };
-type WakeNavigator = Navigator & { wakeLock?: { request(type: 'screen'): Promise<WakeSentinel> } };
+type BatteryManager = { level: number; charging: boolean; addEventListener(type: string, listener: () => void): void; removeEventListener(type: string, listener: () => void): void };
+type PressureRecord = { state: PowerState['thermal'] };
+type PressureObserverLike = { observe(source: 'cpu'): Promise<void>; disconnect(): void };
+type WakeNavigator = Navigator & { wakeLock?: { request(type: 'screen'): Promise<WakeSentinel> }; getBattery?: () => Promise<BatteryManager> };
export class WebDevice implements DeviceBackend {
private readonly events = new DeviceEvents();
@@ -17,6 +20,10 @@ export class WebDevice implements DeviceBackend {
private wake: WakeSentinel | null = null;
private disposed = false;
private lastMotion = 0;
+ private battery: BatteryManager | null = null;
+ private pressure: PowerState['thermal'] = null;
+ private pressureObserver: PressureObserverLike | null = null;
+ private powerStarted = false;
constructor(private readonly win: Window = window, private readonly doc: Document = document,
private readonly nav: WakeNavigator = navigator as WakeNavigator) {
doc.addEventListener('visibilitychange', this.visibility);
@@ -34,6 +41,25 @@ export class WebDevice implements DeviceBackend {
pointerLock: typeof this.doc.documentElement?.requestPointerLock === 'function' };
}
state() { return { ...this.events.state }; }
+ /** What the browser has said so far: the battery (Chromium) and the processor's pressure (Chromium). Both arrive a moment after the first call. */
+ power(): PowerState {
+ this.startPower();
+ const battery = this.battery;
+ return { level: battery ? battery.level : null, charging: battery ? battery.charging : null, thermal: this.pressure };
+ }
+ private startPower(): void {
+ if (this.powerStarted || this.disposed) return;
+ this.powerStarted = true;
+ try { void this.nav.getBattery?.().then((battery) => { if (!this.disposed) this.battery = battery; }, () => undefined); } catch { /* no battery to read */ }
+ try {
+ const Observer = (this.win as unknown as { PressureObserver?: new (callback: (records: PressureRecord[]) => void) => PressureObserverLike }).PressureObserver;
+ if (Observer) {
+ const observer = new Observer((records) => { const last = records[records.length - 1]; if (last) this.pressure = last.state; });
+ this.pressureObserver = observer;
+ void observer.observe('cpu').catch(() => undefined);
+ }
+ } catch { /* the page may not be allowed to observe pressure */ }
+ }
onMotion(handler: Parameters<DeviceBackend['onMotion']>[0]) { return this.events.onMotion(handler); }
onStateChange(handler: Parameters<DeviceBackend['onStateChange']>[0]) { return this.events.onStateChange(handler); }
async startMotion(options: MotionOptions = {}): Promise<DeviceResult> {
@@ -133,6 +159,7 @@ export class WebDevice implements DeviceBackend {
this.win.removeEventListener('pagehide', this.hide); this.win.removeEventListener('pageshow', this.visibility);
this.doc.removeEventListener('fullscreenchange', this.screenChanged);
this.doc.removeEventListener('pointerlockchange', this.screenChanged); this.events.dispose();
+ this.pressureObserver?.disconnect(); this.pressureObserver = null; this.battery = null;
}
private bindMotion(): void {
if (!this.options || this.disposed) return;
diff --git a/sdk/src/render/power.ts b/sdk/src/render/power.ts
new file mode 100644
index 000000000..5c71d365e
--- /dev/null
+++ b/sdk/src/render/power.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file power.ts
+ * @brief When the device is short of power or hot, the engine draws less: a frame cap and a ceiling on the quality level, taken off again when it recovers.
+ *
+ * @details A long session on a phone is heat and battery, and the frame is where both are spent. The engine already has the means (a frame cap, quality
+ * levels, render-on-demand); what was missing was something that notices the device and uses them. The device backend reports a {@link PowerState}
+ * (the battery's level and whether it is charging, and the thermal pressure where the platform says it), a {@link PowerPolicy} says when that is
+ * "saving" and what saving does, and the quality system applies it. Everything is off unless the game names a policy: a game that never asks for
+ * this draws exactly as it did.
+ *
+ * What a platform cannot report is null, and a null never triggers anything: a browser with no battery API saves nothing for battery and loses
+ * nothing else. Saving never raises a cap or a level, only lowers it, and takes its own lowering off when the reason is gone.
+ */
+import type { PowerState } from '../device/types';
+
+/** The level names a ceiling is given in, lowest first. */
+export type PowerLevel = 'low' | 'medium' | 'high';
+
+/** @experimental */
+export interface PowerPolicy {
+ /** Saves when the battery is below this share (0 to 1) and not charging. Default 0.2; 0 never saves for the battery. */
+ lowBattery?: number;
+ /** Saves under thermal pressure of this level or worse: 'serious' (default), 'critical', or 'never'. */
+ thermal?: 'serious' | 'critical' | 'never';
+ /** The frame cap while saving, in frames a second (default 30). Never raises a cap the game already set lower. */
+ fps?: number;
+ /** The quality level no level may exceed while saving (default 'medium'). */
+ ceiling?: PowerLevel;
+ /** The thermal pressure that also holds the level at 'low' and the cap at half of `fps`, never below 15 (default 'critical'; 'never' for none). */
+ severe?: 'critical' | 'never';
+}
+
+/** What saving does, as the quality system applies it. */
+export interface PowerDecision {
+ saving: boolean;
+ /** The frame cap, or 0 for none. */
+ fps: number;
+ /** The level ceiling, or null for none. */
+ ceiling: PowerLevel | null;
+ /** Why it is saving, or 'none'. */
+ reason: 'none' | 'battery' | 'thermal' | 'critical';
+}
+
+const THERMAL_RANK = { nominal: 0, fair: 1, serious: 2, critical: 3 } as const;
+
+/** What the policy says to do about the state the device is in. A null in the state is a reason that cannot hold. */
+export function decidePower(state: PowerState, policy: PowerPolicy): PowerDecision {
+ const none: PowerDecision = { saving: false, fps: 0, ceiling: null, reason: 'none' };
+ const lowBattery = policy.lowBattery ?? 0.2;
+ const thermal = state.thermal ? THERMAL_RANK[state.thermal] : 0;
+ const thermalAt = policy.thermal === 'never' ? Infinity : policy.thermal === 'critical' ? 3 : 2;
+ const severeAt = policy.severe === 'never' ? Infinity : 3;
+ const lowPower = lowBattery > 0 && state.level !== null && state.level < lowBattery && state.charging === false;
+ const hot = thermal >= thermalAt;
+ if (!lowPower && !hot) return none;
+ const fps = Math.max(policy.fps ?? 30, 1);
+ const severe = thermal >= severeAt;
+ return {
+ saving: true,
+ fps: severe ? Math.max(Math.round(fps / 2), 15) : fps,
+ ceiling: severe ? 'low' : policy.ceiling ?? 'medium',
+ reason: severe ? 'critical' : hot ? 'thermal' : 'battery',
+ };
+}
diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.ts
index 68cb17e36..cbf1f7b43 100644
--- a/sdk/src/render/quality.ts
+++ b/sdk/src/render/quality.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { PowerPolicy } from './power';
export type QualityLevel = 'low' | 'medium' | 'high';
export type QualityMode = 'off' | 'auto' | QualityLevel;
@@ -114,6 +115,11 @@ export interface QualityConfig {
prewarmTimeoutMs?: number;
profiles?: Partial<Record<QualityLevel, Partial<QualityProfile>>>;
deviceRules?: DeviceQualityRule[];
+ /**
+ * Draw less when the device is short of battery or running hot: a frame cap and a ceiling on the level while it is, both taken off when it recovers.
+ * Absent, the device is not watched and nothing changes. See {@link PowerPolicy}.
+ */
+ power?: PowerPolicy;
}
const LEVELS: readonly QualityLevel[] = ['low', 'medium', 'high'];
@@ -173,6 +179,7 @@ export function parseQualityConfig(value: unknown): QualityConfig {
renderOnDemandTail: finite(raw.renderOnDemandTail, 30, 1, 600),
prewarmTimeoutMs: finite(raw.prewarmTimeoutMs, 30000, 1000, 600000),
};
+ if (raw.power !== undefined && raw.power !== false) config.power = parsePowerPolicy(raw.power);
if (raw.profiles) {
config.profiles = {};
for (const level of LEVELS) {
@@ -199,6 +206,18 @@ export function parseQualityConfig(value: unknown): QualityConfig {
return config;
}
+/** A power policy from a project's settings: what is not a usable number or name keeps its default, and `true` is every default. */
+export function parsePowerPolicy(value: unknown): PowerPolicy {
+ const r = record(value);
+ const policy: PowerPolicy = {};
+ if (typeof r.lowBattery === 'number' && Number.isFinite(r.lowBattery)) policy.lowBattery = Math.min(Math.max(r.lowBattery, 0), 1);
+ if (r.thermal === 'serious' || r.thermal === 'critical' || r.thermal === 'never') policy.thermal = r.thermal;
+ if (typeof r.fps === 'number' && Number.isFinite(r.fps)) policy.fps = Math.min(Math.max(Math.round(r.fps), 10), 120);
+ if (r.ceiling === 'low' || r.ceiling === 'medium' || r.ceiling === 'high') policy.ceiling = r.ceiling;
+ if (r.severe === 'critical' || r.severe === 'never') policy.severe = r.severe;
+ return policy;
+}
+
function resolveProfile(level: QualityLevel, value: unknown): QualityProfile {
const base = PROFILES[level];
const r = record(value);
@@ -275,6 +294,9 @@ export interface QualityReport {
export class QualityController {
private config_: QualityConfig;
private level_: QualityLevel = 'high';
+ /** The level the mode asks for, before a ceiling lowers it. */
+ private modeLevel_: QualityLevel = 'high';
+ private ceiling_: QualityLevel | null = null;
private profile_: QualityProfile = PROFILES.high;
private scale_ = 1;
private average_ = 0;
@@ -298,8 +320,9 @@ export class QualityController {
const rule = this.config_.deviceRules?.find(r => matches(r, this.device_));
const low = (this.device_.memoryGB !== undefined && this.device_.memoryGB <= 2)
|| (this.device_.cores !== undefined && this.device_.cores <= 2);
- this.level_ = mode === 'off' ? 'high' : mode === 'auto'
+ this.modeLevel_ = mode === 'off' ? 'high' : mode === 'auto'
? rule?.level ?? (low ? 'low' : 'medium') : mode;
+ this.level_ = this.ceilingOf_(this.modeLevel_);
this.profile_ = resolveProfile(this.level_, this.config_.profiles?.[this.level_]);
this.scale_ = mode === 'off' ? 1 : this.profile_.renderScale;
this.average_ = this.pressureMs_ = this.recoveryMs_ = 0;
@@ -308,6 +331,27 @@ export class QualityController {
this.modeReason_ = this.reason_;
}
+ private ceilingOf_(level: QualityLevel): QualityLevel {
+ return this.ceiling_ !== null && LEVELS.indexOf(this.ceiling_) < LEVELS.indexOf(level) ? this.ceiling_ : level;
+ }
+
+ /**
+ * No level above `level` while it is set; null takes it off. Only lowers: a mode already at or under the ceiling is left as it is. Used by the power
+ * policy, which holds the level down while the device is short of battery or hot.
+ */
+ setCeiling(level: QualityLevel | null): void {
+ if (this.ceiling_ === level) return;
+ this.ceiling_ = level;
+ const next = this.ceilingOf_(this.modeLevel_);
+ this.setLimitation('power-saver', next !== this.modeLevel_);
+ if (next === this.level_) return;
+ this.level_ = next;
+ this.profile_ = resolveProfile(next, this.config_.profiles?.[next]);
+ this.scale_ = this.enabled ? this.profile_.renderScale : 1;
+ this.average_ = this.pressureMs_ = this.recoveryMs_ = 0;
+ this.reason_ = next !== this.modeLevel_ ? 'power-saver' : this.modeReason_;
+ }
+
setLimitation(reason: string, active: boolean): void {
if (active) this.limitations_.add(reason);
else this.limitations_.delete(reason);
diff --git a/sdk/src/render/qualityRuntime.ts b/sdk/src/render/qualityRuntime.ts
index f121a621b..9d7691621 100644
--- a/sdk/src/render/qualityRuntime.ts
+++ b/sdk/src/render/qualityRuntime.ts
@@ -7,6 +7,8 @@ import { engineApi } from '../ecs/bridge/engineApi';
import { getPlatform, platformNow, platformOnAppHide, platformOnAppShow } from '../platform';
import { QualityController, type QualityConfig, type QualityProfile } from './quality';
import { getDeviceIdentity } from './renderer';
+import { decidePower } from './power';
+import { NO_POWER_STATE } from '../device/types';
/** @experimental */
export const Quality = defineResource<QualityController | null>(null, 'Quality');
@@ -51,11 +53,37 @@ export function installQuality(app: App, config: QualityConfig, authoredMsaa: nu
};
app.pipeline?.setQuality(quality, apply);
apply();
+
+ // The device's battery and heat, looked at every few seconds and only when a policy names them: saving lowers the frame cap and the level, and
+ // takes only its own lowering off. A cap the game set lower than the saver's is left alone, and one it changes meanwhile is the game's.
+ const policy = config.power;
+ let powerTimer: ReturnType<typeof setInterval> | null = null;
+ if (policy) {
+ let capped: { from: number; to: number } | null = null;
+ const check = (): void => {
+ const state = platform.device?.().power?.() ?? NO_POWER_STATE;
+ const decision = decidePower(state, policy);
+ quality.setCeiling(decision.ceiling);
+ quality.setLimitation('power-saver', decision.saving);
+ const now = app.getTargetFrameRate();
+ if (decision.saving && decision.fps > 0) {
+ // Lowered only: an uncapped loop (0) or a higher cap goes down to the saver's; a lower one stays.
+ if (capped === null && (now === 0 || now > decision.fps)) { capped = { from: now, to: decision.fps }; app.setTargetFrameRate(decision.fps); }
+ else if (capped !== null && capped.to !== decision.fps && now === capped.to) { capped.to = decision.fps; app.setTargetFrameRate(decision.fps); }
+ } else if (capped !== null) {
+ // Back to what it was, unless the game has set its own cap since.
+ if (now === capped.to) app.setTargetFrameRate(capped.from);
+ capped = null;
+ }
+ };
+ check();
+ powerTimer = setInterval(check, 5000);
+ }
const stop = app.onFrameEnd(() => {
const now = platformNow();
if (!hidden && !app.isPaused() && last > 0) quality.sample(now - last,
engineApi(app)?.renderer_getGpuTimeMs?.() ?? -1);
last = hidden || app.isPaused() ? 0 : now;
});
- app.addPlugin({ name: 'quality', build() {}, cleanup() { stop(); hide(); show(); } });
+ app.addPlugin({ name: 'quality', build() {}, cleanup() { stop(); hide(); show(); if (powerTimer !== null) clearInterval(powerTimer); } });
}
diff --git a/sdk/tests/power-runtime.test.ts b/sdk/tests/power-runtime.test.ts
new file mode 100644
index 000000000..52c28b834
--- /dev/null
+++ b/sdk/tests/power-runtime.test.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The power policy at run time: the frame cap and the level ceiling go on when the device says it is short, and come off only as far as they were put on.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { App } from '../src/app/app';
+import { Quality, installQuality } from '../src/render/qualityRuntime';
+import type { QualityController } from '../src/render/quality';
+import type { PowerState } from '../src/device/types';
+
+const { device } = vi.hoisted(() => ({ device: { state: { level: null, charging: null, thermal: null } as PowerState, reads: 0 } }));
+
+vi.mock('../src/platform', () => ({
+ getPlatform: () => ({ deviceName: () => 'phone', deviceQualityInfo: () => ({ memoryGB: 8, cores: 8 }), device: () => ({ power: () => { device.reads++; return device.state; } }) }),
+ platformNow: () => 1,
+ platformOnAppHide: () => () => {}, platformOnAppShow: () => () => {},
+}));
+vi.mock('../src/ecs/bridge/engineApi', () => ({ engineApi: () => ({}) }));
+
+function fakeApp(cap: number) {
+ let controller: QualityController | null = null;
+ const app = {
+ wasmModule: null, cap,
+ insertResource: (resource: unknown, value: QualityController) => { if (resource === Quality) controller = value; },
+ pipeline: { setQuality: () => {} }, addPlugin: vi.fn(), onFrameEnd: () => () => {},
+ getTargetFrameRate() { return app.cap; },
+ setTargetFrameRate(fps: number) { app.cap = fps; },
+ };
+ return { app, app_: app as unknown as App, controller: () => controller! };
+}
+
+beforeEach(() => { vi.useFakeTimers(); device.state = { level: null, charging: null, thermal: null }; device.reads = 0; });
+afterEach(() => { vi.useRealTimers(); });
+
+describe('saving power at run time', () => {
+ it('caps the frame rate and the level while the battery is low, and puts both back when it recovers', () => {
+ const { app, app_, controller } = fakeApp(0);
+ installQuality(app_, { mode: 'high', power: {} }, 4);
+ expect(app.cap).toBe(0);
+ expect(controller().report().level).toBe('high');
+ device.state = { level: 0.1, charging: false, thermal: null };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(30);
+ expect(controller().report().level).toBe('medium');
+ expect(controller().report().limitations).toContain('power-saver');
+ device.state = { level: 0.1, charging: true, thermal: null };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(0);
+ expect(controller().report().level).toBe('high');
+ expect(controller().report().limitations).not.toContain('power-saver');
+ });
+
+ it('never raises a cap the game set lower, and puts back the cap it found', () => {
+ const { app, app_ } = fakeApp(24);
+ installQuality(app_, { mode: 'high', power: { fps: 30 } }, 4);
+ device.state = { level: 0.05, charging: false, thermal: null };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(24);
+ const sixty = fakeApp(60);
+ installQuality(sixty.app_, { mode: 'high', power: { fps: 30 } }, 4);
+ vi.advanceTimersByTime(5000);
+ expect(sixty.app.cap).toBe(30);
+ device.state = { level: 0.9, charging: false, thermal: null };
+ vi.advanceTimersByTime(5000);
+ expect(sixty.app.cap).toBe(60);
+ });
+
+ it('leaves a cap the game changed while saving to the game, and halves it at critical heat', () => {
+ const { app, app_, controller } = fakeApp(60);
+ installQuality(app_, { mode: 'high', power: { fps: 30 } }, 4);
+ device.state = { level: null, charging: null, thermal: 'serious' };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(30);
+ device.state = { level: null, charging: null, thermal: 'critical' };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(15);
+ expect(controller().report().level).toBe('low');
+ // The game takes the cap itself: recovery does not overwrite it.
+ app.cap = 45;
+ device.state = { level: null, charging: null, thermal: 'nominal' };
+ vi.advanceTimersByTime(5000);
+ expect(app.cap).toBe(45);
+ expect(controller().report().level).toBe('high');
+ });
+
+ it('does not look at the device at all without a policy', () => {
+ const { app, app_ } = fakeApp(0);
+ device.state = { level: 0.01, charging: false, thermal: 'critical' };
+ installQuality(app_, { mode: 'high' }, 4);
+ vi.advanceTimersByTime(20000);
+ expect(app.cap).toBe(0);
+ expect(device.reads).toBe(0);
+ });
+});
diff --git a/sdk/tests/power-saving.test.ts b/sdk/tests/power-saving.test.ts
new file mode 100644
index 000000000..3856a2a7f
--- /dev/null
+++ b/sdk/tests/power-saving.test.ts
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Drawing less when the device is short of power or hot: when the policy says saving, what it takes, and that the device says so honestly.
+ */
+import { describe, expect, it } from 'vitest';
+import { decidePower } from '../src/render/power';
+import { QualityController, parsePowerPolicy, parseQualityConfig } from '../src/render/quality';
+import { WebDevice } from '../src/device/web';
+import { NO_POWER_STATE, type PowerState } from '../src/device/types';
+
+const state = (over: Partial<PowerState>): PowerState => ({ ...NO_POWER_STATE, ...over });
+
+describe('when the policy saves', () => {
+ it('saves on a low battery that is not charging, and not on a charging one or a full one', () => {
+ expect(decidePower(state({ level: 0.1, charging: false }), {})).toMatchObject({ saving: true, fps: 30, ceiling: 'medium', reason: 'battery' });
+ expect(decidePower(state({ level: 0.1, charging: true }), {}).saving).toBe(false);
+ expect(decidePower(state({ level: 0.9, charging: false }), {}).saving).toBe(false);
+ expect(decidePower(state({ level: 0.19, charging: false }), { lowBattery: 0.15 }).saving).toBe(false);
+ expect(decidePower(state({ level: 0.01, charging: false }), { lowBattery: 0 }).saving).toBe(false);
+ });
+
+ it('saves under serious thermal pressure, and halves the cap and holds the level low at critical', () => {
+ expect(decidePower(state({ thermal: 'fair' }), {}).saving).toBe(false);
+ expect(decidePower(state({ thermal: 'serious' }), {})).toMatchObject({ saving: true, fps: 30, ceiling: 'medium', reason: 'thermal' });
+ expect(decidePower(state({ thermal: 'critical' }), {})).toMatchObject({ saving: true, fps: 15, ceiling: 'low', reason: 'critical' });
+ expect(decidePower(state({ thermal: 'serious' }), { thermal: 'critical' }).saving).toBe(false);
+ expect(decidePower(state({ thermal: 'critical' }), { thermal: 'never' }).saving).toBe(false);
+ expect(decidePower(state({ thermal: 'critical' }), { severe: 'never' })).toMatchObject({ fps: 30, ceiling: 'medium' });
+ });
+
+ it('takes the policy\'s own cap and ceiling, never a cap under 15 from halving', () => {
+ expect(decidePower(state({ level: 0.05, charging: false }), { fps: 24, ceiling: 'low' })).toMatchObject({ fps: 24, ceiling: 'low' });
+ expect(decidePower(state({ thermal: 'critical' }), { fps: 20 }).fps).toBe(15);
+ });
+
+ it('never saves for what the platform does not say: a null is not a reason', () => {
+ expect(decidePower(NO_POWER_STATE, {})).toEqual({ saving: false, fps: 0, ceiling: null, reason: 'none' });
+ expect(decidePower(state({ level: 0.01, charging: null }), {}).saving).toBe(false);
+ });
+});
+
+describe('the quality ceiling', () => {
+ it('lowers a level above it and leaves one at or under it, and goes away when it is taken off', () => {
+ const q = new QualityController({ mode: 'high' });
+ expect(q.report().level).toBe('high');
+ q.setCeiling('medium');
+ expect(q.report().level).toBe('medium');
+ expect(q.report().limitations).toContain('power-saver');
+ expect(q.report().reason).toBe('power-saver');
+ q.setCeiling(null);
+ expect(q.report().level).toBe('high');
+ expect(q.report().limitations).not.toContain('power-saver');
+ const low = new QualityController({ mode: 'low' });
+ low.setCeiling('medium');
+ expect(low.report().level).toBe('low');
+ expect(low.report().limitations).not.toContain('power-saver');
+ });
+
+ it('keeps a ceiling across a change of mode', () => {
+ const q = new QualityController({ mode: 'low' });
+ q.setCeiling('medium');
+ q.setMode('high');
+ expect(q.report().level).toBe('medium');
+ });
+});
+
+describe('the power policy as a project states it', () => {
+ it('keeps what is usable, clamps what is out of range, and drops what is not a name', () => {
+ expect(parsePowerPolicy({ lowBattery: 3, fps: 5, ceiling: 'ultra', thermal: 'critical', severe: 'never' }))
+ .toEqual({ lowBattery: 1, fps: 10, thermal: 'critical', severe: 'never' });
+ expect(parsePowerPolicy(true)).toEqual({});
+ expect(parseQualityConfig({ mode: 'auto', power: { fps: 24 } }).power).toEqual({ fps: 24 });
+ expect(parseQualityConfig({ mode: 'auto' }).power).toBeUndefined();
+ expect(parseQualityConfig({ mode: 'auto', power: false }).power).toBeUndefined();
+ });
+});
+
+describe('what a browser says of the device', () => {
+ const win = () => ({ addEventListener() {}, removeEventListener() {} }) as unknown as Window;
+ const doc = () => ({ addEventListener() {}, removeEventListener() {}, hidden: false, documentElement: {} }) as unknown as Document;
+
+ it('says nothing before the browser has answered, then the battery it reported', async () => {
+ const battery = { level: 0.4, charging: false, addEventListener() {}, removeEventListener() {} };
+ const nav = { getBattery: () => Promise.resolve(battery) } as never;
+ const device = new WebDevice(win(), doc(), nav);
+ expect(device.power()).toEqual({ level: null, charging: null, thermal: null });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(device.power()).toEqual({ level: 0.4, charging: false, thermal: null });
+ battery.level = 0.1;
+ expect(device.power().level).toBe(0.1);
+ device.dispose();
+ });
+
+ it('says nothing for a browser with no battery API and no pressure observer', () => {
+ const device = new WebDevice(win(), doc(), {} as never);
+ expect(device.power()).toEqual({ level: null, charging: null, thermal: null });
+ device.dispose();
+ });
+
+ it('takes the processor pressure a PressureObserver reports', async () => {
+ let deliver: ((records: { state: PowerState['thermal'] }[]) => void) | null = null;
+ const w = win() as unknown as { PressureObserver: unknown };
+ w.PressureObserver = class { constructor(cb: typeof deliver) { deliver = cb; } observe() { return Promise.resolve(); } disconnect() {} };
+ const device = new WebDevice(w as unknown as Window, doc(), {} as never);
+ expect(device.power().thermal).toBeNull();
+ deliver!([{ state: 'fair' }, { state: 'serious' }]);
+ expect(device.power().thermal).toBe('serious');
+ device.dispose();
+ });
+});
diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjs
index a305259be..42b708b06 100644
--- a/tools/check-project-settings.mjs
+++ b/tools/check-project-settings.mjs
@@ -267,6 +267,7 @@ const BLOCKS = [
prewarmShaders: { ui: 'project.rendering.quality.prewarmShaders' },
prewarmTimeoutMs: { ui: 'project.rendering.quality.prewarmTimeoutMs' },
renderOnDemand: { ui: 'project.rendering.quality.renderOnDemand' },
+ power: { ui: 'project.rendering.quality.power' },
renderOnDemandTail: { ui: 'project.rendering.quality.renderOnDemandTail' },
profiles: { ui: 'project.rendering.quality.renderScale' },
deviceRules: { ui: 'project.rendering.qualityDeviceRules' },