[Optimize] Simplify workflow (#16503)

* [Optimize] Simplify workflow
This commit is contained in:
SijieWang
2023-11-13 09:31:40 +08:00
committed by GitHub
parent 60088d4f65
commit c41807c4f6
35 changed files with 1554 additions and 6411 deletions
+2 -1
View File
@@ -3,7 +3,8 @@ root: true
parser: '@typescript-eslint/parser'
parserOptions:
project: ./tsconfig.json
project:
- ./tsconfig.json
extends:
- eslint:recommended
+1 -1
View File
@@ -33,4 +33,4 @@ jobs:
uses: OperationsYU/auto-assignment@v1
with:
token: ${{ secrets.LABEl_TOKEN }}
users: '["holycanvas"]'
users: '["minggo"]'
+2 -2
View File
@@ -41,7 +41,7 @@ jobs:
vulkan-use-cache: true
- name: gen simulator
run: |
gulp gen-simulator
npx gulp gen-simulator
- name: check result
run: |
Get-ChildItem ./simulator/Release -Name SimulatorApp-Win32.exe
@@ -66,7 +66,7 @@ jobs:
- name: gen simulator
run: |
gulp gen-simulator-release
npx gulp gen-simulator-release
- name: check result
run: |
find ./ -name SimulatorApp-Mac
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts
- run: npx gulp build-debug-infos
- run: npm run build:debug-infos
- name: Download external
run: |
EXT_VERSION=`node ./.github/workflows/get-native-external-version.js`
+1 -2
View File
@@ -33,8 +33,7 @@ jobs:
EXT_VERSION=`node ./.github/workflows/get-native-external-version.js`
git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos/cocos-engine-external native/external
- run: npm install -g gulp
- run: npm ci
- run: echo "::add-matcher::.github/workflows/build-problem-matcher.json"
- run: gulp build-h5-source
- run: npm run build:dev
#- run: echo "::remove-matcher owner=circular-reference-check::"
+2 -2
View File
@@ -29,11 +29,11 @@ jobs:
run: |
branch=`echo ${{ github.base_ref }} | awk -F'/' '{print $NF}'`
echo "Branch: ${branch}"
npm run verify-engine-version -- ${branch}
npm run verify:engine-version -- ${branch}
- name: check version create
if: github.event_name == 'create'
run: |
branch=`echo ${{ github.ref }} | awk -F'/' '{print $NF}'`
echo "Branch: ${branch}"
npm run verify-engine-version -- ${branch}
npm run verify:engine-version -- ${branch}
+1 -5
View File
@@ -18,10 +18,6 @@ jobs:
- uses: actions/setup-node@v2
with:
node-version: '18.x'
- name: install gulp
run: |
npm install -g gulp
- name: Download external
run: |
@@ -34,7 +30,7 @@ jobs:
- name: build-debug-infos
run: |
gulp build-debug-infos
npm run build:debug-infos
- name: run test
run: |
-29
View File
@@ -1,29 +0,0 @@
const Fs = require('fs');
module.exports = function buildDebugInfos () {
let readContent = Fs.readFileSync('EngineErrorMap.md', 'utf-8');
let titleRegExp = /### \d+/g;
let debugInfos = {};
let result1 = titleRegExp.exec(readContent);
while (result1) {
let result2 = titleRegExp.exec(readContent);
let errInfoHead = result1.index + result1[0].length;
let errInfoTail = result2? result2.index: readContent.length;
let errCode = /\d+/.exec(result1[0])[0];
let errInfo = readContent.slice(errInfoHead, errInfoTail);
errInfo = errInfo.replace(/```/g, ' ');
errInfo = errInfo.trim();
errInfo = errInfo.replace(/\r\n/g, '\n');
if (!errInfo.includes('<!-- DEPRECATED -->')) {
debugInfos[`${errCode}`] = errInfo;
}
result1 = result2;
}
let writeContent = JSON.stringify(debugInfos, null, 4);
Fs.writeFileSync('DebugInfos.json', writeContent);
};
-137
View File
@@ -1,137 +0,0 @@
/*
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.
*/
/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable @typescript-eslint/no-var-requires */
'use strict';
const gulp = require('gulp');
const fs = require('fs-extra');
const ps = require('path');
const cp = require('child_process');
gulp.task('build-debug-infos', async () => {
return await Promise.resolve(require('./gulp/tasks/buildDebugInfos')());
});
gulp.task('build-source', async () => {
const cli = require.resolve('@cocos/build-engine/dist/cli');
return cp.spawn('node', [
cli,
`--engine=${__dirname}`,
'--module=system',
...process.argv.slice(3),
], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
});
});
gulp.task('build-h5-source', gulp.series('build-debug-infos', async () => {
const outDir = ps.join('bin', 'dev', 'cc');
await fs.ensureDir(outDir);
await fs.emptyDir(outDir);
const cli = require.resolve('@cocos/build-engine/dist/cli');
const exitCode = await new Promise((resolve, reject) => {
cp.spawn('node', [
cli,
`--engine=${__dirname}`,
'--module=system',
'--build-mode=BUILD',
'--platform=HTML5',
'--physics=cannon',
`--out=${outDir}`,
], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
}).on('exit', (code) => {
resolve(code);
}).on('error', (err) => {
reject(err);
});
});
if (exitCode) {
throw new Error(`Build process exit with ${exitCode}`);
}
}));
gulp.task('build-h5-minified', gulp.series('build-debug-infos', async () => {
const outDir = ps.join('bin', 'dev', 'cc-min');
await fs.ensureDir(outDir);
await fs.emptyDir(outDir);
const cli = require.resolve('@cocos/build-engine/dist/cli');
return cp.spawn('node', [
cli,
`--engine=${__dirname}`,
'--module=system',
'--compress',
'--sourcemap',
'--build-mode=BUILD',
'--platform=HTML5',
'--physics=cannon',
`--out=${outDir}`,
], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
});
}));
gulp.task('build-declarations', async () => {
const outDir = ps.join('bin', '.declarations');
const { build } = require('@cocos/build-engine/dist/build-declarations');
await fs.emptyDir(outDir);
return await build({
engine: __dirname,
outDir,
withIndex: true,
withExports: false,
withEditorExports: true,
});
});
gulp.task('build', gulp.parallel('build-h5-minified', 'build-debug-infos', 'build-declarations'));
gulp.task('code-check', () => {
return cp.spawn('npx', ['tsc', '--noEmit'], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
});
});
gulp.task('unit-tests', () => {
return cp.spawn('npx', ['jest'], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
});
});
gulp.task('test', gulp.series('code-check', 'unit-tests'));
+1177 -5088
View File
File diff suppressed because it is too large Load Diff
+17 -27
View File
@@ -12,23 +12,23 @@
"node": ">=18.0.0"
},
"scripts": {
"server": "http-server . -p 8002 -o playground/index.html",
"postinstall": "gulp build-debug-infos && npm run build-declaration && npm run bundle-adapter && npm run fetch-ral && npm run install:native-pack-tool",
"build": "gulp build",
"build:dev": "gulp build-h5-source",
"build:min": "gulp build-h5-minified",
"build-declaration": "npm run build-const && gulp build-declarations",
"checkout-engine-version": "node ./scripts/checkout-engine-version.js",
"verify-engine-version": "node ./scripts/verify-engine-version.js",
"fetch-ral": "node ./scripts/fetch-ral.js",
"bundle-adapter": "node ./scripts/bundle-adapter.js",
"build-const": "node ./scripts/build-const.js",
"postinstall": "npm run build:debug-infos && npm run build:declaration && npm run build:adapter && npm run fetch-ral && npm run build:native-pack-tool",
"build": "npm run build:min && npm run build:declaration",
"build:adapter": "node ./scripts/build-adapter.js",
"build:const": "node ./scripts/build-const.js",
"build:dev": "npm run build:debug-infos && node ./scripts/build-h5-source",
"build:debug-infos": "node ./scripts/build-debug-infos",
"build:declaration": "npm run build:const && node ./scripts/build-declarations",
"build:min": "npm run build:debug-infos && node ./scripts/build-h5-minified",
"build:native-pack-tool": "cd ./scripts/native-pack-tool && npm install && npm run build",
"clear": "node ./scripts/clear-cache.js",
"clear-platform": "node ./native/utils/clear-platform.js && node ./scripts/clear-file.js",
"clear:platform": "node ./native/utils/clear-platform.js && node ./scripts/clear-file.js",
"fetch-ral": "node ./scripts/fetch-ral.js",
"generate:doc-info": "node ./scripts/generate-doc-info",
"test": "tsc --noEmit && jest",
"update:engine-version": "node ./scripts/checkout-engine-version.js",
"update:native-external": "node ./native/utils/update-external.js",
"test": "gulp test",
"generate-doc-info": "node ./scripts/generate-doc-info",
"install:native-pack-tool": "cd ./scripts/native-pack-tool && npm install && npm run build"
"verify:engine-version": "node ./scripts/verify-engine-version.js"
},
"repository": {
"type": "git",
@@ -49,10 +49,7 @@
"axios": "^1.4.0",
"babelify": "^10.0.0",
"browserify": "^17.0.0",
"chalk": "^2.4.1",
"child_process": "^1.0.2",
"commander": "^2.20.3",
"dat.gui": "^0.7.5",
"chalk": "^4.1.2",
"del": "^6.0.0",
"eslint": "^8.44.0",
"eslint-config-airbnb-base": "^15.0.0",
@@ -62,33 +59,26 @@
"ftp": "0.3.10",
"gulp": "^4.0.2",
"gulp-rename": "^2.0.0",
"gulp-sequence": "^1.0.0",
"gulp-uglify": "^3.0.2",
"gulp-zip": "^5.0.2",
"http-server": "^0.12.3",
"jest": "^28.0.2",
"jest-environment-jsdom": "^28.0.2",
"jest-extended": "^1.1.0",
"jest-matcher-deep-close-to": "^2.0.1",
"jsdom": "^19.0.0",
"node-fetch": "^2.6.1",
"path": "^0.12.7",
"pngjs": "^6.0.0",
"progress": "^2.0.3",
"spectorjs": "^0.9.15",
"stats.js": "^0.17.0",
"tar": "^6.1.15",
"tmp": "^0.2.1",
"tree-kill": "^1.2.0",
"ts-jest": "^28.0.8",
"typescript": "^4.3.5",
"vconsole": "^3.3.0",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"which": "^2.0.2",
"yargs": "^12.0.5"
},
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@cocos/box2d": "1.0.1",
"@cocos/cannon": "1.2.8",
"@cocos/ccbuild": "2.0.3-alpha.18",
-143
View File
@@ -1,143 +0,0 @@
document.addEventListener('readystatechange', () => {
if (document.readyState !== 'complete') return;
window.FirstPersonCamera = (() => {
const { Quat, Vec2, Vec3 } = cc.math;
const v2_1 = new Vec2();
const v2_2 = new Vec2();
const v3_1 = new Vec3();
const qt_1 = new Quat();
const KEYCODE = {
W: 'W'.charCodeAt(0),
S: 'S'.charCodeAt(0),
A: 'A'.charCodeAt(0),
D: 'D'.charCodeAt(0),
Q: 'Q'.charCodeAt(0),
E: 'E'.charCodeAt(0),
SHIFT: cc.macro.KEY.shift,
};
class FirstPersonCamera extends cc.Component {
constructor () {
super();
this.moveSpeed = 1;
this.moveSpeedShiftScale = 5;
this.damp = 0.2;
this.rotateSpeed = 1;
}
onLoad () {
this._euler = new Vec3();
this._velocity = new Vec3();
this._position = new Vec3();
this._speedScale = 1;
cc.systemEvent.on(cc.SystemEvent.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_MOVE, this.onTouchMove, this);
cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
Vec3.copy(this._euler, this.node.eulerAngles);
Vec3.copy(this._position, this.node.position);
}
onDestroy () {
cc.systemEvent.off(cc.SystemEvent.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_MOVE, this.onTouchMove, this);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
}
update (dt) {
// position
Vec3.transformQuat(v3_1, this._velocity, this.node.rotation);
Vec3.scaleAndAdd(this._position, this._position, v3_1, this.moveSpeed * this._speedScale);
Vec3.lerp(v3_1, this.node.position, this._position, dt / this.damp);
this.node.setPosition(v3_1);
// rotation
Quat.fromEuler(qt_1, this._euler.x, this._euler.y, this._euler.z);
Quat.slerp(qt_1, this.node.rotation, qt_1, dt / this.damp);
this.node.setRotation(qt_1);
}
onMouseWheel (e) {
const delta = -e.getScrollY() * this.moveSpeed * 0.1; // delta is positive when scroll down
Vec3.transformQuat(v3_1, Vec3.UNIT_Z, this.node.rotation);
Vec3.scaleAndAdd(this._position, this.node.position, v3_1, delta);
}
onKeyDown (e) {
const v = this._velocity;
if (e.keyCode === KEYCODE.SHIFT) {
this._speedScale = this.moveSpeedShiftScale;
} else if (e.keyCode === KEYCODE.W) {
if (v.z === 0) { v.z = -1; }
} else if (e.keyCode === KEYCODE.S) {
if (v.z === 0) { v.z = 1; }
} else if (e.keyCode === KEYCODE.A) {
if (v.x === 0) { v.x = -1; }
} else if (e.keyCode === KEYCODE.D) {
if (v.x === 0) { v.x = 1; }
} else if (e.keyCode === KEYCODE.Q) {
if (v.y === 0) { v.y = -1; }
} else if (e.keyCode === KEYCODE.E) {
if (v.y === 0) { v.y = 1; }
}
}
onKeyUp (e) {
const v = this._velocity;
if (e.keyCode === KEYCODE.SHIFT) {
this._speedScale = 1;
} else if (e.keyCode === KEYCODE.W) {
if (v.z < 0) { v.z = 0; }
} else if (e.keyCode === KEYCODE.S) {
if (v.z > 0) { v.z = 0; }
} else if (e.keyCode === KEYCODE.A) {
if (v.x < 0) { v.x = 0; }
} else if (e.keyCode === KEYCODE.D) {
if (v.x > 0) { v.x = 0; }
} else if (e.keyCode === KEYCODE.Q) {
if (v.y < 0) { v.y = 0; }
} else if (e.keyCode === KEYCODE.E) {
if (v.y > 0) { v.y = 0; }
}
}
onTouchStart () {
if (cc.game.canvas.requestPointerLock) cc.game.canvas.requestPointerLock();
}
onTouchMove (e) {
e.getStartLocation(v2_1);
if (v2_1.x > cc.winSize.width * 0.4) { // rotation
e.getDelta(v2_2);
this._euler.y -= v2_2.x * this.rotateSpeed * 0.1;
this._euler.x += v2_2.y * this.rotateSpeed * 0.1;
} else { // position
e.getLocation(v2_2);
Vec3.subtract(v2_2, v2_2, v2_1);
this._velocity.x = v2_2.x * 0.01;
this._velocity.z = -v2_2.y * 0.01;
}
}
onTouchEnd (e) {
if (document.exitPointerLock) document.exitPointerLock();
e.getStartLocation(v2_1);
if (v2_1.x < cc.winSize.width * 0.4) { // position
this._velocity.x = 0;
this._velocity.z = 0;
}
}
}
return cc.Class({
name: 'FirstPersonCamera',
ctor: FirstPersonCamera,
});
})();
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

-104
View File
@@ -1,104 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1,minimal-ui=true" />
<style>
body {
background: #333;
color: #888;
margin: 0px;
display: flex;
flex-direction: column;
padding: 5px;
}
.view {
position: relative;
flex: 1;
}
.toolbar {
display: flex;
margin-top: 10px;
font-size: 12px;
}
.toolbar>* {
margin-right: 10px;
}
.toolbar>*:last-child {
margin-right: 0px;
}
.fit {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
canvas {
background: #09f;
}
canvas:focus {
outline: 0;
}
.field {
display: inline-block;
margin-right: 5px;
}
.dgui {
position: absolute;
top: 5px;
left: 5px;
}
</style>
<script src="../../node_modules/vconsole/dist/vconsole.min.js"></script>
<script src="../../node_modules/stats.js/build/stats.min.js"></script>
<script src="../../node_modules/dat.gui/build/dat.gui.min.js"></script>
<script src="../bin/dev/polyfills.bundle.js"> </script>
<script src="../bin/dev/system.bundle.js"> </script>
<script src="../bin/dev/cc.js"></script>
<script src="./common/camera.js"></script>
<script src="./shell.js"></script>
</head>
<body class="fit">
<div id="view" class="view">
<canvas id="GameCanvas"></canvas>>
</div>
<div class="toolbar">
<div>
<div class="field">
<input type="checkbox" id="showFPS"></input>FPS
</div>
<div class="field">
<input type="checkbox" id="spector"></input>Spector
</div>
<div class="field">
<input type="checkbox" id="vconsole"></input>VConsole
</div>
</div>
<span style="flex: 1"></span>
<select id="exampleList">
<option value="./src/simple.js">Simple</option>
<option value="./src/collision-detection.js">Collision Detection</option>
<option value="./src/gizmo.js">Gizmo</option>
<option value="./src/planar-shadow.js">Planar Shadow</option>
<option value="./src/save-primitive-objs.js">Save Primitive OBJs</option>
<!-- <option value="./src/custom-effect.js">Custom Effect</option> -->
</select>
</div>
</body>
</html>
-153
View File
@@ -1,153 +0,0 @@
(() => {
function loadPromise (url) {
return new Promise((resolve, reject) => {
const xhr = new window.XMLHttpRequest();
xhr.open('GET', `${url}?_=${new Date().getTime()}`, true); // force no cache
xhr.onreadystatechange = onreadystatechange;
xhr.send(null);
function onreadystatechange (e) {
if (xhr.readyState !== 4) {
return;
}
// Testing harness file:/// results in 0.
if ([0, 200, 304].indexOf(xhr.status) === -1) {
reject(new Error(`While loading from url ${url} server responded with a status of ${xhr.status}`));
} else {
resolve(e.target.response);
}
}
});
}
function _load (url) {
loadPromise(url).then((result) => {
if (window.dgui) {
window.dgui.destroy();
window.dgui = null;
}
cc.director.off(cc.Director.EVENT_BEFORE_UPDATE);
// cc.director.off(cc.Director.EVENT_AFTER_UPDATE);
// cc.director.off(cc.Director.EVENT_BEFORE_DRAW);
// cc.director.off(cc.Director.EVENT_AFTER_DRAW);
cc.systemEvent.off(cc.SystemEvent.EventType.MOUSE_WHEEL);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_START);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_MOVE);
cc.systemEvent.off(cc.SystemEvent.EventType.TOUCH_END);
// init dgui
if (window.dat) {
const dgui = new window.dat.GUI({ width: 270 });
dgui.domElement.classList.add('dgui');
window.dgui = dgui;
}
const curAbsPath = (() => {
const scripts = document.getElementsByTagName('script');
const lastScriptPath = scripts[scripts.length - 1].src;
const segs = lastScriptPath.split('/');
if (segs.length >= 1) {
segs.pop();
}
const path = `${segs.join('/')}/`;
return path;
})();
// eslint-disable-next-line no-eval
eval(`(() => {\n${result}\n})();\n\n//# sourceURL=${curAbsPath + url}`);
window.cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
window.stats.update();
});
}).catch((err) => {
console.error(err);
});
}
document.addEventListener('readystatechange', () => {
if (document.readyState !== 'complete') return;
const view = document.getElementById('view');
const showFPS = document.getElementById('showFPS');
const enableSpector = document.getElementById('spector');
const enableVConsole = document.getElementById('vconsole');
const exampleList = document.getElementById('exampleList');
// update profile
showFPS.checked = localStorage.getItem('engine.showFPS') === 'true';
enableSpector.checked = localStorage.getItem('engine.enableSpector') === 'true';
enableVConsole.checked = localStorage.getItem('engine.enableVConsole') === 'true';
let exampleIndex = parseInt(localStorage.getItem('engine.exampleIndex'));
if (Number.isNaN(exampleIndex) || exampleIndex >= exampleList.childElementCount) exampleIndex = 0;
exampleList.selectedIndex = exampleIndex;
// init stats
if (window.Stats) {
const stats = new window.Stats();
stats.dom.style.cssText = 'position:fixed;top:0;right:0;cursor:pointer;opacity:0.9;z-index:10000';
stats.dom.style.display = showFPS.checked ? 'block' : 'none';
document.body.appendChild(stats.dom);
window.stats = stats;
showFPS.addEventListener('click', (event) => {
localStorage.setItem('engine.showFPS', event.target.checked);
stats.dom.style.display = event.target.checked ? 'block' : 'none';
});
}
// init spector
const url = '../node_modules/spectorjs/dist/spector.bundle.js';
loadPromise(url).then((result) => {
// eslint-disable-next-line no-eval
eval(`${result}\n//# sourceURL=${url}`);
if (enableSpector.checked) {
window.spector = new window.SPECTOR.Spector();
window.spector.displayUI();
}
enableSpector.addEventListener('click', () => {
// localStorage.setItem('engine.enableSpector', event.target.checked);
if (enableSpector.checked) {
window.spector = new window.SPECTOR.Spector();
window.spector.displayUI();
}
});
});
// init vconsole
if (window.VConsole) {
if (enableVConsole.checked) window.vconsole = new window.VConsole();
enableVConsole.addEventListener('click', () => {
// localStorage.setItem('engine.enableVConsole', event.target.checked);
if (enableVConsole.checked) window.vconsole = new window.VConsole();
});
}
// create canvas
const bcr = view.getBoundingClientRect();
const canvas = document.getElementById('GameCanvas');
canvas.classList.add('fit');
canvas.tabIndex = -1;
canvas.width = bcr.width;
canvas.height = bcr.height;
// init engine
window.cc.game.init({
adapter: { canvas, container: canvas.parentNode, frame: canvas.parentNode.parentNode },
});
window.cc.game.run(() => {
_load(exampleList.value);
window.addEventListener('resize', () => {
const bcr = view.getBoundingClientRect();
cc.director.root.resize(bcr.width, bcr.height);
});
const bcr = view.getBoundingClientRect();
cc.director.root.resize(bcr.width, bcr.height);
exampleList.addEventListener('change', (event) => {
localStorage.setItem('engine.exampleIndex', event.target.selectedIndex);
_load(exampleList.value);
});
});
});
})();
-210
View File
@@ -1,210 +0,0 @@
const { cc, dgui } = window;
const { Camera, Scene, Material, Node } = cc;
const { BlendFactor } = cc.gfx;
const { Color, randomRange, toRadian, Vec3 } = cc.math;
const { sphere, capsule } = cc.primitives;
const { createMesh } = cc.utils;
const dobj = {
playing: true,
play: () => {
dobj.playing = true;
},
pause: () => {
dobj.playing = false;
},
stop: () => {
dobj.playing = false;
emitters.forEach((e) => {
e.reapAll();
});
},
step: () => {
dobj.playing = true;
emitters.forEach((e) => {
e.update();
});
dobj.playing = false;
},
};
const scene = new Scene();
const poolSize = 50;
const hintMesh = createMesh(capsule(1));
const sphereMesh = createMesh(sphere(1));
const outOfBounds = (v, border = 20) => Math.abs(v.x) > border || Math.abs(v.y) > border || Math.abs(v.z) > border;
const v3_1 = new Vec3();
class Element {
constructor () {
this.velocity = new Vec3();
this.color = new Color();
this.collided = false;
this.framesRemaining = 0;
this.pass = null;
this.hColor = 0;
this.node = null;
}
}
// encapsulate an interesting emitter, emitted particles will
// annihilate after collision, if satisfying filter condition
class Emitter {
constructor (group, mask, pos, minAngle, maxAngle, color) {
this.node = new Node(`emitter_${group}`);
this.node.parent = scene;
this.node.setPosition(pos);
this.group = group;
this.mask = mask;
this.minAngle = minAngle;
this.maxAngle = maxAngle;
this.color = color;
this._deadpool = [];
this._livepool = [];
this._elements = [];
// emitter hint
const hint = new Node('hint');
const hintModel = hint.addComponent('cc.MeshRenderer');
const hintMat = new Material();
hintMat.initialize({ effectName: 'builtin-standard' });
hintMat.setProperty('albedo', this.color);
hintMat.setProperty('metallic', 0.1);
hintModel.material = hintMat;
hintModel.mesh = hintMesh;
hint.parent = this.node;
// elements
for (let i = 0; i < poolSize; i++) {
const node = new Node(i);
node.parent = this.node;
// element info
const ele = new Element();
ele.node = node;
ele.color.set(this.color);
// model
const model = node.addComponent('cc.MeshRenderer');
const mat = new Material();
mat.initialize({
effectName: 'builtin-standard',
states: {
blendState: {
targets: [{
blend: true,
blendSrc: BlendFactor.SRC_ALPHA,
blendDst: BlendFactor.ONE_MINUS_SRC_ALPHA,
blendDstAlpha: BlendFactor.ONE_MINUS_SRC_ALPHA,
}],
},
depthStencilState: { depthTest: false },
},
});
mat.setProperty('metallic', 0.1);
ele.pass = mat.passes[0];
ele.hColor = ele.pass.getHandle('albedo');
ele.pass.setUniform(ele.hColor, ele.color);
model.material = mat;
model.mesh = sphereMesh;
// collider
const col = node.addComponent('cc.SphereCollider');
col.radius = 1;
col.isTrigger = true;
col.setGroup(this.group); col.setMask(this.mask);
col.on('onTriggerEnter', (e) => {
const col = e.selfCollider;
const ele = this._elements[col.node.name];
if (ele.collided) return;
ele.color.a = 255;
ele.pass.setUniform(ele.hColor, ele.color);
ele.collided = true;
ele.framesRemaining = 5;
Vec3.set(ele.velocity, 0, 0, 0);
col.setGroup(0); col.setMask(0);
});
// store
node.active = false;
this._deadpool.push(ele);
this._elements.push(ele);
}
}
update () {
if (!dobj.playing) return;
for (let i = 0; i < this._livepool.length; i++) {
const ele = this._livepool[i];
if (ele.collided) {
if (ele.framesRemaining-- <= 0) this.reap(ele);
} else {
Vec3.add(v3_1, ele.node.position, ele.velocity);
ele.node.setPosition(v3_1);
if (outOfBounds(v3_1)) this.reap(ele);
}
}
if (this._deadpool.length > 0) this.resurrect();
// for (let i = 0; i < this._deadpool.length; i++) this.resurrect();
}
reap (ele) {
ele.node.active = false;
this._livepool.splice(this._livepool.indexOf(ele), 1);
this._deadpool.push(ele);
}
reapAll () {
for (let i = 0; i < this._livepool.length; i++) {
const ele = this._livepool[i];
ele.node.active = false;
this._deadpool.push(ele);
}
this._livepool.length = 0;
}
resurrect () {
const ele = this._deadpool.pop();
const theta = toRadian(randomRange(this.minAngle, this.maxAngle));
const phi = randomRange(1, 2);
const speed = randomRange(0.1, 0.3);
Vec3.set(ele.velocity, Math.cos(theta) * Math.sin(phi) * speed,
Math.cos(phi) * speed, Math.sin(theta) * Math.sin(phi) * speed);
ele.color.a = this.color.a; ele.collided = false;
ele.pass.setUniform(ele.hColor, ele.color);
const col = ele.node.getComponent('cc.SphereCollider');
col.setGroup(this.group); col.setMask(this.mask);
ele.node.setPosition(0, 0, 0);
this._livepool.push(ele);
ele.node.active = true;
}
}
// camera
const cameraNode = new Node('camera');
cameraNode.parent = scene;
cameraNode.setPosition(-20, 50, 12);
cameraNode.lookAt(Vec3.ZERO);
cameraNode.addComponent(Camera);
cameraNode.addComponent(window.FirstPersonCamera);
// light
const light = new Node('light');
light.parent = scene;
light.setRotationFromEuler(-80, 20, -40);
light.addComponent('cc.DirectionalLight');
cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
for (let i = 0; i < emitters.length; i++) {
emitters[i].update();
}
});
dgui.add(dobj, 'play');
dgui.add(dobj, 'pause');
dgui.add(dobj, 'stop');
dgui.add(dobj, 'step');
cc.director.runSceneImmediate(scene); // have to run the scene before set collider groups & masks
// set the stage
const emitters = []; // a particle does not collide with those come from the same group
emitters.push(new Emitter(1, ~1, new Vec3(-10, 0, 10), 0, -90, new Color(204, 178, 128, 51)));
emitters.push(new Emitter(2, ~2, new Vec3(10, 0, -10), 90, 180, new Color(51, 76, 128, 51)));
emitters.push(new Emitter(4, ~4, new Vec3(-10, 0, -10), 0, 90, new Color(204, 76, 128, 51)));
emitters.push(new Emitter(8, ~8, new Vec3(10, 0, 10), -90, -180, new Color(51, 178, 128, 51)));
-31
View File
@@ -1,31 +0,0 @@
cc.AssetLibrary.init({
libraryPath: 'library',
rawAssetsBase: 'library',
rawAssets: {
assets: {
// https://github.com/cocos-creator/example-3d/blob/master/show-cases/assets/effects/test.effect
'97051ce4-0cc9-4ae0-a584-d73943d7c11a': ['test', 'cc.EffectAsset'],
},
},
});
const scene = new cc.Scene();
const cameraNode = new cc.Node('Camera');
cameraNode.parent = scene;
cameraNode.setPosition(6, 0, 2);
cameraNode.setRotationFromEuler(0, 70, 0);
cameraNode.addComponent(cc.Camera);
cameraNode.addComponent(window.FirstPersonCamera);
const modelNode = new cc.Node('test');
modelNode.parent = scene;
const modelComp = modelNode.addComponent('cc.MeshRenderer');
modelComp.mesh = cc.utils.createMesh(cc.primitives.sphere());
cc.director.runSceneImmediate(scene);
cc.loader.loadRes('test', cc.EffectAsset, (err, effect) => {
const material = new cc.Material();
material.initialize({ effectAsset: effect });
modelComp.material = material;
});
-115
View File
@@ -1,115 +0,0 @@
const scene = new cc.Scene('scene');
const cameraNode = new cc.Node('camera');
cameraNode.parent = scene;
cameraNode.setPosition(20, 20, 20);
cameraNode.lookAt(cc.v3());
cameraNode.addComponent(window.FirstPersonCamera);
cameraNode.addComponent(cc.Camera);
const material = new cc.Material();
material.initialize({
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
});
const material2 = new cc.Material();
material2.initialize({
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
states: {
depthStencilState: { depthTest: false, depthWrite: false },
rasterizerState: { cullMode: cc.gfx.CullMode.NONE },
blendState: { targets: [
{ blend: true, blendDst: cc.gfx.BlendFactor.ONE_MINUS_SRC_ALPHA, blendDstAlpha: cc.gfx.BlendFactor.ONE_MINUS_SRC_ALPHA },
] },
},
});
const createArrow = (color, rotation) => {
const arrow = new cc.Node('arrow');
arrow.setRotation(rotation);
const arrowHead = new cc.Node('arrowHead');
arrowHead.parent = arrow;
arrowHead.setPosition(0, 10, 0);
const headModel = arrowHead.addComponent('cc.MeshRenderer');
headModel.mesh = cc.utils.createMesh(cc.primitives.cone());
headModel.material = material;
headModel.material.setProperty('color', color);
const arrowBody = new cc.Node('arrowBody');
arrowBody.parent = arrow;
const bodyModel = arrowBody.addComponent('cc.MeshRenderer');
bodyModel.mesh = cc.utils.createMesh({
positions: [0, 0, 0, 0, 10, 0],
indices: [0, 1],
primitiveMode: cc.gfx.PrimitiveMode.LINE_LIST,
});
bodyModel.material = material;
bodyModel.material.overridePipelineStates({ primitive: cc.gfx.PrimitiveMode.LINE_LIST });
bodyModel.material.setProperty('color', color);
return arrow;
};
const createBorderPlane = (color, position, rotation) => {
const borderPlane = new cc.Node('borderPlane');
borderPlane.setPosition(position);
borderPlane.setRotation(rotation);
const plane = new cc.Node('plane');
plane.parent = borderPlane;
const planeModel = plane.addComponent('cc.MeshRenderer');
const mesh = planeModel.mesh = cc.utils.createMesh(cc.primitives.quad());
const submesh = mesh.renderingSubMeshes[0];
const vbInfo = mesh.struct.vertexBundles[0].view;
submesh.vbuffer = mesh.data.buffer.slice(vbInfo.offset, vbInfo.offset + vbInfo.length);
const ibInfo = mesh.struct.primitives[0].indexView;
submesh.ibuffer = mesh.data.buffer.slice(ibInfo.offset, ibInfo.offset + ibInfo.length);
planeModel.material = material2;
planeModel.material.setProperty('color', cc.color(0, 0, 0, 0).lerp(color, 0.5));
const border = new cc.Node('border');
border.parent = borderPlane;
const borderModel = border.addComponent('cc.MeshRenderer');
borderModel.mesh = cc.utils.createMesh({
positions: [0.5, 0.5, 0, 0, 0.5, 0, 0.5, 0, 0],
indices: [0, 1, 0, 2],
primitiveMode: cc.gfx.PrimitiveMode.LINE_LIST,
});
borderModel.material = material;
borderModel.material.overridePipelineStates({ primitive: cc.gfx.PrimitiveMode.LINE_LIST });
borderModel.material.setProperty('color', color);
return borderPlane;
};
const moveTool = new cc.Node('moveTool');
moveTool.parent = scene;
createArrow(cc.Color.RED, cc.Quat.fromEuler(new cc.Quat(), 90, 0, 0)).parent = moveTool;
createArrow(cc.Color.GREEN, cc.Quat.fromEuler(new cc.Quat(), 0, 0, 0)).parent = moveTool;
createArrow(cc.Color.BLUE, cc.Quat.fromEuler(new cc.Quat(), 0, 0, -90)).parent = moveTool;
createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), cc.Quat.fromEuler(new cc.Quat(), 0, 0, 0)).parent = moveTool;
createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), cc.Quat.fromEuler(new cc.Quat(), -90, -90, 0)).parent = moveTool;
createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), cc.Quat.fromEuler(new cc.Quat(), 90, 0, 90)).parent = moveTool;
const vel = cc.v3(); const speed = 0.1; const keys = 'IKJLOUR';
const KEYCODE = new Array(keys.length).fill(0).reduce((acc, _, i) => (acc[keys[i]] = keys.charCodeAt(i), acc), {});
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (e) => {
if (e.keyCode === KEYCODE.I) vel.z = speed;
else if (e.keyCode === KEYCODE.K) vel.z = -speed;
else if (e.keyCode === KEYCODE.J) vel.x = speed;
else if (e.keyCode === KEYCODE.L) vel.x = -speed;
else if (e.keyCode === KEYCODE.O) vel.y = speed;
else if (e.keyCode === KEYCODE.U) vel.y = -speed;
});
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, (e) => {
if (e.keyCode === KEYCODE.I) vel.z = 0;
else if (e.keyCode === KEYCODE.K) vel.z = 0;
else if (e.keyCode === KEYCODE.J) vel.x = 0;
else if (e.keyCode === KEYCODE.L) vel.x = 0;
else if (e.keyCode === KEYCODE.O) vel.y = 0;
else if (e.keyCode === KEYCODE.U) vel.y = 0;
else if (e.keyCode === KEYCODE.R) moveTool.active = !moveTool.active;
});
cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
moveTool.setPosition(cc.Vec3.add(moveTool._lpos, moveTool._lpos, vel));
});
cc.director.runSceneImmediate(scene);
-50
View File
@@ -1,50 +0,0 @@
const scene = new cc.Scene();
const root = new cc.Node();
root.parent = scene;
const altitude = 0;
root.setPosition(0, altitude, 0);
const cameraNode = new cc.Node('Camera');
cameraNode.parent = root;
cameraNode.setPosition(-16, 2, 16);
cameraNode.setRotationFromEuler(-12, -63, 0);
cameraNode.addComponent(cc.Camera);
cameraNode.addComponent(window.FirstPersonCamera);
const lightNode = new cc.Node('Light');
lightNode.parent = root;
lightNode.setPosition(-10, 10, -10);
lightNode.setRotationFromEuler(-50, 0, 0);
lightNode.addComponent('cc.DirectionalLight');
const material = new cc.Material();
material.initialize({ effectName: 'builtin-standard' });
const manifest = [
{ name: 'box', pos: cc.v3(0, 1, 10) },
{ name: 'sphere', pos: cc.v3(5, 1, 15) },
{ name: 'cylinder', pos: cc.v3(-5, 1, 5) },
{ name: 'torus', pos: cc.v3(5, 1, 5) },
{ name: 'cone', pos: cc.v3(-5, 1, 15) },
{ name: 'plane', pos: cc.v3(0, 0, 0), param: { width: 100, length: 100 } },
];
const models = {};
for (const info of manifest) {
const modelNode = new cc.Node(`${info.name}`);
modelNode.parent = root;
const modelComp = modelNode.addComponent('cc.MeshRenderer');
modelComp.material = info.mat || material;
modelComp.mesh = cc.utils.createMesh(cc.primitives[info.name](info.param));
if (info.name !== 'plane') modelComp.shadowCastingMode = cc.ModelComponent.ShadowCastingMode.ON;
modelNode.setPosition(info.pos);
models[info.name] = modelComp;
}
const qt = cc.Quat.fromEuler(cc.quat(), 10, 20, 0);
models.plane.node.setRotation(qt);
scene.globals.shadows.enabled = true;
scene.globals.shadows.setPlaneFromNode(models.plane.node);
scene.globals.shadows.shadowColor = cc.color('#2a4e90');
cc.director.runSceneImmediate(scene);
-18
View File
@@ -1,18 +0,0 @@
function write (name) {
const text = cc.primitives.toWavefrontOBJ(cc.primitives[name](), 100);
const blob = new Blob([text], { type: 'text/plain' });
const anchor = document.createElement('a');
anchor.download = `${name}.obj`;
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
anchor.click();
}
// write('box');
// write('sphere');
// write('cylinder');
write('cone');
// write('capsule');
// write('torus');
// write('plane');
// write('quad');
-107
View File
@@ -1,107 +0,0 @@
const geomList = ['box', 'sphere', 'cylinder', 'cone', 'torus', 'capsule'];
const scene = new cc.Scene();
const cameraNode = new cc.Node('Camera');
cameraNode.parent = scene;
cameraNode.setPosition(-2.2, 3.6, -5.3);
cameraNode.setRotationFromEuler(-13.6, -165.5, 0);
cameraNode.addComponent(window.FirstPersonCamera);
const camComp = cameraNode.addComponent(cc.Camera);
const skybox = scene.globals.skybox;
skybox.enabled = true;
camComp.clearFlags = cc.Camera.CameraClearFlag.SKYBOX;
const lightNode = new cc.Node('Light');
lightNode.parent = scene;
lightNode.setRotationFromEuler(-40, 0, 0);
lightNode.addComponent(cc.DirectionalLightComponent);
// parsed effect file is embedded in cocos/3d/builtin/effects.js
const material = new cc.Material();
material.initialize({
/* *
effectName: 'builtin-standard',
/* */
effectName: 'builtin-unlit',
defines: { USE_COLOR: true },
/* */
});
const len = 50;
const models = []; const passes = [];
const color = cc.color();
for (let i = 0; i < len; i++) {
const modelNode = new cc.Node(`${i}`);
modelNode.parent = scene;
const modelCom = modelNode.addComponent('cc.MeshRenderer');
modelCom.material = material;
modelCom.mesh = cc.utils.createMesh(cc.primitives[geomList[i % geomList.length]]());
modelNode.setPosition(0, 0, i * 2);
models.push(modelNode);
// material instance initialized here
passes.push(modelCom.material.passes[0]);
}
const handle = passes[0].getHandle('mainColor');
const canvasNode = new cc.Node('Canvas');
canvasNode.parent = scene;
canvasNode.addComponent(cc.Canvas);
// const spriteNode = new cc.Node('test-sprite');
// spriteNode.parent = canvasNode;
// const spriteComp = spriteNode.addComponent('cc.Sprite');
// spriteComp.sizeMode = cc.SpriteComponent.SizeMode.CUSTOM;
// spriteNode.getComponent('cc.UITransform').contentSize = cc.size(64, 64);
// const widgetComp = spriteNode.addComponent(cc.WidgetComponent);
// widgetComp.isAlignBottom = widgetComp.isAlignLeft = true;
// widgetComp.bottom = widgetComp.left = 10;
const img = document.createElement('img');
img.src = './common/texture.png';
img.onload = () => {
const textureCube = new cc.TextureCube();
textureCube.image = {
right: new cc.ImageAsset(img),
left: new cc.ImageAsset(img),
top: new cc.ImageAsset(img),
bottom: new cc.ImageAsset(img),
front: new cc.ImageAsset(img),
back: new cc.ImageAsset(img),
};
skybox.envmap = textureCube;
const texture = new cc.Texture2D();
texture.image = new cc.ImageAsset(img);
const originalSize = cc.size(img.width, img.height);
const rect = cc.rect(0, 0, img.width, img.height);
const spriteFrame = new cc.SpriteFrame();
spriteFrame.reset({ texture, originalSize, rect });
// spriteComp.spriteFrame = spriteFrame;
};
const material2 = new cc.Material();
material2.initialize({ effectName: 'builtin-standard' });
const modelNode2 = new cc.Node('test2');
modelNode2.parent = scene;
const modelCom2 = modelNode2.addComponent('cc.MeshRenderer');
modelCom2.material = material2;
const shape2 = cc.primitives.sphere();
modelCom2.mesh = cc.utils.createMesh(shape2);
const pos = cc.v2();
cc.systemEvent.on(cc.SystemEvent.EventType.TOUCH_MOVE, (e) => e.getLocation(pos));
cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
models.forEach((m, i) => {
const dt = cc.director.getDeltaTime();
const t = cc.director.getTotalFrames() / 60;
const rad = i * Math.PI * 8 / len;
const x = Math.cos(rad + t); const y = Math.sin(rad + t);
let z = m.position.z + dt; if (z > len * 2) z = 0;
m.setPosition(x * 2, y * 2, z);
color.fromHSV((x + 1) * 0.5, 0.5, 1);
passes[i].setUniform(handle, color);
});
});
cc.director.runSceneImmediate(scene);
@@ -4,6 +4,16 @@ extends:
- eslint:recommended
- airbnb-base
settings:
import/resolver:
node:
extensions:
- .js
- .jsx
- .ts
- .tsx
- .d.ts
env:
browser: true
node: true
@@ -11,11 +21,13 @@ env:
jest: true
globals:
cc: readonly
cc: false
wx: false
Editor: false
rules:
# https://eslint.org/docs/rules/
# https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin
# !!!!!!!!!!!!!!!!!!!!!!!!!
# BEFORE ADDING ANY RULES
@@ -23,6 +35,8 @@ rules:
##### RECOMMENDED RULE OVERRIDES #####
global-require: off # we use dynamic requires a lot
no-await-in-loop: off # we use async/await a lot
camelcase: off # underscores may come in handy in some cases
eqeqeq: warn # important check missing from recommended
keyword-spacing: warn # we require this explicitly
@@ -36,22 +50,28 @@ rules:
no-underscore-dangle: off
quotes: [warn, single, { allowTemplateLiterals: true }] # force single, but allow template literal
no-else-return: off # else-return is a common pattern which clearly expresses the control flow
no-unused-expressions: off # taken over by '@typescript-eslint/no-unused-expressions'
##### AIRBNB-SPECIFIC RULE OVERRIDES #####
class-methods-use-this: off # so empty functions could work
guard-for-in: off # for-in is a efficient choice for plain objects
import/export: off # so export declare namespace could work
import/extensions: off # typescript doesn't support this
import/no-unresolved: off # TODO: fix internal modules
import/prefer-default-export: off # prefer named exports
indent: off # use @typescript-eslint/indent instead for better compatibility
import/no-extraneous-dependencies: off # we have a lot of internal modules
indent: [error, 4, {
SwitchCase: 0,
ignoredNodes: [ # https://stackoverflow.com/a/72897089
"FunctionExpression > .params[decorators.length > 0]",
"FunctionExpression > .params > :matches(Decorator, :not(:first-child))",
"ClassBody.body > PropertyDefinition[decorators.length > 0] > .key",
]
}]
lines-between-class-members: off # be more lenient on member declarations
max-classes-per-file: off # helper classes are common
max-len: [warn, 150] # more lenient on max length per line
no-console: off # this is just too much work, cc.warn is still too much pain to use
no-console: off # prefer the uniform logging methods
no-plusplus: off # allow increment/decrement operators
no-continue: off # allow unlabeled continues
no-mixed-operators: off # this is just cumbersome
@@ -70,8 +90,4 @@ rules:
prefer-destructuring: off # auto-fix is not smart enough to merge different instances
linebreak-style: off # we don't enforce this on everyone's dev environment for now
spaced-comment: off # for license declarations
##### JS SPECIFIC OVERRIDES #####
global-require: off # may require different files based on global environment
func-names: off # overriding existing functions are common
default-case-last: off # Place default case clause to first make it more clear that this switch statement has handled all cases
@@ -1,14 +1,17 @@
const ps = require('path');
const fs = require('fs');
const gulp = require('gulp');
const babelify = require("babelify");
const babelify = require('babelify');
const browserify = require('browserify');
const source = require("vinyl-source-stream");
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const chalk = require('chalk').default;
const { magenta, green } = require('chalk');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build adapter ${prefix}`));
const engineRoot = ps.join(__dirname, '..');
(async function bundleAdapter () {
@@ -23,16 +26,16 @@ const engineRoot = ps.join(__dirname, '..');
console.error(e);
process.exit(1);
}
})();
}());
function getPlatformsFromPath (path) {
let platforms = fs.readdirSync(path);
platforms = platforms.filter(p => !p.startsWith('.'));
platforms = platforms.filter((p) => !p.startsWith('.'));
return platforms;
}
async function bundleNativeAdapter () {
console.log(chalk.green('\nBundling native adapter'));
console.log(green('\nBundling native adapter'));
// bundle engine-adapter.js
const engineAdapterEntry = normalizePath(ps.join(engineRoot, 'platforms/native/engine/index.js'));
const engineAdapterOutput = normalizePath(ps.join(engineRoot, 'bin/adapter/native/engine-adapter.js'));
@@ -47,10 +50,10 @@ async function bundleNativeAdapter () {
async function bundleMinigameAdapter () {
const platformsPath = ps.join(engineRoot, 'platforms/minigame/platforms');
const platforms = getPlatformsFromPath(platformsPath);
console.log(chalk.green(`\nBundling minigame platform adapters, including: ${platforms}`));
console.log(green(`\nBundling minigame platform adapters, including: ${platforms}`));
for (let platform of platforms) {
console.log(`handle platform: ${chalk.green(platform)}`);
for (const platform of platforms) {
console.log(`handle platform: ${green(platform)}`);
const needUglify = (platform !== 'xiaomi'); // uglify conflicts with the webpack tool on xiaomi platform
@@ -72,9 +75,9 @@ async function bundleMinigameAdapter () {
async function bundleRuntimeAdapter () {
const platformsPath = ps.join(engineRoot, 'platforms/runtime/platforms');
const platforms = getPlatformsFromPath(platformsPath);
console.log(chalk.green(`\nBundling runtime platform adapters, including: ${platforms}`));
for (let platform of platforms) {
console.log(`handle platform: ${chalk.green(platform)}`);
console.log(green(`\nBundling runtime platform adapters, including: ${platforms}`));
for (const platform of platforms) {
console.log(`handle platform: ${green(platform)}`);
// bundle engine-adapter.js
const engineEntry = normalizePath(ps.join(engineRoot, `platforms/runtime/platforms/${platform}/engine/index.js`));
const engineOutput = normalizePath(ps.join(engineRoot, `bin/adapter/runtime/${platform}/engine-adapter.js`));
@@ -82,30 +85,29 @@ async function bundleRuntimeAdapter () {
}
}
function normalizePath (path) {
return path.replace(/\\/g, '/');
}
/**
* Create bundle task
* @param {string} src
* @param {string} dst
* @param {string} src
* @param {string} dst
* @param {boolean} needUglify
* @param {string} targets
*/
function createBundleTask (src, dst, needUglify, targets) {
let targetFileName = ps.basename(dst);
let targetFileNameMin = ps.basename(targetFileName, '.js') + '.min.js';
const targetFileName = ps.basename(dst);
const targetFileNameMin = `${ps.basename(targetFileName, '.js')}.min.js`;
dst = ps.dirname(dst);
let bundler = browserify(src);
let task = bundler.transform(babelify, {presets: [
[require('@babel/preset-env'), targets ? { targets } : undefined],
],
plugins: [
require('@babel/plugin-proposal-class-properties'),
require('@babel/plugin-proposal-export-default-from')
]})
const bundler = browserify(src);
let task = bundler.transform(babelify, { presets: [
[require('@babel/preset-env'), targets ? { targets } : undefined],
],
plugins: [
require('@babel/plugin-proposal-class-properties'),
require('@babel/plugin-proposal-export-default-from'),
] })
.bundle()
.pipe(source(targetFileName))
.pipe(buffer())
@@ -121,14 +123,14 @@ function createBundleTask (src, dst, needUglify, targets) {
/**
* Build adapters
* @param {string} entry
* @param {string} output
* @param {string} entry
* @param {string} output
* @param {boolean} needUglify
* @param {string} targets
*/
async function bundle (entry, output, needUglify, targets = '') {
await new Promise((resolve) => {
console.log(`Generate bundle: ${chalk.green(ps.basename(output))}`);
console.log(`Generate bundle: ${green(ps.basename(output))}`);
createBundleTask(entry, output, needUglify, targets).on('end', resolve);
});
}
+17 -15
View File
@@ -1,21 +1,23 @@
const { StatsQuery } = require('@cocos/build-engine');
const ps = require('path');
const fsExt = require('fs-extra');
const chalk = require('chalk').default;
const { join } = require('path');
const { outputFileSync } = require('fs-extra');
const { magenta, green } = require('chalk');
const engineRoot = ps.join(__dirname, '../');
const targetConstFile = ps.join(engineRoot, `./@types/consts.d.ts`);
const engineRoot = join(__dirname, '../');
const targetConstFile = join(engineRoot, `./@types/consts.d.ts`);
console.log(chalk.green(`\nGenerate consts.d.ts: ${targetConstFile}\n`));
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build const ${prefix}`));
StatsQuery.create(engineRoot).then(statsQuery => {
StatsQuery.create(engineRoot).then((statsQuery) => {
const ic = statsQuery.constantManager.genInternalConstants();
const source =
`/**\n` +
` * This is an auto-generated declaration file for constants internally used in engine.\n` +
` * You may regenerate it by running cli command \`npm run build-const\`.\n` +
` */\n` +
`\n` +
ic.replace(/\t/g, ' ');
fsExt.outputFileSync(targetConstFile, source, 'utf8');
const source = `/**\n`
+ ` * This is an auto-generated declaration file for constants internally used in engine.\n`
+ ` * You may regenerate it by running cli command \`npm run build-const\`.\n`
+ ` */\n`
+ `\n${
ic.replace(/\t/g, ' ')}`;
outputFileSync(targetConstFile, source, 'utf8');
console.log(green(`\nGenerate consts.d.ts: ${targetConstFile}\n`));
});
+34
View File
@@ -0,0 +1,34 @@
const { readFileSync, writeFileSync } = require('fs');
const { magenta } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build debug infos ${prefix}`));
function buildDebugInfos () {
const readContent = readFileSync('EngineErrorMap.md', 'utf-8');
const titleRegExp = /### \d+/g;
const debugInfos = {};
let result1 = titleRegExp.exec(readContent);
while (result1) {
const result2 = titleRegExp.exec(readContent);
const errInfoHead = result1.index + result1[0].length;
const errInfoTail = result2 ? result2.index : readContent.length;
const errCode = /\d+/.exec(result1[0])[0];
let errInfo = readContent.slice(errInfoHead, errInfoTail);
errInfo = errInfo.replace(/```/g, ' ');
errInfo = errInfo.trim();
errInfo = errInfo.replace(/\r\n/g, '\n');
if (!errInfo.includes('<!-- DEPRECATED -->')) {
debugInfos[`${errCode}`] = errInfo;
}
result1 = result2;
}
const writeContent = JSON.stringify(debugInfos, null, 4);
writeFileSync('DebugInfos.json', writeContent);
}
buildDebugInfos();
+22
View File
@@ -0,0 +1,22 @@
const { join } = require('path');
const { emptyDir } = require('fs-extra');
const { build } = require('@cocos/build-engine/dist/build-declarations');
const { magenta } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build declarations ${prefix}`));
(async function exec () {
const PATHS = {
engine: join(__dirname, '..'),
out: join(__dirname, '..', 'bin', '.declarations'),
};
await emptyDir(PATHS.out);
await build({
engine: PATHS.engine,
outDir: PATHS.out,
withIndex: true,
withExports: false,
withEditorExports: true,
});
}());
+39
View File
@@ -0,0 +1,39 @@
const { join } = require('path');
const { ensureDir, emptyDir } = require('fs-extra');
const { spawn } = require('child_process');
const { magenta } = require('chalk');
const cli = require.resolve('@cocos/build-engine/dist/cli');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build H5 minified ${prefix}`));
(async function exec () {
const outDir = join(__dirname, '..', 'bin', 'dev', 'cc-min');
await ensureDir(outDir);
await emptyDir(outDir);
const exitCode = await new Promise((resolve, reject) => {
spawn('node', [
cli,
`--engine=${join(__dirname, '..')}`,
'--module=system',
'--build-mode=BUILD',
'--platform=HTML5',
'--physics=cannon',
`--out=${outDir}`,
'--compress',
'--sourcemap',
], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
}).on('exit', (code) => {
resolve(code);
}).on('error', (err) => {
reject(err);
});
});
if (exitCode) {
throw new Error(`Build process exit with ${exitCode}`);
}
}());
+37
View File
@@ -0,0 +1,37 @@
const { join } = require('path');
const { ensureDir, emptyDir } = require('fs-extra');
const { spawn } = require('child_process');
const { magenta } = require('chalk');
const cli = require.resolve('@cocos/build-engine/dist/cli');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Build H5 source ${prefix}`));
(async function exec () {
const outDir = join(__dirname, '..', 'bin', 'dev', 'cc');
await ensureDir(outDir);
await emptyDir(outDir);
const exitCode = await new Promise((resolve, reject) => {
spawn('node', [
cli,
`--engine=${join(__dirname, '..')}`,
'--module=system',
'--build-mode=BUILD',
'--platform=HTML5',
'--physics=cannon',
`--out=${outDir}`,
], {
shell: true,
stdio: 'inherit',
cwd: __dirname,
}).on('exit', (code) => {
resolve(code);
}).on('error', (err) => {
reject(err);
});
});
if (exitCode) {
throw new Error(`Build process exit with ${exitCode}`);
}
}());
+6 -6
View File
@@ -7,7 +7,7 @@ const fs = require('fs');
// .argv;
const targetEngineVersion = process.argv[2];
const versionRegExp = /^\d+\.\d+\.\d+$/
const versionRegExp = /^\d+\.\d+\.\d+$/;
if (!targetEngineVersion) {
console.error('please specify a target engine version');
process.exit(1);
@@ -22,21 +22,21 @@ if (!targetEngineVersion) {
* each handler needs to return the handle result.
*/
const fileHandlers = {
'./package.json' (content) {
'./package.json': function (content) {
const versionRegExp = /"version": ".*"/;
content = content.replace(versionRegExp, `"version": "${targetEngineVersion}"`);
return content;
},
'./cocos/core/global-exports.ts' (content) {
'./cocos/core/global-exports.ts': function (content) {
const versionRegExp = /engineVersion = '.*'/;
content = content.replace(versionRegExp, `engineVersion = '${targetEngineVersion}'`);
return content;
},
};
for (filePath in fileHandlers) {
let handler = fileHandlers[filePath];
for (const filePath in fileHandlers) {
const handler = fileHandlers[filePath];
let content = fs.readFileSync(filePath, 'utf8');
content = handler(content);
if (!content) {
@@ -45,5 +45,5 @@ for (filePath in fileHandlers) {
}
fs.writeFileSync(filePath, content, 'utf8');
}
console.log('Checkout engine version complete!')
console.log('Checkout engine version complete!');
process.exit(0);
+35 -33
View File
@@ -1,51 +1,53 @@
'use strict';
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { magenta } = require('chalk');
function deleteFolderRecursive(dirPath) {
if (fs.existsSync(dirPath)) {
if(fs.lstatSync(dirPath).isDirectory()) {
fs.readdirSync(dirPath).forEach(function(file) {
const curPath = path.join(dirPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
deleteFolderRecursive(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(dirPath);
console.log("deleting: "+ dirPath);
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Clear cache ${prefix}`));
function deleteFolderRecursive (dirPath) {
if (fs.existsSync(dirPath)) {
if (fs.lstatSync(dirPath).isDirectory()) {
fs.readdirSync(dirPath).forEach((file) => {
const curPath = path.join(dirPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
deleteFolderRecursive(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(dirPath);
console.log(`deleting: ${dirPath}`);
} else {
fs.unlinkSync(dirPath);
console.log(`Deleting ${dirPath}`);
}
} else {
fs.unlinkSync(dirPath);
console.log("Deleting "+ dirPath);
console.log(`not exist, skip: ${dirPath}`);
}
} else {
console.log("not exist, skip: " + dirPath);
}
};
}
const fileStream = fs.createReadStream(path.join(__dirname, "../.gitignore"));
const fileStream = fs.createReadStream(path.join(__dirname, '../.gitignore'));
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
input: fileStream,
crlfDelay: Infinity,
});
const gitignoreFiles = [];
rl.on('line', (line) => {
if (line !== "" && !line.includes("native/external/") && !line.includes("!")) {
gitignoreFiles.push(path.join(__dirname,".." ,line));
}
if (line !== '' && !line.includes('native/external/') && !line.includes('!')) {
gitignoreFiles.push(path.join(__dirname, '..', line));
}
});
rl.on('close', () => {
console.log("=================== ready to delete ===================");
console.log(gitignoreFiles);
console.log("=================== processing ===================");
gitignoreFiles.forEach((dirPath)=>{
deleteFolderRecursive(dirPath);
console.log('=================== ready to delete ===================');
console.log(gitignoreFiles);
console.log('=================== processing ===================');
gitignoreFiles.forEach((dirPath) => {
deleteFolderRecursive(dirPath);
});
});
});
+15 -15
View File
@@ -1,14 +1,16 @@
'use strict';
const { readdirSync, statSync, unlinkSync } = require('fs');
const { join } = require('path');
(() => {
const { magenta } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Clear file ${prefix}`));
(() => {
let total = 0;
let m = 0;
function step(dir) {
function step (dir) {
total++;
const names = readdirSync(dir);
@@ -17,17 +19,15 @@ const { join } = require('path');
const stat = statSync(file);
if (stat.isDirectory()) {
step(file);
} else if (
/\.d\.ts$/.test(file)
|| /\.md$/.test(file)
|| /\.markdown$/.test(file)
) {
m++;
unlinkSync(file);
} else {
if (
/\.d\.ts$/.test(file) ||
/\.md$/.test(file) ||
/\.markdown$/.test(file)
) {
m++;
unlinkSync(file);
} else {
total++;
}
total++;
}
});
}
@@ -39,4 +39,4 @@ const { join } = require('path');
step(xcode);
console.log(`${total} - ${m}`);
})();
})();
+51 -49
View File
@@ -3,7 +3,10 @@ const ps = require('path');
const fs = require('fs-extra');
const ts = require('typescript');
const del = require('del');
const chalk = require('chalk').default;
const { magenta, green, red } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Compile native TS ${prefix}`));
let clean = true;
const argv2 = process.argv[2];
@@ -21,10 +24,10 @@ function normalizePath (path) {
(async function main () {
await buildTsEngine();
await compileTsEngine();
})();
}());
async function buildTsEngine () {
console.log(chalk.green('building TS engine ...\n'));
console.log(green('building TS engine ...\n'));
await ccbuild.buildEngine({
// NOTE: for now only OH platform supports building TS engine
platform: 'OPEN_HARMONY',
@@ -32,41 +35,41 @@ async function buildTsEngine () {
engine: engineRoot,
// TODO: some modules still cannot be compile
features: [
"base",
"gfx-webgl",
"gfx-webgl2",
"3d",
"animation",
"skeletal-animation",
"2d",
"ui",
"particle",
"particle-2d",
"physics-framework",
'base',
'gfx-webgl',
'gfx-webgl2',
'3d',
'animation',
'skeletal-animation',
'2d',
'ui',
'particle',
'particle-2d',
'physics-framework',
// "physics-cannon",
// "physics-physx",
// "physics-ammo",
"physics-builtin",
'physics-builtin',
// "physics-2d-framework",
// "physics-2d-box2d",
// "physics-2d-builtin",
"intersection-2d",
"primitive",
"profiler",
'intersection-2d',
'primitive',
'profiler',
// "occlusion-query",
// "geometry-renderer",
// "debug-renderer",
"audio",
"video",
'audio',
'video',
// "xr",
// "terrain",
"webview",
"tween",
'webview',
'tween',
// "tiled-map",
// "spine",
// "dragon-bones",
// "marionette",
"custom-pipeline",
'custom-pipeline',
// "light-probe",
],
mode: 'BUILD',
@@ -78,36 +81,36 @@ async function buildTsEngine () {
}
async function compileTsEngine () {
console.log(chalk.green('compiling TS engine ...\n'));
console.log(green('compiling TS engine ...\n'));
const entryDir = normalizePath(ps.join(buildOutput, 'exports'));
const entries = fs.readdirSync(entryDir).map(file => normalizePath(ps.join(entryDir, file)));
console.log('typescript version: ' + ts.version);
const entries = fs.readdirSync(entryDir).map((file) => normalizePath(ps.join(entryDir, file)));
console.log(`typescript version: ${ts.version}`);
console.log('compile source file: ', entries);
const compilerOptions = {
strict: true,
noImplicitAny: false,
experimentalDecorators: true,
lib: ["lib.es2015.d.ts", "lib.es2017.d.ts"],
lib: ['lib.es2015.d.ts', 'lib.es2017.d.ts'],
types: [
"./@types/editor-extends",
"./@types/globals",
"./@types/jsb",
"./@types/lib.dom",
"./@types/webGL.extras",
"./@types/webGL2.extras",
'./@types/editor-extends',
'./@types/globals',
'./@types/jsb',
'./@types/lib.dom',
'./@types/webGL.extras',
'./@types/webGL2.extras',
// pal
"./@types/pal/system-info",
"./@types/pal/screen-adapter",
"./@types/pal/minigame",
"./@types/pal/audio",
"./@types/pal/input",
"./@types/pal/env",
"./@types/pal/pacer",
"./@types/pal/wasm",
].map(typePath => normalizePath(ps.join(buildOutput, typePath))),
'./@types/pal/system-info',
'./@types/pal/screen-adapter',
'./@types/pal/minigame',
'./@types/pal/audio',
'./@types/pal/input',
'./@types/pal/env',
'./@types/pal/pacer',
'./@types/pal/wasm',
].map((typePath) => normalizePath(ps.join(buildOutput, typePath))),
skipLibCheck: true,
rootDir: buildOutput,
// outDir: normalizePath(ps.join(buildOutput, '__out__')),
@@ -119,7 +122,7 @@ async function compileTsEngine () {
const program = ts.createProgram(entries, compilerOptions);
const emitResult = program.emit();
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
let hasError = false;
for (const diagnostic of allDiagnostics) {
let printer;
@@ -127,7 +130,7 @@ async function compileTsEngine () {
case ts.DiagnosticCategory.Error:
printer = console.error;
if (!hasError) {
printer(chalk.red('\n============= | Error | ========================\n'))
printer(red('\n============= | Error | ========================\n'));
hasError = true;
}
break;
@@ -153,14 +156,13 @@ async function compileTsEngine () {
}
if (clean) {
console.log(chalk.green(`\nclean output: ${buildOutput}\n`));
await del(buildOutput, {force: true});
console.log(green(`\nclean output: ${buildOutput}\n`));
await del(buildOutput, { force: true });
}
if (hasError) {
if (clean) {
console.log(chalk.red(`\nNOTE: please run 'node ./scripts/compile-native-ts.js --no-clean' locally to locate the error !\n`));
console.log(red(`\nNOTE: please run 'node ./scripts/compile-native-ts.js --no-clean' locally to locate the error !\n`));
}
process.exit(1);
} else {
+16 -12
View File
@@ -3,13 +3,17 @@ const fs = require('fs');
const fsExt = require('fs-extra');
const { exec } = require('child_process');
const del = require('del');
const chalk = require('chalk').default;
const chalk = require('chalk');
const distDir = join(__dirname, '../bin/adapter/runtime');
const { magenta } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Fetch RAL ${prefix}`));
function forceCopyFileSync (src, dst) {
const content = fs.readFileSync(src, 'utf8');
fsExt.outputFileSync(dst, content, {encoding: 'utf8'});
fsExt.outputFileSync(dst, content, { encoding: 'utf8' });
}
function join (...paths) {
@@ -70,7 +74,7 @@ function checkFile () {
}
/**
* @param {string} cmd
* @param {string} cmd
* @param {string} cwd
* @returns {Promise<void>}
*/
@@ -94,21 +98,21 @@ function runCommand (cmd, cwd) {
ls.stdout.on('close', () => {
resolve(ls.exitCode);
});
})
});
}
function copyRal () {
console.log(`Copy files from '${repositoryPath}' to '${distDir}'\n`);
// copy web-adapter
['web-adapter.js', 'web-adapter.min.js'].forEach(fileName => {
['web-adapter.js', 'web-adapter.min.js'].forEach((fileName) => {
const src = join(repositoryPath, 'dist/common', fileName);
const dst = join(distDir, fileName);
forceCopyFileSync(src, dst);
});
// copy ral
['cocos-play', 'huawei-quick-game', 'link-sure', 'oppo-mini-game', 'qtt', 'vivo-mini-game'].forEach(platformName => {
['ral.js', 'ral.min.js'].forEach(fileName => {
['cocos-play', 'huawei-quick-game', 'link-sure', 'oppo-mini-game', 'qtt', 'vivo-mini-game'].forEach((platformName) => {
['ral.js', 'ral.min.js'].forEach((fileName) => {
const src = join(repositoryPath, 'dist/platforms', platformName, fileName);
const dst = join(distDir, platformName, fileName);
forceCopyFileSync(src, dst);
@@ -122,13 +126,13 @@ async function cleanOldRal () {
// del local commit
delPatterns.push(localCommitFile);
// del web adapter
['web-adapter.js', 'web-adapter.min.js'].forEach(fileName => {
['web-adapter.js', 'web-adapter.min.js'].forEach((fileName) => {
const dst = join(distDir, fileName);
delPatterns.push(dst);
});
// del ral
['cocos-play', 'huawei-quick-game', 'link-sure', 'oppo-mini-game', 'qtt', 'vivo-mini-game'].forEach(platformName => {
['ral.js', 'ral.min.js'].forEach(fileName => {
['cocos-play', 'huawei-quick-game', 'link-sure', 'oppo-mini-game', 'qtt', 'vivo-mini-game'].forEach((platformName) => {
['ral.js', 'ral.min.js'].forEach((fileName) => {
const dst = join(distDir, platformName, fileName);
delPatterns.push(dst);
});
@@ -143,7 +147,7 @@ async function writeLocalCommitFile () {
}
/**
* @param {string} dirPath
* @param {string} dirPath
* @returns {Promise<void>}
*/
async function removeDir (dirPath) {
@@ -162,7 +166,7 @@ async function removeDir (dirPath) {
await cleanOldRal();
await removeDir(repositoryPath);
try {
let exitCode = await runCommand('git clone git@github.com:yangws/runtime-web-adapter.git', __dirname);
const exitCode = await runCommand('git clone git@github.com:yangws/runtime-web-adapter.git', __dirname);
if (exitCode !== 0) {
await removeDir(repositoryPath);
await runCommand('git clone https://github.com/yangws/runtime-web-adapter', __dirname);
+18 -13
View File
@@ -1,22 +1,28 @@
'use strict';
const { join } = require('path');
const { spawn } = require('child_process');
const { magenta } = require('chalk');
const prefix = ''.padStart(20, '=');
console.log(magenta(`${prefix} Generate DOC infos ${prefix}`));
const PATHS = {
plugin: join(__dirname, './typedoc-plugin'),
engine: join(__dirname, '..'),
};
function bash(cmd, args, options = {}) {
function bash (cmd, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, options);
child.stdout && child.stdout.on('data', (data) => {
console.log(data + '');
});
child.stderr && child.stderr.on('data', (data) => {
console.error(data + '');
});
if (child.stdout) {
child.stdout.on('data', (data) => {
console.log(`${data}`);
});
}
if (child.stderr) {
child.stderr.on('data', (data) => {
console.error(`${data}`);
});
}
child.on('close', (code) => {
resolve(code);
});
@@ -26,7 +32,7 @@ function bash(cmd, args, options = {}) {
});
}
async function exec() {
async function exec () {
await bash('npm', ['install', 'typedoc@0.22.18', '--no-save'], {
cwd: PATHS.engine,
});
@@ -34,15 +40,14 @@ async function exec() {
await bash('npm', ['install', '--only=production'], {
cwd: PATHS.plugin,
});
await bash('npm', ['install', './scripts/typedoc-plugin', '--no-save'], {
cwd: PATHS.engine,
});
await bash('npx', ['typedoc'], {
cwd: PATHS.engine,
});
}
exec();
+3 -3
View File
@@ -5,10 +5,10 @@ if (typeof branchName === 'undefined') {
console.error('Need to specify the current branch name in git repository');
process.exit(1);
}
const branchRegExp = /^v?(\d+\.\d+\.\d+)(?:-.*)?$/
const branchRegExp = /^v?(\d+\.\d+\.\d+)(?:-.*)?$/;
const matchResult = branchName.match(branchRegExp);
if (!(matchResult && matchResult[1])) {
console.warn(`Invalid branch name: "${branchName}", skip engine version validation.`)
console.warn(`Invalid branch name: "${branchName}", skip engine version validation.`);
process.exit(0);
}
const branchVersion = matchResult[1];
@@ -17,7 +17,7 @@ const versionRegExpMap = {
'./package.json': /"version": "(.*)"/,
'./cocos/core/global-exports.ts': /engineVersion = '(.*)'/,
};
for (filePath in versionRegExpMap) {
for (const filePath in versionRegExpMap) {
const regExp = versionRegExpMap[filePath];
const content = fs.readFileSync(filePath, 'utf8');
const version = content.match(regExp)[1];