diff --git a/cocos/core/game.js b/cocos/core/game.js index 3daeb900c9..636e2b6157 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -26,7 +26,7 @@ import EventTarget from './event/event-target'; import inputManager from './platform/event-manager/CCInputManager'; -import debug from './platform/CCDebug'; +import * as debug from './platform/CCDebug'; import { addon } from './utils/js'; /** diff --git a/cocos/core/platform/CCDebug.js b/cocos/core/platform/CCDebug.js deleted file mode 100644 index 47dbbcfa21..0000000000 --- a/cocos/core/platform/CCDebug.js +++ /dev/null @@ -1,382 +0,0 @@ -/**************************************************************************** - Copyright (c) 2018 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. - ****************************************************************************/ - -import * as debugInfos from '../../../DebugInfos'; -const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; - -// the html element displays log in web page (DebugMode.INFO_FOR_WEB_PAGE) -let logList; - -/** - * @module cc - */ - -cc.log = cc.warn = cc.error = cc.assert = console.log; - -let _resetDebugSetting = function (mode) { - // reset - cc.log = cc.warn = cc.error = cc.assert = function () {}; - - if (mode === DebugMode.NONE) - return; - - if (mode > DebugMode.ERROR) { - //log to web page - - function logToWebPage (msg) { - if (!cc.game.canvas) - return; - - if (!logList) { - var logDiv = document.createElement("Div"); - logDiv.setAttribute("id", "logInfoDiv"); - logDiv.setAttribute("width", "200"); - logDiv.setAttribute("height", cc.game.canvas.height); - var logDivStyle = logDiv.style; - logDivStyle.zIndex = "99999"; - logDivStyle.position = "absolute"; - logDivStyle.top = logDivStyle.left = "0"; - - logList = document.createElement("textarea"); - logList.setAttribute("rows", "20"); - logList.setAttribute("cols", "30"); - logList.setAttribute("disabled", "true"); - var logListStyle = logList.style; - logListStyle.backgroundColor = "transparent"; - logListStyle.borderBottom = "1px solid #cccccc"; - logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = "0px"; - logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = "none"; - logListStyle.padding = "0px"; - logListStyle.margin = 0; - - logDiv.appendChild(logList); - cc.game.canvas.parentNode.appendChild(logDiv); - } - - logList.value = logList.value + msg + "\r\n"; - logList.scrollTop = logList.scrollHeight; - } - - cc.error = function () { - logToWebPage("ERROR : " + cc.js.formatStr.apply(null, arguments)); - }; - cc.assert = function (cond, msg) { - 'use strict'; - if (!cond && msg) { - msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments)); - logToWebPage("ASSERT: " + msg); - } - }; - if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) { - cc.warn = function () { - logToWebPage("WARN : " + cc.js.formatStr.apply(null, arguments)); - }; - } - if (mode === DebugMode.INFO_FOR_WEB_PAGE) { - cc.log = function () { - logToWebPage(cc.js.formatStr.apply(null, arguments)); - }; - } - } - else if (console && console.log.apply) {//console is null when user doesn't open dev tool on IE9 - //log to console - - // For JSB - if (!console.error) console.error = console.log; - if (!console.warn) console.warn = console.log; - - /** - * !#en - * Outputs an error message to the Cocos Creator Console (editor) or Web Console (runtime).
- * - In Cocos Creator, error is red.
- * - In Chrome, error have a red icon along with red message text.
- * !#zh - * 输出错误消息到 Cocos Creator 编辑器的 Console 或运行时页面端的 Console 中。
- * - 在 Cocos Creator 中,错误信息显示是红色的。
- * - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。
- * - * @method error - * @param {any} msg - A JavaScript string containing zero or more substitution strings. - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - */ - if (CC_EDITOR) { - cc.error = Editor.error; - } - else if (console.error.bind) { - // use bind to avoid pollute call stacks - cc.error = console.error.bind(console); - } - else { - cc.error = CC_JSB ? console.error : function () { - return console.error.apply(console, arguments); - }; - } - cc.assert = function (cond, msg) { - if (!cond) { - if (msg) { - msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments)); - } - if (CC_DEV) { - debugger; - } - if (CC_TEST) { - ok(false, msg); - } - else { - throw new Error(msg); - } - } - } - } - if (mode !== DebugMode.ERROR) { - /** - * !#en - * Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). - * - In Cocos Creator, warning is yellow. - * - In Chrome, warning have a yellow warning icon with the message text. - * !#zh - * 输出警告消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。
- * - 在 Cocos Creator 中,警告信息显示是黄色的。
- * - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。
- * @method warn - * @param {any} msg - A JavaScript string containing zero or more substitution strings. - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - */ - if (CC_EDITOR) { - cc.warn = Editor.warn; - } - else if (console.warn.bind) { - // use bind to avoid pollute call stacks - cc.warn = console.warn.bind(console); - } - else { - cc.warn = CC_JSB ? console.warn : function () { - return console.warn.apply(console, arguments); - }; - } - } - if (CC_EDITOR) { - cc.log = Editor.log; - } - else if (mode === DebugMode.INFO) { - /** - * !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). - * !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 - * @method log - * @param {String|any} msg - A JavaScript string containing zero or more substitution strings. - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - */ - if (CC_JSB) { - if (scriptEngineType === "JavaScriptCore") { - // console.log has to use `console` as its context for iOS 8~9. Therefore, apply it. - cc.log = function () { - return console.log.apply(console, arguments); - }; - } else { - cc.log = console.log; - } - } - else if (console.log.bind) { - // use bind to avoid pollute call stacks - cc.log = console.log.bind(console); - } - else { - cc.log = function () { - return console.log.apply(console, arguments); - }; - } - } -}; - -cc._throw = CC_EDITOR ? Editor.error : function (error) { - var stack = error.stack; - if (stack) { - cc.error(CC_JSB ? (error + '\n' + stack) : stack); - } - else { - cc.error(error); - } -}; - -function getTypedFormatter (type) { - return function () { - var id = arguments[0]; - var msg = CC_DEBUG ? (debugInfos[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; - if (arguments.length === 1) { - return msg; - } - else if (arguments.length === 2) { - return CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : - msg + ' Arguments: ' + arguments[1]; - } - else { - var argsArray = cc.js.shiftArguments.apply(null, arguments); - return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : - msg + ' Arguments: ' + argsArray.join(', '); - } - }; -} - -var logFormatter = getTypedFormatter('Log'); -cc.logID = function () { - cc.log(logFormatter.apply(null, arguments)); -}; - -var warnFormatter = getTypedFormatter('Warning'); -cc.warnID = function () { - cc.warn(warnFormatter.apply(null, arguments)); -}; - -var errorFormatter = getTypedFormatter('Error'); -cc.errorID = function () { - cc.error(errorFormatter.apply(null, arguments)); -}; - -var assertFormatter = getTypedFormatter('Assert'); -cc.assertID = function (cond) { - 'use strict'; - if (cond) { - return; - } - cc.assert(false, assertFormatter.apply(null, cc.js.shiftArguments.apply(null, arguments))); -}; - -/** - * !#en An object to boot the game. - * !#zh 包含游戏主体信息并负责驱动游戏的游戏对象。 - * @class debug - * @main - * @static - */ - -/** - * !#en Enum for debug modes. - * !#zh 调试模式 - * @enum debug.DebugMode - * @memberof cc - */ -var DebugMode = cc.Enum({ - /** - * !#en The debug mode none. - * !#zh 禁止模式,禁止显示任何日志信息。 - * @property NONE - * @type {Number} - * @static - */ - NONE: 0, - /** - * !#en The debug mode info. - * !#zh 信息模式,在 console 中显示所有日志。 - * @property INFO - * @type {Number} - * @static - */ - INFO: 1, - /** - * !#en The debug mode warn. - * !#zh 警告模式,在 console 中只显示 warn 级别以上的(包含 error)日志。 - * @property WARN - * @type {Number} - * @static - */ - WARN: 2, - /** - * !#en The debug mode error. - * !#zh 错误模式,在 console 中只显示 error 日志。 - * @property ERROR - * @type {Number} - * @static - */ - ERROR: 3, - /** - * !#en The debug mode info for web page. - * !#zh 信息模式(仅 WEB 端有效),在画面上输出所有信息。 - * @property INFO_FOR_WEB_PAGE - * @type {Number} - * @static - */ - INFO_FOR_WEB_PAGE: 4, - /** - * !#en The debug mode warn for web page. - * !#zh 警告模式(仅 WEB 端有效),在画面上输出 warn 级别以上的(包含 error)信息。 - * @property WARN_FOR_WEB_PAGE - * @type {Number} - * @static - */ - WARN_FOR_WEB_PAGE: 5, - /** - * !#en The debug mode error for web page. - * !#zh 错误模式(仅 WEB 端有效),在画面上输出 error 信息。 - * @property ERROR_FOR_WEB_PAGE - * @type {Number} - * @static - */ - ERROR_FOR_WEB_PAGE: 6 -}); - -/** - * @module debug - */ -let debug = { - DebugMode: DebugMode, - - _resetDebugSetting, - - /** - * !#en Gets error message with the error id and possible parameters. - * !#zh 通过 error id 和必要的参数来获取错误信息。 - * @method getError - * @param {id} errorId - * @param {any} [param] - * @return {String} - */ - getError: errorFormatter, - - /** - * !#en Returns whether or not to display the FPS informations. - * !#zh 是否显示 FPS 信息。 - * @method isDisplayStats - * @return {Boolean} - */ - isDisplayStats: function () { - return cc.profiler ? cc.profiler.isShowingStats() : false; - }, - - /** - * !#en Sets whether display the FPS on the bottom-left corner. - * !#zh 设置是否在左下角显示 FPS。 - * @method setDisplayStats - * @param {Boolean} displayStats - */ - setDisplayStats: function (displayStats) { - if (cc.profiler) { - displayStats ? cc.profiler.showStats() : cc.profiler.hideStats(); - cc.game.config.showFPS = !!displayStats; - } - }, -} - -cc.debug = debug; -export default debug; diff --git a/cocos/core/platform/CCDebug.ts b/cocos/core/platform/CCDebug.ts new file mode 100644 index 0000000000..1ab51384f6 --- /dev/null +++ b/cocos/core/platform/CCDebug.ts @@ -0,0 +1,356 @@ +/**************************************************************************** + Copyright (c) 2018 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. + ****************************************************************************/ + +import * as debugInfos from '../../../DebugInfos'; +const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; + +// The html element displays log in web page (DebugMode.INFO_FOR_WEB_PAGE) +let logList: HTMLTextAreaElement | null = null; + +let ccLog = console.log; + +let ccWarn = console.log; + +let ccError = console.log; + +let ccAssert = console.log; + +function formatString (message?: any, ...optionalParams: any[]) { + return cc.js.formatStr.apply(null, [message].concat(optionalParams)); +} + +/** + * !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). + * !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 + * @param message - A JavaScript string containing zero or more substitution strings. + * @param optionalParams - JavaScript objects with which to replace substitution strings within msg. + * This gives you additional control over the format of the output. + */ +export function log (message?: any, ...optionalParams: any[]) { + return ccLog(message, ...optionalParams); +} + +/** + * !#en + * Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). + * - In Cocos Creator, warning is yellow. + * - In Chrome, warning have a yellow warning icon with the message text. + * !#zh + * 输出警告消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。
+ * - 在 Cocos Creator 中,警告信息显示是黄色的。
+ * - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。
+ * @param message - A JavaScript string containing zero or more substitution strings. + * @param optionalParams - JavaScript objects with which to replace substitution strings within msg. + * This gives you additional control over the format of the output. + */ +export function warn (message?: any, ...optionalParams: any[]) { + return ccWarn(message, ...optionalParams); +} + +/** + * !#en + * Outputs an error message to the Cocos Creator Console (editor) or Web Console (runtime).
+ * - In Cocos Creator, error is red.
+ * - In Chrome, error have a red icon along with red message text.
+ * !#zh + * 输出错误消息到 Cocos Creator 编辑器的 Console 或运行时页面端的 Console 中。
+ * - 在 Cocos Creator 中,错误信息显示是红色的。
+ * - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。
+ * @param message - A JavaScript string containing zero or more substitution strings. + * @param optionalParams - JavaScript objects with which to replace substitution strings within msg. + * This gives you additional control over the format of the output. + */ +export function error (message?: any, ...optionalParams: any[]) { + return ccError(message, ...optionalParams); +} + +export function assert (value: any, message?: string, ...optionalParams: any[]) { + return ccAssert(value, message, ...optionalParams); +} + +export function _resetDebugSetting (mode: DebugMode) { + // reset + ccLog = ccWarn = ccError = ccAssert = () => { + }; + + if (mode === DebugMode.NONE) { + return; + } + + if (mode > DebugMode.ERROR) { + // Log to web page. + const logToWebPage = (msg: string) => { + if (!cc.game.canvas) { + return; + } + + if (!logList) { + const logDiv = document.createElement('Div'); + logDiv.setAttribute('id', 'logInfoDiv'); + logDiv.setAttribute('width', '200'); + logDiv.setAttribute('height', cc.game.canvas.height); + const logDivStyle = logDiv.style; + logDivStyle.zIndex = '99999'; + logDivStyle.position = 'absolute'; + logDivStyle.top = logDivStyle.left = '0'; + + logList = document.createElement('textarea'); + logList.setAttribute('rows', '20'); + logList.setAttribute('cols', '30'); + logList.setAttribute('disabled', 'true'); + const logListStyle = logList.style; + logListStyle.backgroundColor = 'transparent'; + logListStyle.borderBottom = '1px solid #cccccc'; + logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = '0px'; + logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = 'none'; + logListStyle.padding = '0px'; + logListStyle.margin = '0px'; + + logDiv.appendChild(logList); + cc.game.canvas.parentNode.appendChild(logDiv); + } + + logList.value = logList.value + msg + '\r\n'; + logList.scrollTop = logList.scrollHeight; + }; + + ccError = (message?: any, ...optionalParams: any[]) => { + logToWebPage('ERROR : ' + formatString(message, ...optionalParams)); + }; + ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { + if (!condition) { + logToWebPage('ASSERT: ' + formatString(message, ...optionalParams)); + } + }; + if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) { + ccWarn = (message?: any, ...optionalParams: any[]) => { + logToWebPage('WARN : ' + formatString(message, ...optionalParams)); + }; + } + if (mode === DebugMode.INFO_FOR_WEB_PAGE) { + ccLog = (message?: any, ...optionalParams: any[]) => { + logToWebPage(formatString(message, ...optionalParams)); + }; + } + } + else if (console && console.log.apply) {// console is null when user doesn't open dev tool on IE9 + // Log to console. + + // For JSB + if (!console.error) { + console.error = console.log; + } + if (!console.warn) { + console.warn = console.log; + } + + if (CC_EDITOR) { + ccError = Editor.error; + } + else if (console.error.bind) { + // use bind to avoid pollute call stacks + ccError = console.error.bind(console); + } + else { + ccError = CC_JSB ? console.error : (message?: any, ...optionalParams: any[]) => { + return console.error.apply(console, [message, ...optionalParams]); + }; + } + ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { + if (!condition) { + const errorText = formatString(message, ...optionalParams); + if (CC_DEV) { + debugger; + } + else { + throw new Error(errorText); + } + } + }; + } + + if (mode !== DebugMode.ERROR) { + if (CC_EDITOR) { + ccWarn = Editor.warn; + } + else if (console.warn.bind) { + // use bind to avoid pollute call stacks + ccWarn = console.warn.bind(console); + } + else { + ccWarn = CC_JSB ? console.warn : (message?: any, ...optionalParams: any[]) => { + return console.warn.apply(console, [message, ...optionalParams]); + }; + } + } + + if (CC_EDITOR) { + ccLog = Editor.log; + } + else if (mode === DebugMode.INFO) { + if (CC_JSB) { + if (scriptEngineType === 'JavaScriptCore') { + // console.log has to use `console` as its context for iOS 8~9. Therefore, apply it. + ccLog = (message?: any, ...optionalParams: any[]) => { + return console.log.apply(console, [message, ...optionalParams]); + }; + } else { + ccLog = console.log; + } + } + else if (console.log.bind) { + // use bind to avoid pollute call stacks + ccLog = console.log.bind(console); + } + else { + ccLog = (message?: any, ...optionalParams: any[]) => { + return console.log.apply(console, [message, ...optionalParams]); + }; + } + } +} + +export function _throw (error_: any) { + if (CC_EDITOR) { + // @ts-ignore + return Editor.error(error_); + } else { + const stack = error_.stack; + if (stack) { + error(CC_JSB ? (error_ + '\n' + stack) : stack); + } + else { + error(error_); + } + } +} + +function getTypedFormatter (type: 'Log' | 'Warning' | 'Error' | 'Assert') { + return (id: number, ...args: any[]) => { + const msg = CC_DEBUG ? (debugInfos[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; + if (args.length === 0) { + return msg; + } + return CC_DEBUG ? formatString(msg, ...args) : msg + ' Arguments: ' + args.join(', '); + }; +} + +const logFormatter = getTypedFormatter('Log'); +export function logID (id: number, ...optionalParams: any[]) { + log(logFormatter(id, ...optionalParams)); +} + +const warnFormatter = getTypedFormatter('Warning'); +export function warnID (id: number, ...optionalParams: any[]) { + warn(warnFormatter(id, ...optionalParams)); +} + +const errorFormatter = getTypedFormatter('Error'); +export function errorID (id: number, ...optionalParams: any[]) { + error(errorFormatter(id, ...optionalParams)); +} + +const assertFormatter = getTypedFormatter('Assert'); +export function assertID (condition: boolean, id: number, ...optionalParams: any[]) { + if (condition) { + return; + } + assert(false, assertFormatter(id, ...optionalParams)); +} + +/** + * !#en Enum for debug modes. + * !#zh 调试模式 + */ +export enum DebugMode { + /** + * !#en The debug mode none. + * !#zh 禁止模式,禁止显示任何日志信息。 + */ + NONE = 0, + + /** + * !#en The debug mode info. + * !#zh 信息模式,在 console 中显示所有日志。 + */ + INFO = 1, + + /** + * !#en The debug mode warn. + * !#zh 警告模式,在 console 中只显示 warn 级别以上的(包含 error)日志。 + */ + WARN = 2, + + /** + * !#en The debug mode error. + * !#zh 错误模式,在 console 中只显示 error 日志。 + */ + ERROR = 3, + + /** + * !#en The debug mode info for web page. + * !#zh 信息模式(仅 WEB 端有效),在画面上输出所有信息。 + */ + INFO_FOR_WEB_PAGE = 4, + + /** + * !#en The debug mode warn for web page. + * !#zh 警告模式(仅 WEB 端有效),在画面上输出 warn 级别以上的(包含 error)信息。 + */ + WARN_FOR_WEB_PAGE = 5, + + /** + * !#en The debug mode error for web page. + * !#zh 错误模式(仅 WEB 端有效),在画面上输出 error 信息。 + */ + ERROR_FOR_WEB_PAGE = 6, +} + +/** + * !#en Gets error message with the error id and possible parameters. + * !#zh 通过 error id 和必要的参数来获取错误信息。 + */ +export function getError (errorId: any, param?: any): string { + return errorFormatter(errorId, param); +} + +/** + * !#en Returns whether or not to display the FPS informations. + * !#zh 是否显示 FPS 信息。 + */ +export function isDisplayStats (): boolean { + return cc.profiler ? cc.profiler.isShowingStats() : false; +} + +/** + * !#en Sets whether display the FPS on the bottom-left corner. + * !#zh 设置是否在左下角显示 FPS。 + */ +export function setDisplayStats (displayStats: boolean) { + if (cc.profiler) { + displayStats ? cc.profiler.showStats() : cc.profiler.hideStats(); + cc.game.config.showFPS = !!displayStats; + } +} diff --git a/cocos/core/utils/index.js b/cocos/core/utils/index.js index be47c5ca6e..3344201d5d 100644 --- a/cocos/core/utils/index.js +++ b/cocos/core/utils/index.js @@ -25,6 +25,11 @@ ****************************************************************************/ import * as js from './js'; + +/** + * !#en The module provides utilities for working with file and directory paths + * !#zh 用于处理文件与目录的路径的模块 + */ import * as path from './path'; export * from './prefab-helper'; diff --git a/cocos/core/utils/path.js b/cocos/core/utils/path.ts similarity index 50% rename from cocos/core/utils/path.js rename to cocos/core/utils/path.ts index cc92cdac2c..6b39216075 100644 --- a/cocos/core/utils/path.js +++ b/cocos/core/utils/path.ts @@ -28,25 +28,15 @@ const EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; const DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; const NORMALIZE_RE = /[^\.\/]+\/\.\.\//; -/** - * !#en The module provides utilities for working with file and directory paths - * !#zh 用于处理文件与目录的路径的模块 - * @class path - * @static - */ - /** * !#en Join strings to be a path. - * !#zh 拼接字符串为 Path - * @method join + * !#zh 拼接字符串为路径。 * @example {@link cocos2d/core/utils/CCPath/join.js} - * @returns {String} */ -export function join () { - let l = arguments.length; - let result = ""; - for (let i = 0; i < l; i++) { - result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); +export function join (...segments: string[]) { + let result = ''; + for (const segment of segments) { + result = (result + (result === '' ? '' : '/') + segment).replace(/(\/|\\\\)$/, ''); } return result; } @@ -54,29 +44,24 @@ export function join () { /** * !#en Get the ext name of a path including '.', like '.png'. * !#zh 返回 Path 的扩展名,包括 '.',例如 '.png'。 - * @method extname * @example {@link cocos2d/core/utils/CCPath/extname.js} - * @param {String} pathStr - * @returns {*} */ -export function extname (pathStr) { - let temp = EXTNAME_RE.exec(pathStr); +export function extname (path: string) { + const temp = EXTNAME_RE.exec(path); return temp ? temp[1] : ''; } /** - * !#en Get the main name of a file name - * !#zh 获取文件名的主名称 - * @method mainFileName - * @param {String} fileName - * @returns {String} + * !#en Get the main name of a file name. + * !#zh 获取文件名的主名称。 * @deprecated */ -export function mainFileName (fileName) { +export function mainFileName (fileName: string) { if (fileName) { - let idx = fileName.lastIndexOf("."); - if (idx !== -1) + const idx = fileName.lastIndexOf('.'); + if (idx !== -1) { return fileName.substring(0, idx); + } } return fileName; } @@ -84,110 +69,92 @@ export function mainFileName (fileName) { /** * !#en Get the file name of a file path. * !#zh 获取文件路径的文件名。 - * @method basename * @example {@link cocos2d/core/utils/CCPath/basename.js} - * @param {String} pathStr - * @param {String} [extname] - * @returns {*} */ -export function basename (pathStr, extname) { - let index = pathStr.indexOf("?"); - if (index > 0) pathStr = pathStr.substring(0, index); - let reg = /(\/|\\)([^\/\\]+)$/g; - let result = reg.exec(pathStr.replace(/(\/|\\)$/, "")); - if (!result) return null; - let baseName = result[2]; - if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) - return baseName.substring(0, baseName.length - extname.length); +export function basename (path: string, extName?: string) { + const index = path.indexOf('?'); + if (index > 0) { + path = path.substring(0, index); + } + const reg = /(\/|\\)([^\/\\]+)$/g; + const result = reg.exec(path.replace(/(\/|\\)$/, '')); + if (!result) { + return ''; + } + const baseName = result[2]; + if (extName && path.substring(path.length - extName.length).toLowerCase() === extName.toLowerCase()) { + return baseName.substring(0, baseName.length - extName.length); + } return baseName; } /** * !#en Get dirname of a file path. * !#zh 获取文件路径的目录名。 - * @method dirname * @example {@link cocos2d/core/utils/CCPath/dirname.js} - * @param {String} pathStr - * @returns {*} */ -export function dirname (pathStr) { - let temp = DIRNAME_RE.exec(pathStr); +export function dirname (path: string) { + const temp = DIRNAME_RE.exec(path); return temp ? temp[2] : ''; } /** * !#en Change extname of a file path. * !#zh 更改文件路径的扩展名。 - * @method changeExtname * @example {@link cocos2d/core/utils/CCPath/changeExtname.js} - * @param {String} pathStr - * @param {String} [extname] - * @returns {String} */ -export function changeExtname (pathStr, extname) { - extname = extname || ""; - let index = pathStr.indexOf("?"); - let tempStr = ""; +export function changeExtname (path: string, extName?: string) { + extName = extName || ''; + let index = path.indexOf('?'); + let tempStr = ''; if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); + tempStr = path.substring(index); + path = path.substring(0, index); } - index = pathStr.lastIndexOf("."); - if (index < 0) return pathStr + extname + tempStr; - return pathStr.substring(0, index) + extname + tempStr; + index = path.lastIndexOf('.'); + if (index < 0) { + return path + extName + tempStr; + } + return path.substring(0, index) + extName + tempStr; } /** * !#en Change file name of a file path. * !#zh 更改文件路径的文件名。 * @example {@link cocos2d/core/utils/CCPath/changeBasename.js} - * @param {String} pathStr - * @param {String} basename - * @param {Boolean} [isSameExt] - * @returns {String} */ -export function changeBasename (pathStr, basename, isSameExt) { - if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename); - let index = pathStr.indexOf("?"); - let tempStr = ""; - let ext = isSameExt ? this.extname(pathStr) : ""; - if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); +export function changeBasename (path: string, baseName: string, isSameExt?: boolean) { + if (baseName.indexOf('.') === 0) { + return changeExtname(path, baseName); } - index = pathStr.lastIndexOf("/"); + let index = path.indexOf('?'); + let tempStr = ''; + const ext = isSameExt ? extname(path) : ''; + if (index > 0) { + tempStr = path.substring(index); + path = path.substring(0, index); + } + index = path.lastIndexOf('/'); index = index <= 0 ? 0 : index + 1; - return pathStr.substring(0, index) + basename + ext + tempStr; + return path.substring(0, index) + baseName + ext + tempStr; } -//todo make public after verification +// todo make public after verification export function _normalize (url) { let oldUrl = url = String(url); - //removing all ../ + // removing all ../ do { oldUrl = url; - url = url.replace(NORMALIZE_RE, ""); + url = url.replace(NORMALIZE_RE, ''); } while (oldUrl.length !== url.length); return url; } -// @param {string} path -export function stripSep (path) { +export function stripSep (path: string) { return path.replace(/[\/\\]$/, ''); } -cc.path = { - join, - extname, - mainFileName, - basename, - dirname, - changeExtname, - changeBasename, - _normalize, - stripSep, - get sep () { - return (cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'); - } -}; \ No newline at end of file +export function getSeperator () { + return cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'; +} diff --git a/cocos/legacy.ts b/cocos/legacy.ts new file mode 100644 index 0000000000..8f0de26ef6 --- /dev/null +++ b/cocos/legacy.ts @@ -0,0 +1,37 @@ +// import AssetLibrary from './assets/CCAssetLibrary'; +import * as debug from './core/platform/CCDebug'; +import { _normalize, basename, changeBasename, changeExtname, dirname, extname, getSeperator, join, mainFileName, stripSep } from './core/utils/path'; +// import Pipeline from './load-pipeline/pipeline'; +// import Url from './load-pipeline/url'; + +// cc.Pipeline = Pipeline; +// cc.url = Url; +// cc.AssetLibrary = AssetLibrary; + +// CCDebug.js +cc.log = debug.log; +cc.warn = debug.warn; +cc.error = debug.error; +cc.assert = debug.assert; +cc._throw = debug._throw; +cc.logID = debug.logID; +cc.warnID = debug.warnID; +cc.errorID = debug.errorID; +cc.assertID = debug.assertID; +cc.debug = debug; + +// path.js +cc.path = { + join, + extname, + mainFileName, + basename, + dirname, + changeExtname, + changeBasename, + _normalize, + stripSep, + get sep () { + return getSeperator(); + }, +}; diff --git a/cocos/load-pipeline/asset-loader.js b/cocos/load-pipeline/asset-loader.js index 15cf2b312a..dac22723b0 100644 --- a/cocos/load-pipeline/asset-loader.js +++ b/cocos/load-pipeline/asset-loader.js @@ -25,7 +25,7 @@ ****************************************************************************/ import {extname} from '../core/utils/path'; -import debug from '../core/platform/CCDebug'; +import * as debug from '../core/platform/CCDebug'; import Pipeline from './pipeline'; import LoadingItems from './loading-items'; diff --git a/cocos/load-pipeline/audio-downloader.js b/cocos/load-pipeline/audio-downloader.js index a34643c3b2..de031ef5c3 100644 --- a/cocos/load-pipeline/audio-downloader.js +++ b/cocos/load-pipeline/audio-downloader.js @@ -25,7 +25,7 @@ ****************************************************************************/ import sys from '../core/platform/CCSys'; -import debug from '../core/platform/CCDebug'; +import * as debug from '../core/platform/CCDebug'; var __audioSupport = sys.__audioSupport; var formatSupport = __audioSupport.format; diff --git a/cocos/load-pipeline/downloader.js b/cocos/load-pipeline/downloader.js index 2e7701f983..f11494a44e 100644 --- a/cocos/load-pipeline/downloader.js +++ b/cocos/load-pipeline/downloader.js @@ -24,7 +24,7 @@ ****************************************************************************/ import {mixin} from '../core/utils/js'; -import debug from '../core/platform/CCDebug'; +import * as debug from '../core/platform/CCDebug'; import Pipeline from './pipeline'; import * as PackDownloader from './pack-downloader'; import downloadBinary from './binary-downloader'; diff --git a/cocos/load-pipeline/uuid-loader.js b/cocos/load-pipeline/uuid-loader.js index ddfdb6eecc..bca06ad566 100644 --- a/cocos/load-pipeline/uuid-loader.js +++ b/cocos/load-pipeline/uuid-loader.js @@ -26,7 +26,7 @@ import * as js from '../core/utils/js'; import {_getClassById} from '../core/utils/js'; -import debug from '../core/platform/CCDebug'; +import * as debug from '../core/platform/CCDebug'; import deserialize from '../core/data/deserialize'; import LoadingItems from './loading-items'; @@ -229,6 +229,10 @@ export function loadUuid (item, callback) { return new Error(debug.getError(4924)); } + if (json === undefined || json === null) { + return new Error(debug.getError(4923, item.id)); + } + var classFinder; var isScene = isSceneObj(json); if (isScene) { diff --git a/globals.d.ts b/globals.d.ts index 558d0b281c..7940f459d8 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -52,4 +52,10 @@ declare module "webgl-debug" { ): WebGLRenderingContext; export function glEnumToString(glEnum: GLenum): string; -} \ No newline at end of file +} + +declare namespace Editor { + function log (message?: any, ...optionalParams: any[]): void; + function error (message?: any, ...optionalParams: any[]): void; + function warn (message?: any, ...optionalParams: any[]): void; +} diff --git a/index.ts b/index.ts index 4bb2994381..5195bcd8ca 100644 --- a/index.ts +++ b/index.ts @@ -28,6 +28,8 @@ import cc from './predefine'; +import './cocos/legacy'; + // LOAD ENGINE CORE export * from './cocos/core'; export * from './cocos/scene-graph'; diff --git a/tslint.json b/tslint.json index 85f54e09b9..7edabd8a56 100644 --- a/tslint.json +++ b/tslint.json @@ -21,7 +21,11 @@ "ban-types": false, "no-bitwise": false, "no-empty": false, - "radix": false + "radix": false, + "max-line-length": [ + true, + 160 + ] }, "rulesDirectory": [] }