feat(screen): configure Web DPR through startup settings (#367)

* feat(pal): declare startup maximum DPR configuration

Add an optional maximum DPR to screen initialization and readonly access to
the original DPR and explicitly configured cap. An omitted or null cap retains
the platform's existing policy.

This is the engine type contract for the staged PAL implementation. Public
Screen configuration methods and Native render-target integration remain
separate work; this commit does not change runtime rendering.

Validated against the PAL engine/four-platform contract check and full npm test
(65 source tests, 4 build tests, release/debug module validation).

* feat(screen): expose startup maximum DPR configuration

Allow applications to set, reset and read a pending maximum DPR before Screen
initialization while preserving platform defaults when unconfigured. Lock the
configuration at initialization and reject unsupported PAL implementations or
options that PAL silently ignores.

Add startup validation and compatibility tests. Only implementation and tests
are included; local documentation and generated validation artifacts remain
outside this commit.

Companion PAL commit: 2959778b7acf83dd84e3aab5957d60d80e20c461.
Native render-target integration, device acceptance, runtime changes and editor
configuration remain separate work.

Validation recorded on 2026-09-29: tsc --noEmit; 20 Screen and 6 View tests;
public declaration generation; real WebGL demo with simulated host DPR,
first-draw, input, reset, late-call rejection and resize checks. Screen source
SHA-256 still matches that verified build.

* fix(screen): restrict startup DPR configuration to Web

* fix(screen): ignore DPR cap calls on non-Web platforms

* fix(screen): preserve optional DPR types in native builds

* refactor(screen): configure Web DPR through startup settings

* refactor(screen): delegate DPR policy and validation to PAL

* style(screen): wrap fullscreen method signatures

* perf(screen): simplify startup DPR null checks

* version update
This commit is contained in:
ChiaNing
2026-10-22 19:15:17 +08:00
committed by GitHub
parent d0a696cfe6
commit f570c1f02d
8 changed files with 284 additions and 12 deletions
+12
View File
@@ -22,6 +22,12 @@ declare module 'pal/screen-adapter' {
* Determine whether use headless renderer, which means do not support some screen operations.
*/
isHeadlessMode: boolean;
/**
* Optional startup DPR cap, currently consumed by Web.
* Supporting adapters validate that it is finite and >= 1; other adapters ignore it.
* Omission/null preserves the adapter's default policy (Web caps DPR at 2).
*/
maxDevicePixelRatio?: number | null;
}
class ScreenAdapter {
@@ -58,6 +64,12 @@ declare module 'pal/screen-adapter' {
* Query the current fullscreen state.
*/
public get isFullScreen (): boolean;
/**
* Optional capability: the applied startup cap, or null for the adapter's default.
* Adapters exposing this property consume and validate maxDevicePixelRatio.
* Absent on adapters that ignore this setting.
*/
public readonly maxDevicePixelRatio?: number | null;
/**
* The ratio of pixel sizes:
* the size of one CSS pixel to the size of one physical pixel.
+12
View File
@@ -3226,6 +3226,18 @@ Cannot access game frame or container.
Setting window size is not supported.
### 9204
maxDevicePixelRatio, when specified, must be a finite number >= 1.
### 9205
PAL did not apply the configured maximum DPR. Check that the engine and PAL versions match.
### 9206
maxDevicePixelRatio cannot change after ScreenAdapter.init().
### 9300
The current buffer beyond the limit in ui static component, please reduce the amount
+1 -1
View File
@@ -45,5 +45,5 @@ export {
DebugMode,
} from './debug';
export { screen } from './screen';
export { screen, MaxDPR } from './screen';
export type { Screen } from './screen';
+51 -6
View File
@@ -25,12 +25,34 @@
THE SOFTWARE.
*/
import { screenAdapter } from 'pal/screen-adapter';
import { screenAdapter, IScreenOptions } from 'pal/screen-adapter';
import { legacyCC } from '../global-exports';
import { Size } from '../math';
import { settings, SettingsCategory } from '../settings';
import { error, warn, warnID } from './debug';
import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type';
import { error, getError, warn, warnID } from './debug';
import type { PalScreenEvent } from '../../../pal/screen-adapter/enum-type';
/**
* @en Presets for the Web startup setting `screen.maxDevicePixelRatio`.
* Store the preset's numeric value or any finite number >= 1 in the startup settings.
* An omitted or null setting keeps the default cap of 2. Effective DPR never exceeds the browser DPR.
* Configure before Screen initialization; changing settings afterward does not resize the running game.
* Non-Web platforms ignore this setting. Higher caps increase pixel-related rendering costs.
* @zh Web 启动配置 `screen.maxDevicePixelRatio` 的预设档位。
* 在启动配置中保存预设的数值或任意有限且 >=1 的数字。
* 未配置或为 null 时保留默认上限 2,实际 DPR 不超过浏览器 DPR。
* 需在 Screen 初始化前配置,之后修改 settings 不会调整运行中游戏的分辨率。
* 非 Web 平台忽略该配置;提高上限会增加像素相关的渲染开销。
*/
export enum MaxDPR {
/** @en Cap DPR at 1 to reduce rendering cost. @zh 上限为 1,优先降低渲染开销。 */
Performance = 1,
/** @en Cap DPR at 2, matching the existing default. @zh 上限为 2,与现有默认策略一致。 */
Balanced = 2,
/** @en Cap DPR at 4 for higher-density rendering. @zh 上限为 4,允许更高密度渲染。 */
Quality = 4,
}
/**
* @en The screen API provides an easy way to do some screen managing stuff.
* @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。
@@ -40,10 +62,18 @@ export class Screen {
* @internal
*/
public init (): void {
// PAL decides whether to consume the setting and validates its value.
const maximum = settings.querySettings<number>(SettingsCategory.SCREEN, 'maxDevicePixelRatio');
const exactFitScreen = settings.querySettings(SettingsCategory.SCREEN, 'exactFitScreen') ?? true;
const orientation = settings.querySettings(SettingsCategory.SCREEN, 'orientation') ?? 'auto';
const isHeadlessMode = settings.querySettings(SettingsCategory.RENDERING, 'renderMode') === 3;
screenAdapter.init({ exactFitScreen, configOrientation: orientation, isHeadlessMode }, (): void => {
const options: IScreenOptions & { maxDevicePixelRatio?: number | null } = {
exactFitScreen, configOrientation: orientation, isHeadlessMode,
};
if (maximum != null) {
options.maxDevicePixelRatio = maximum;
}
screenAdapter.init(options, (): void => {
const director = legacyCC.director;
if (!director.root?.pipeline) {
warnID(1220);
@@ -51,6 +81,13 @@ export class Screen {
}
director.root.pipeline.shadingScale = screenAdapter.resolutionScale;
});
// Only adapters exposing this capability are expected to apply the setting.
// The property check also narrows concrete adapter types in Native TS builds.
if (maximum != null
&& 'maxDevicePixelRatio' in screenAdapter
&& screenAdapter.maxDevicePixelRatio !== maximum) {
throw new Error(getError(9205));
}
}
/**
@@ -137,7 +174,11 @@ export class Screen {
* @return {Promise|undefined}
* @deprecated since v3.3, please use `screen.requestFullScreen(): Promise<void>` instead.
*/
public requestFullScreen (element: HTMLElement, onFullScreenChange?: (this: Document, ev: any) => any, onFullScreenError?: (this: Document, ev: any) => any): Promise<any> | undefined;
public requestFullScreen (
element: HTMLElement,
onFullScreenChange?: (this: Document, ev: any) => any,
onFullScreenError?: (this: Document, ev: any) => any,
): Promise<any> | undefined;
/**
* @en Request to enter full screen mode.
* Many browsers forbid to enter full screen mode without an user intended interaction.
@@ -150,7 +191,11 @@ export class Screen {
* @return {Promise}
*/
public requestFullScreen (): Promise<void>;
public requestFullScreen (element?: HTMLElement, onFullScreenChange?: (this: Document, ev?: any) => any, onFullScreenError?: (this: Document, ev?: any) => any): Promise<any> {
public requestFullScreen (
element?: HTMLElement,
onFullScreenChange?: (this: Document, ev?: any) => any,
onFullScreenError?: (this: Document, ev?: any) => any,
): Promise<any> {
if (arguments.length > 0) {
warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
}
+4 -4
View File
@@ -15,7 +15,7 @@
"@cocos/cannon": "1.2.8",
"@cocos/ccbuild": "^2.3.21",
"@cocos/dragonbones-js": "^1.0.1",
"@cocos/engine-pal": "^1.0.4",
"@cocos/engine-pal": "^1.0.5",
"@cocos/engine-platforms": "^1.0.6",
"@types/jest": "^24.9.1"
},
@@ -2568,9 +2568,9 @@
"integrity": "sha512-1bWAW8td2WTGicyCqxtpIjc1YuK5EzMWfMEWaJlskPAQwLS0JfxEGka71sZ1BzudiWiKS7hPMg+FvXr5NRnVwQ=="
},
"node_modules/@cocos/engine-pal": {
"version": "1.0.4",
"resolved": "https://registry.npmmirror.com/@cocos/engine-pal/-/engine-pal-1.0.4.tgz",
"integrity": "sha512-VtvO0xE2ZviVtwqWn4P6cysn2BX7QABm9sNc1rfy4gy+FHtiwSMkLLL3l3Faw+yZiTE6EwxjPvnc96Igb7mNuQ=="
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@cocos/engine-pal/-/engine-pal-1.0.5.tgz",
"integrity": "sha512-KTqpQ/+GqjVr+iiyD58soC999Yg9zrpnQypwTAb550rrAY5Er/NVvhnneRzs6zAcMrxuWUY0dKQGXzAQghqz4w=="
},
"node_modules/@cocos/engine-platforms": {
"version": "1.0.6",
+1 -1
View File
@@ -83,7 +83,7 @@
"@cocos/cannon": "1.2.8",
"@cocos/ccbuild": "^2.3.21",
"@cocos/dragonbones-js": "^1.0.1",
"@cocos/engine-pal": "^1.0.4",
"@cocos/engine-pal": "^1.0.5",
"@cocos/engine-platforms": "^1.0.6",
"@types/jest": "^24.9.1"
},
+198
View File
@@ -0,0 +1,198 @@
import { screenAdapter } from 'pal/screen-adapter';
import * as constants from 'internal:constants';
import { Screen } from '../../cocos/core/platform/screen';
import { MaxDPR } from '../../cocos/core/platform';
import { Settings, settings, SettingsCategory } from '../../cocos/core/settings';
import { AsyncDelegate } from '../../cocos/core/event/async-delegate';
import * as debug from '../../cocos/core/platform/debug';
const adapter = screenAdapter as unknown as {
maxDevicePixelRatio?: number | null;
init: jest.Mock;
};
const originalAdapterPrototype = Object.getPrototypeOf(screenAdapter);
const flags = constants as unknown as Record<string, boolean | undefined>;
const platformKeys = ['HTML5', 'NATIVE', 'MINIGAME', 'RUNTIME_BASED', 'NODEJS'];
const originalFlags: typeof flags = {};
for (const key of platformKeys) originalFlags[key] = flags[key];
describe('Screen startup maximum DPR setting', () => {
let startupSettings: Settings;
let querySpy: jest.SpyInstance;
let initSpy: jest.SpyInstance;
let warnSpy: jest.SpyInstance;
beforeEach(() => {
Object.assign(flags, { HTML5: true, NATIVE: false, MINIGAME: false, RUNTIME_BASED: false, NODEJS: false });
startupSettings = new Settings();
// Exercise real Settings precedence without modifying the bootstrapped engine's settings.
querySpy = jest.spyOn(settings, 'querySettings').mockImplementation(startupSettings.querySettings.bind(startupSettings));
warnSpy = jest.spyOn(debug, 'warnID').mockImplementation(() => {});
Object.defineProperty(adapter, 'maxDevicePixelRatio', { value: null, writable: true, configurable: true });
initSpy = jest.spyOn(screenAdapter, 'init').mockImplementation(options => {
adapter.maxDevicePixelRatio = options.maxDevicePixelRatio ?? null;
});
});
afterEach(() => {
Object.assign(flags, originalFlags);
Object.setPrototypeOf(screenAdapter, originalAdapterPrototype);
querySpy.mockRestore();
initSpy.mockRestore();
warnSpy.mockRestore();
delete adapter.maxDevicePixelRatio;
});
function useAdapterWithoutDprCapability (): void {
const descriptors = Object.getOwnPropertyDescriptors(originalAdapterPrototype);
delete descriptors.maxDevicePixelRatio;
Object.setPrototypeOf(screenAdapter, Object.create(Object.getPrototypeOf(originalAdapterPrototype), descriptors));
delete adapter.maxDevicePixelRatio;
initSpy.mockImplementation(() => {});
expect('maxDevicePixelRatio' in screenAdapter).toBe(false);
}
test('omitted setting preserves the adapter default without injecting a cap', () => {
new Screen().init();
expect(adapter.init.mock.calls[0][0]).not.toHaveProperty('maxDevicePixelRatio');
expect(warnSpy).not.toHaveBeenCalled();
});
test.each([null, undefined])('treats %s as the platform default', value => {
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', value);
new Screen().init();
expect(adapter.init.mock.calls[0][0]).not.toHaveProperty('maxDevicePixelRatio');
expect(warnSpy).not.toHaveBeenCalled();
});
test.each([
[MaxDPR.Performance, 1],
[MaxDPR.Balanced, 2],
[MaxDPR.Quality, 4],
])('passes public preset %s as the serialized numeric cap %s', async (preset, expected) => {
await startupSettings.init('', { screen: { maxDevicePixelRatio: preset } });
expect(adapter.init).not.toHaveBeenCalled();
new Screen().init();
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(expected);
expect(adapter.maxDevicePixelRatio).toBe(expected);
});
test.each([2.5, 3.25])('continues to accept custom cap %s outside the presets', maximum => {
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', maximum);
new Screen().init();
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(maximum);
});
test('reads an exported screen setting', () => {
// Simulate the settings.json data loaded by Settings.init.
Object.assign(startupSettings, { _settings: { screen: { maxDevicePixelRatio: 2.5 } } });
new Screen().init();
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(2.5);
});
test('code overrides take priority without discarding other exported settings', async () => {
Object.assign(startupSettings, {
_settings: {
screen: { maxDevicePixelRatio: 2, exactFitScreen: false, orientation: 'landscape' },
rendering: { renderMode: 3 },
},
});
await startupSettings.init('', { screen: { maxDevicePixelRatio: MaxDPR.Quality } });
new Screen().init();
expect(adapter.init.mock.calls[0][0]).toEqual({
exactFitScreen: false, configOrientation: 'landscape', isHeadlessMode: true, maxDevicePixelRatio: 4,
});
});
test('a null code override clears an exported cap and retains the default strategy', async () => {
Object.assign(startupSettings, { _settings: { screen: { maxDevicePixelRatio: 4 } } });
await startupSettings.init('', { screen: { maxDevicePixelRatio: null } });
new Screen().init();
expect(adapter.init.mock.calls[0][0]).not.toHaveProperty('maxDevicePixelRatio');
});
test('a post-base startup delegate can override the setting before Screen.init', async () => {
await startupSettings.init('', { screen: { maxDevicePixelRatio: 2 } });
const startupDelegate = new AsyncDelegate();
startupDelegate.add(() => {
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', 3.25);
});
await Promise.resolve().then(() => startupDelegate.dispatch()).then(() => new Screen().init());
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(3.25);
});
test.each([0, -1, 0.5, NaN, Infinity, -Infinity, '3', false, {}, []])('forwards %s unchanged and propagates PAL validation errors', value => {
const validationError = new RangeError(debug.getError(9204));
initSpy.mockImplementation(() => { throw validationError; });
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', value);
let caught: unknown;
try { new Screen().init(); } catch (error) { caught = error; }
expect(caught).toBe(validationError);
expect(adapter.init).toHaveBeenCalledTimes(1);
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(value);
expect(adapter.maxDevicePixelRatio).toBeNull();
});
test('changing Settings after initialization does not reconfigure PAL', () => {
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', 3.25);
new Screen().init();
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', 4);
expect(settings.querySettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio')).toBe(4);
expect(adapter.init).toHaveBeenCalledTimes(1);
expect(adapter.maxDevicePixelRatio).toBe(3.25);
});
test('allows adapters without the DPR capability to ignore the setting', () => {
useAdapterWithoutDprCapability();
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', 3);
expect(() => new Screen().init()).not.toThrow();
expect(adapter.init).toHaveBeenCalledTimes(1);
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(3);
expect(warnSpy).not.toHaveBeenCalled();
});
test('default startup does not require a configured cap readback', () => {
adapter.maxDevicePixelRatio = undefined;
expect(() => new Screen().init()).not.toThrow();
});
test('rejects PAL that advertises properties but ignores the setting', () => {
adapter.init.mockImplementation(() => {});
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', 3);
expect(() => new Screen().init()).toThrow(debug.getError(9205));
});
test.each([
['non-HTML5', { HTML5: false }],
['Native', { NATIVE: true }],
['mini game', { MINIGAME: true }],
['runtime-based mini game', { RUNTIME_BASED: true }],
['Node.js', { NODEJS: true }],
])('passes the startup cap to a supporting PAL on %s without platform filtering', async (_name, overrides) => {
Object.assign(flags, overrides);
const originalDpr = new Screen().devicePixelRatio;
await startupSettings.init('', { screen: { maxDevicePixelRatio: 3.25 } });
const screen = new Screen();
expect(() => screen.init()).not.toThrow();
expect(warnSpy).not.toHaveBeenCalled();
expect(screen.devicePixelRatio).toBe(originalDpr);
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBe(3.25);
expect(adapter.maxDevicePixelRatio).toBe(3.25);
});
test('does not warn for an unconfigured non-Web platform', () => {
flags.NATIVE = true;
new Screen().init();
expect(warnSpy).not.toHaveBeenCalled();
expect(adapter.init.mock.calls[0][0]).not.toHaveProperty('maxDevicePixelRatio');
});
test('an unsupported PAL can ignore invalid input without engine validation or warnings', () => {
flags.NATIVE = true;
useAdapterWithoutDprCapability();
startupSettings.overrideSettings(SettingsCategory.SCREEN, 'maxDevicePixelRatio', NaN);
expect(() => new Screen().init()).not.toThrow();
expect(adapter.init.mock.calls[0][0].maxDevicePixelRatio).toBeNaN();
expect(warnSpy).not.toHaveBeenCalled();
});
});
+5
View File
@@ -0,0 +1,5 @@
{
"constantOverrides": {
"USE_MESHOPT": false
}
}