Files
cocos4/cocos/core/game.ts
T
Yun Hsiao Wu 32598c25cb switch to eslint (#7727)
* switch to eslint

* eslint: extends airbnb
2020-11-09 10:19:12 +08:00

1027 lines
35 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module core
*/
import { ALIPAY, EDITOR, JSB, PREVIEW, RUNTIME_BASED, BUILD } from 'internal:constants';
import { default as assetManager, IAssetManagerOptions } from './asset-manager/asset-manager';
import { EventTarget } from './event/event-target';
import * as debug from './platform/debug';
import inputManager from './platform/event-manager/input-manager';
import { Device, DeviceInfo } from './gfx';
import { sys } from './platform/sys';
import { macro } from './platform/macro';
import { ICustomJointTextureLayout } from './renderer/models';
import { legacyCC, VERSION } from './global-exports';
import { IPhysicsConfig } from '../physics/framework/physics-config';
import { bindingMappingInfo } from './pipeline/define';
import { SplashScreen } from './splash-screen';
import { RenderPipeline } from './pipeline';
import { Node } from './scene-graph/node';
interface ISceneInfo {
url: string;
uuid: string;
}
/**
* @zh
* 游戏配置。
* @en
* Game configuration.
*/
export interface IGameConfig {
/**
* @zh
* 设置 debug 模式,在浏览器中这个选项会被忽略。
* 各种设置选项的意义:
* - 0 - 没有消息被打印出来。
* - 1 - `error`,`assert`,`warn`,`log` 将打印在 console 中。
* - 2 - `error`,`assert`,`warn` 将打印在 console 中。
* - 3 - `error`,`assert` 将打印在 console 中。
* - 4 - `error`,`assert`,`warn`,`log` 将打印在 canvas 中(仅适用于 web 端)。
* - 5 - `error`,`assert`,`warn` 将打印在 canvas 中(仅适用于 web 端)。
* - 6 - `error`,`assert` 将打印在 canvas 中(仅适用于 web 端)。
* @en
* Set debug mode, only valid in non-browser environment.
* Possible values:
* 0 - No message will be printed.
* 1 - `error`,`assert`,`warn`,`log` will print in console.
* 2 - `error`,`assert`,`warn` will print in console.
* 3 - `error`,`assert` will print in console.
* 4 - `error`,`assert`,`warn`,`log` will print on canvas, available only on web.
* 5 - `error`,`assert`,`warn` will print on canvas, available only on web.
* 6 - `error`,`assert` will print on canvas, available only on web.
*/
debugMode?: debug.DebugMode;
/**
* @zh
* 当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。
* @en
* Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.
*/
showFPS?: boolean;
/**
* @zh
* 暴露类名让 Chrome DevTools 可以识别,如果开启会稍稍降低类的创建过程的性能,但对对象构造没有影响。
* @en
* Expose class name to chrome debug tools, the class intantiate performance is a little bit slower when exposed.
*/
exposeClassName?: boolean;
/**
* @zh
* 设置想要的帧率你的游戏,但真正的FPS取决于你的游戏实现和运行环境。
* @en
* Set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.
*/
frameRate?: number;
/**
* @zh
* Web 页面上的 Canvas Element ID,仅适用于 web 端。
* @en
* Sets the id of your canvas element on the web page, it's useful only on web.
*/
id?: string | HTMLElement;
/**
* @zh
* 渲染模式。
* 设置渲染器类型,仅适用于 web 端:
* - 0 - 通过引擎自动选择。
* - 1 - 强制使用 canvas 渲染。
* - 2 - 强制使用 WebGL 渲染,但是在部分 Android 浏览器中这个选项会被忽略。
* @en
* Sets the renderer type, only useful on web:
* - 0 - Automatically chosen by engine.
* - 1 - Forced to use canvas renderer.
* - 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers.
*/
renderMode?: 0 | 1 | 2;
/**
* @zh
* 当前包中可用场景。
* @en
* Include available scenes in the current bundle.
*/
scenes?: ISceneInfo[];
/**
* For internal use.
*/
registerSystemEvent?: boolean;
/**
* For internal use.
*/
collisionMatrix?: never[];
/**
* For internal use.
*/
groupList?: any[];
/**
* For internal use.
*/
jsList?: string[];
/**
* Render pipeline resources
*/
renderPipeline?: string;
/**
* Asset Manager initialization options
*/
assetOptions?: IAssetManagerOptions;
/**
* GPU instancing options
*/
customJointTextureLayouts?: ICustomJointTextureLayout[];
/**
* Physics system config
*/
physics?: IPhysicsConfig;
}
/**
* @en An object to boot the game.
* @zh 包含游戏主体信息并负责驱动游戏的游戏对象。
*/
export class Game extends EventTarget {
/**
* @en Event triggered when game hide to background.<br>
* Please note that this event is not 100% guaranteed to be fired on Web platform,<br>
* on native platforms, it corresponds to enter background event, os status bar or notification center may not trigger this event.
* @zh 游戏进入后台时触发的事件。<br>
* 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。<br>
* 在原生平台,它对应的是应用被切换到后台事件,下拉菜单和上拉状态栏等不一定会触发这个事件,这取决于系统行为。
* @example
* ```ts
* import { game, audioEngine } from 'cc';
* game.on(Game.EVENT_HIDE, function () {
* audioEngine.pauseMusic();
* audioEngine.pauseAllEffects();
* });
* ```
*/
public static EVENT_HIDE = 'game_on_hide';
/**
* @en Event triggered when game back to foreground<br>
* Please note that this event is not 100% guaranteed to be fired on Web platform,<br>
* on native platforms, it corresponds to enter foreground event.
* @zh 游戏进入前台运行时触发的事件。<br>
* 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。<br>
* 在原生平台,它对应的是应用被切换到前台事件。
*/
public static readonly EVENT_SHOW: string = 'game_on_show';
/**
* @en Event triggered when system in low memory status.<br>
* This event is only triggered on native iOS/Android platform.
* @zh 程序在内存不足时触发的事件。<br>
* 该事件只会在 iOS/Android 平台触发。
*/
public static readonly EVENT_LOW_MEMORY: string = 'game_on_low_memory';
/**
* @en Event triggered after game inited, at this point all engine objects and game scripts are loaded
* @zh 游戏启动后的触发事件,此时加载所有的引擎对象和游戏脚本。
*/
public static EVENT_GAME_INITED = 'game_inited';
/**
* @en Event triggered after engine inited, at this point you will be able to use all engine classes.<br>
* It was defined as EVENT_RENDERER_INITED in cocos creator v1.x and renamed in v2.0.
* In cocos creator 3d, EVENT_RENDERER_INITED is a new event, look up define for details.
* @zh 在引擎初始化之后触发的事件,此时您能够使用引擎所有的类。<br>
* 它在 cocos creator v1.x 版本中名字为 EVENT_RENDERER_INITED ,在 v2.0 版本中更名为 EVENT_ENGINE_INITED
* 并在 cocos creator 3d 版本中将 EVENT_RENDERER_INITED 用作为渲染器初始化的事件。
*/
public static EVENT_ENGINE_INITED = 'engine_inited';
/**
* @en Event triggered after renderer inited, at this point you will be able to use all gfx renderer feature.<br>
* @zh 在渲染器初始化之后触发的事件,此事件在 EVENT_ENGINE_INITED 之前触发,此时开始可使用 gfx 渲染框架。
*/
public static readonly EVENT_RENDERER_INITED: string = 'renderer_inited';
/**
* @en Event triggered when game restart
* @zh 调用restart后,触发事件
*/
public static EVENT_RESTART = 'game_on_restart';
/**
* @en Web Canvas 2d API as renderer backend.
* @zh 使用 Web Canvas 2d API 作为渲染器后端。
*/
public static RENDER_TYPE_CANVAS = 0;
/**
* @en WebGL API as renderer backend.
* @zh 使用 WebGL API 作为渲染器后端。
*/
public static RENDER_TYPE_WEBGL = 1;
/**
* @en OpenGL API as renderer backend.
* @zh 使用 OpenGL API 作为渲染器后端。
*/
public static RENDER_TYPE_OPENGL = 2;
/**
* @en The outer frame of the game canvas; parent of game container.
* @zh 游戏画布的外框,container 的父容器。
*/
public frame: Record<string, unknown> | null = null;
/**
* @en The container of game canvas.
* @zh 游戏画布的容器。
*/
public container: HTMLDivElement | null = null;
/**
* @en The canvas of the game.
* @zh 游戏的画布。
*/
public canvas: HTMLCanvasElement | null = null;
/**
* @en The renderer backend of the game.
* @zh 游戏的渲染器类型。
*/
public renderType = -1;
public eventTargetOn = super.on;
public eventTargetOnce = super.once;
/**
* @en
* The current game configuration,
* please be noticed any modification directly on this object after the game initialization won't take effect.
* @zh
* 当前的游戏配置
* 注意:请不要直接修改这个对象,它不会有任何效果。
*/
public config: NormalizedGameConfig = {} as NormalizedGameConfig;
/**
* @en Callback when the scripts of engine have been load.
* @zh 当引擎完成启动后的回调函数。
* @method onStart
*/
public onStart: Game.OnStart | null = null;
/**
* @en Indicates whether the engine has inited
* @zh 引擎是否以完成初始化
*/
public get inited () {
return this._inited;
}
public get frameTime () {
return this._frameTime;
}
public _persistRootNodes = {};
// states
public _paused = true; // whether the game is paused
public _configLoaded = false; // whether config loaded
public _isCloning = false; // deserializing or instantiating
public _inited = false; // whether the engine has inited
public _rendererInitialized = false;
public _gfxDevice: Device | null = null;
public _intervalId: number | null = null; // interval target of main
public declare _lastTime: number;
public declare _frameTime: number;
public collisionMatrix = [];
public groupList: any[] = [];
// @Methods
// @Game play control
/**
* @en Set frame rate of game.
* @zh 设置游戏帧率。
* @param {Number} frameRate
*/
public setFrameRate (frameRate: number) {
const config = this.config;
if (typeof frameRate !== 'number') {
frameRate = parseInt(frameRate);
if (isNaN(frameRate)) {
frameRate = 60;
}
}
config.frameRate = frameRate;
this._paused = true;
this._setAnimFrame();
this._runMainLoop();
}
/**
* @en Get frame rate set for the game, it doesn't represent the real frame rate.
* @zh 获取设置的游戏帧率(不等同于实际帧率)。
* @return frame rate
*/
public getFrameRate (): number {
return this.config.frameRate || 0;
}
/**
* @en Run the game frame by frame.
* @zh 执行一帧游戏循环。
*/
public step () {
legacyCC.director.mainLoop();
}
/**
* @en Pause the game main loop. This will pause:<br>
* game logic execution, rendering process, event manager, background music and all audio effects.<br>
* This is different with `director.pause` which only pause the game logic execution.<br>
* @zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 `director.pause` 不同。
*/
public pause () {
if (this._paused) { return; }
this._paused = true;
// Pause main loop
if (this._intervalId) {
window.cAF(this._intervalId);
this._intervalId = 0;
}
// Because runtime platforms never actually stops the swap chain,
// we draw some more frames here to (try to) make sure swap chain consistency
if (RUNTIME_BASED || ALIPAY) {
let swapbuffers = 3;
const cb = () => {
if (--swapbuffers > 1) {
window.rAF(cb);
}
const root = legacyCC.director.root;
root.frameMove(0); root.device.present();
};
window.rAF(cb);
}
}
/**
* @en Resume the game from pause. This will resume:<br>
* game logic execution, rendering process, event manager, background music and all audio effects.<br>
* @zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。
*/
public resume () {
if (!this._paused) { return; }
this._paused = false;
// Resume main loop
this._runMainLoop();
}
/**
* @en Check whether the game is paused.
* @zh 判断游戏是否暂停。
*/
public isPaused (): boolean {
return this._paused;
}
/**
* @en Restart game.
* @zh 重新开始游戏
*/
public restart (): Promise<void> {
const afterDrawPromise = new Promise<void>((resolve) =>
legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, () => resolve()) as void);
return afterDrawPromise.then(() => {
for (const id in this._persistRootNodes) {
this.removePersistRootNode(this._persistRootNodes[id]);
}
// Clear scene
legacyCC.director.getScene().destroy();
legacyCC.Object._deferredDestroy();
legacyCC.director.reset();
this.pause();
return this._setRenderPipelineNShowSplash().then(() => {
this.resume();
this._safeEmit(Game.EVENT_RESTART);
});
});
}
/**
* @en End game, it will close the game window
* @zh 退出游戏
*/
public end () {
if (this._gfxDevice) {
this._gfxDevice.destroy();
this._gfxDevice = null;
}
close();
}
/**
* @en
* Register an callback of a specific event type on the game object.<br>
* This type of event should be triggered via `emit`.<br>
* @zh
* 注册 game 的特定事件类型回调。这种类型的事件应该被 `emit` 触发。<br>
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.<br>
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
* @param once - After the first invocation, whether the callback should be unregistered.
* @return - Just returns the incoming callback so you can save the anonymous function easier.
*/
public on (type: string, callback: Function, target?: object, once?: boolean): any {
// Make sure EVENT_ENGINE_INITED callbacks to be invoked
if (this._inited && type === Game.EVENT_ENGINE_INITED) {
callback.call(target);
}
else {
this.eventTargetOn(type, callback, target, once);
}
}
/**
* @en
* Register an callback of a specific event type on the game object,<br>
* the callback will remove itself after the first time it is triggered.<br>
* @zh
* 注册 game 的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @param type - A string representing the event type to listen for.
* @param callback - The callback that will be invoked when the event is dispatched.<br>
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param target - The target (this object) to invoke the callback, can be null
*/
// @ts-expect-error
public once (type: string, callback: Function, target?: object) {
// Make sure EVENT_ENGINE_INITED callbacks to be invoked
if (this._inited && type === Game.EVENT_ENGINE_INITED) {
callback.call(target);
}
else {
this.eventTargetOnce(type, callback, target);
}
}
/**
* @en Init game with configuration object.
* @zh 使用指定的配置初始化引擎。
* @param config - Pass configuration object
*/
public init (config: IGameConfig) {
this._initConfig(config);
// Init assetManager
if (this.config.assetOptions) {
legacyCC.assetManager.init(this.config.assetOptions);
}
return this._initEngine().then(() => {
if (!EDITOR) {
this._initEvents();
}
legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts);
return this._inited;
});
}
/**
* @en Run game with configuration object and onStart function.
* @zh 运行游戏,并且指定引擎配置和 onStart 的回调。
* @param onStart - function to be executed after game initialized
*/
public run (onStart?: Game.OnStart): Promise<void>;
public run (configOrCallback?: Game.OnStart | IGameConfig, onStart?: Game.OnStart) {
if (!EDITOR) {
this._initEvents();
}
// To compatible with older version,
// we allow the `run(config, onstart?)` form. But it's deprecated.
let initPromise: Promise<boolean> | undefined;
if (typeof configOrCallback !== 'function' && configOrCallback) {
initPromise = this.init(configOrCallback);
this.onStart = onStart ?? null;
} else {
this.onStart = configOrCallback ?? null;
}
return Promise.resolve(initPromise).then(() => {
this._setAnimFrame();
this._runMainLoop();
// register system events
if (!EDITOR && game.config.registerSystemEvent) {
inputManager.registerSystemEvent(game.canvas);
}
return this._setRenderPipelineNShowSplash();
});
}
// @ Persist root node section
/**
* @en
* Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.<br>
* The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect.
* @zh
* 声明常驻根节点,该节点不会在场景切换中被销毁。<br>
* 目标节点必须位于为层级的根节点,否则无效。
* @param node - The node to be made persistent
*/
public addPersistRootNode (node: Node) {
if (!legacyCC.Node.isNode(node) || !node.uuid) {
debug.warnID(3800);
return;
}
const id = node.uuid;
if (!this._persistRootNodes[id]) {
const scene = legacyCC.director._scene;
if (legacyCC.isValid(scene)) {
if (!node.parent) {
node.parent = scene;
}
else if (!(node.parent instanceof legacyCC.Scene)) {
debug.warnID(3801);
return;
}
else if (node.parent !== scene) {
debug.warnID(3802);
return;
}
}
this._persistRootNodes[id] = node;
node._persistNode = true;
legacyCC.assetManager._releaseManager._addPersistNodeRef(node);
}
}
/**
* @en Remove a persistent root node.
* @zh 取消常驻根节点。
* @param node - The node to be removed from persistent node list
*/
public removePersistRootNode (node: { uuid: string; _persistNode: boolean; }) {
const id = node.uuid || '';
if (node === this._persistRootNodes[id]) {
delete this._persistRootNodes[id];
node._persistNode = false;
legacyCC.assetManager._releaseManager._removePersistNodeRef(node);
}
}
/**
* @en Check whether the node is a persistent root node.
* @zh 检查节点是否是常驻根节点。
* @param node - The node to be checked
*/
public isPersistRootNode (node: { _persistNode: any; }): boolean {
return node._persistNode;
}
// @Engine loading
private _initEngine () {
this._initDevice();
return Promise.resolve(legacyCC.director._init()).then(() => {
// Log engine version
debug.log(`Cocos Creator 3D v${VERSION}`);
this.emit(Game.EVENT_ENGINE_INITED);
this._inited = true;
});
}
// @Methods
// @Time ticker section
private _setAnimFrame () {
this._lastTime = performance.now();
const frameRate = this.config.frameRate;
this._frameTime = 1000 / frameRate;
if (JSB || RUNTIME_BASED) {
// @ts-expect-error
jsb.setPreferredFramesPerSecond(frameRate);
window.rAF = window.requestAnimationFrame;
window.cAF = window.cancelAnimationFrame;
}
else {
if (this._intervalId) {
window.cAF(this._intervalId);
this._intervalId = 0;
}
const rAF = window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if (frameRate !== 60 && frameRate !== 30) {
// @ts-expect-error
window.rAF = rAF ? this._stTimeWithRAF : this._stTime;
window.cAF = this._ctTime;
}
else {
window.rAF = rAF || this._stTime;
window.cAF = window.cancelAnimationFrame ||
window.cancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.ocancelAnimationFrame ||
this._ctTime;
}
}
}
private _stTimeWithRAF (callback) {
const currTime = performance.now();
const elapseTime = Math.max(0, (currTime - game._lastTime));
const timeToCall = Math.max(0, game._frameTime - elapseTime);
const id = window.setTimeout(() => {
window.requestAnimationFrame(callback);
}, timeToCall);
game._lastTime = currTime + timeToCall;
return id;
}
private _stTime (callback) {
const currTime = performance.now();
const elapseTime = Math.max(0, (currTime - game._lastTime));
const timeToCall = Math.max(0, game._frameTime - elapseTime);
const id = window.setTimeout(callback, timeToCall);
game._lastTime = currTime + timeToCall;
return id;
}
private _ctTime (id: number | undefined) {
window.clearTimeout(id);
}
// Run game.
private _runMainLoop () {
if (EDITOR && !legacyCC.GAME_VIEW) {
return;
}
const config = this.config;
const director = legacyCC.director;
let skip = true;
const frameRate = config.frameRate;
debug.setDisplayStats(!!config.showFPS);
director.startAnimation();
const callback = (time: number) => {
if (this._paused) { return; }
this._intervalId = window.rAF(callback);
if (!JSB && !RUNTIME_BASED && frameRate === 30) {
skip = !skip;
if (skip) {
return;
}
}
director.mainLoop(time);
};
if (this._intervalId) {
window.cAF(this._intervalId);
this._intervalId = 0;
}
this._intervalId = window.rAF(callback);
this._paused = false;
}
// @Game loading section
private _initConfig (config: IGameConfig) {
// Configs adjustment
if (typeof config.debugMode !== 'number') {
config.debugMode = debug.DebugMode.NONE;
}
config.exposeClassName = !!config.exposeClassName;
if (typeof config.frameRate !== 'number') {
config.frameRate = 60;
}
const renderMode = config.renderMode;
if (typeof renderMode !== 'number' || renderMode > 2 || renderMode < 0) {
config.renderMode = 0;
}
if (typeof config.registerSystemEvent !== 'boolean') {
config.registerSystemEvent = true;
}
config.showFPS = !!config.showFPS;
// Collide Map and Group List
this.collisionMatrix = config.collisionMatrix || [];
this.groupList = config.groupList || [];
debug._resetDebugSetting(config.debugMode);
this.config = config as NormalizedGameConfig;
this._configLoaded = true;
}
private _determineRenderType () {
const config = this.config;
const userRenderMode = parseInt(config.renderMode as any);
// Determine RenderType
this.renderType = Game.RENDER_TYPE_CANVAS;
let supportRender = false;
if (userRenderMode === 0) {
if (legacyCC.sys.capabilities.opengl) {
this.renderType = Game.RENDER_TYPE_WEBGL;
supportRender = true;
}
else if (legacyCC.sys.capabilities.canvas) {
this.renderType = Game.RENDER_TYPE_CANVAS;
supportRender = true;
}
}
else if (userRenderMode === 1 && legacyCC.sys.capabilities.canvas) {
this.renderType = Game.RENDER_TYPE_CANVAS;
supportRender = true;
}
else if (userRenderMode === 2 && legacyCC.sys.capabilities.opengl) {
this.renderType = Game.RENDER_TYPE_WEBGL;
supportRender = true;
}
if (!supportRender) {
throw new Error(debug.getError(3820, userRenderMode));
}
}
private _initDevice () {
// Avoid setup to be called twice.
if (this._rendererInitialized) { return; }
this.canvas = (this.config as any).adapter.canvas;
this.frame = (this.config as any).adapter.frame;
this.container = (this.config as any).adapter.container;
this._determineRenderType();
// WebGL context created successfully
if (this.renderType === Game.RENDER_TYPE_WEBGL) {
const ctors: Constructor<Device>[] = [];
if (JSB && window.gfx) {
if (gfx.CCVKDevice) { ctors.push(gfx.CCVKDevice); }
if (gfx.CCMTLDevice) { ctors.push(gfx.CCMTLDevice); }
if (gfx.GLES3Device) { ctors.push(gfx.GLES3Device); }
if (gfx.GLES2Device) { ctors.push(gfx.GLES2Device); }
} else {
let useWebGL2 = (!!window.WebGL2RenderingContext);
const userAgent = window.navigator.userAgent.toLowerCase();
if (userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1
|| sys.browserType === sys.BROWSER_TYPE_UC // UC browser implementation doesn't not conform to WebGL2 standard
) {
useWebGL2 = false;
}
if (useWebGL2 && legacyCC.WebGL2Device) {
ctors.push(legacyCC.WebGL2Device);
}
if (legacyCC.WebGLDevice) {
ctors.push(legacyCC.WebGLDevice);
}
}
const opts = new DeviceInfo(
this.canvas as HTMLCanvasElement,
EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
false,
window.devicePixelRatio,
Math.floor(screen.width * window.devicePixelRatio),
Math.floor(screen.height * window.devicePixelRatio),
bindingMappingInfo,
);
for (let i = 0; i < ctors.length; i++) {
this._gfxDevice = new ctors[i]();
if (this._gfxDevice.initialize(opts)) { break; }
}
}
if (!this._gfxDevice) {
// todo fix here for wechat game
debug.error('can not support canvas rendering in 3D');
this.renderType = Game.RENDER_TYPE_CANVAS;
return;
}
this.canvas!.oncontextmenu = () => {
if (!legacyCC._isContextMenuEnable) { return false; }
};
}
private _initEvents () {
const win = window;
let hiddenPropName: string;
if (typeof document.hidden !== 'undefined') {
hiddenPropName = 'hidden';
} else if (typeof document.mozHidden !== 'undefined') {
hiddenPropName = 'mozHidden';
} else if (typeof document.msHidden !== 'undefined') {
hiddenPropName = 'msHidden';
} else if (typeof document.webkitHidden !== 'undefined') {
hiddenPropName = 'webkitHidden';
}
let hidden = false;
const me = this;
function onHidden () {
if (!hidden) {
hidden = true;
me.emit(Game.EVENT_HIDE);
}
}
// In order to adapt the most of platforms the onshow API.
function onShown (arg0?, arg1?, arg2?, arg3?, arg4?) {
if (hidden) {
hidden = false;
me.emit(Game.EVENT_SHOW, arg0, arg1, arg2, arg3, arg4);
}
}
if (hiddenPropName!) {
const changeList = [
'visibilitychange',
'mozvisibilitychange',
'msvisibilitychange',
'webkitvisibilitychange',
'qbrowserVisibilityChange',
];
for (let i = 0; i < changeList.length; i++) {
document.addEventListener(changeList[i], (event) => {
let visible = document[hiddenPropName];
// QQ App
// @ts-expect-error
visible = visible || event.hidden;
if (visible) {
onHidden();
}
else {
onShown();
}
});
}
} else {
win.addEventListener('blur', onHidden);
win.addEventListener('focus', onShown);
}
if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) {
win.onfocus = onShown;
}
if ('onpageshow' in window && 'onpagehide' in window) {
win.addEventListener('pagehide', onHidden);
win.addEventListener('pageshow', onShown);
// Taobao UIWebKit
document.addEventListener('pagehide', onHidden);
document.addEventListener('pageshow', onShown);
}
this.on(Game.EVENT_HIDE, () => {
this.pause();
});
this.on(Game.EVENT_SHOW, () => {
this.resume();
});
}
private _setRenderPipelineNShowSplash () {
return Promise.resolve(this._setupRenderPipeline()).then(() => {
this._safeEmit(Game.EVENT_GAME_INITED);
return Promise.resolve(this._showSplashScreen()).then(() => {
if (this.onStart) {
this.onStart();
}
});
});
}
private _setupRenderPipeline () {
const { renderPipeline } = this.config;
if (!renderPipeline) {
this._setRenderPipeline();
} else {
return new Promise<RenderPipeline>((resolve, reject) => {
legacyCC.assetManager.loadAny(renderPipeline, (err, asset) => {
return (err || !(asset instanceof RenderPipeline)) ? reject(err) : resolve(asset);
});
}).then((asset) => {
this._setRenderPipeline(asset);
}).catch((reason) => {
debug.warn(reason);
debug.warn(`Failed load render pipeline: ${renderPipeline}, engine failed to initialize, will fallback to default pipeline`);
this._setRenderPipeline();
});
}
}
private _showSplashScreen () {
if (!EDITOR && !PREVIEW && legacyCC.internal.SplashScreen) {
const splashScreen = legacyCC.internal.SplashScreen.instance as SplashScreen;
splashScreen.main(legacyCC.director.root);
return new Promise<void>((resolve) => {
splashScreen.setOnFinish(() => resolve());
splashScreen.loadFinish = true;
});
}
}
private _setRenderPipeline (rppl?: RenderPipeline) {
if (!legacyCC.director.root.setRenderPipeline(rppl)) {
this._setRenderPipeline();
}
this._rendererInitialized = true;
this._safeEmit(Game.EVENT_RENDERER_INITED);
}
private _safeEmit (event) {
if (EDITOR) {
try {
this.emit(event);
} catch (e) {
debug.warn(e);
}
} else {
this.emit(event);
}
}
}
export declare namespace Game {
export type OnStart = () => void;
}
legacyCC.Game = Game;
/**
* @en
* This is a Game instance.
* @zh
* 这是一个 Game 类的实例,包含游戏主体信息并负责驱动游戏的游戏对象。
*/
export const game = legacyCC.game = new Game();
type NormalizedGameConfig = IGameConfig & {
frameRate: NonNullable<IGameConfig['frameRate']>;
};