Commit b6724e14 authored by rockyl's avatar rockyl

init

parents
Pipeline #163372 failed with stages
in 0 seconds
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
import xml from 'xml';
import path from 'path';
import fs from 'fs-extra';
import Color from 'color';
import generateUUID from 'uuid/v4';
/**
* Created by rockyl on 2019-08-09.
*/
const PSD = require('psd');
async function getTree(psdFilePath) {
const psd = await PSD.open(psdFilePath);
const root = {};
walk(psd.tree(), root);
return root;
}
function walk(psNode, dataNode) {
const {left: pLeft = 0, top: pTop = 0,} = psNode.parent || {};
const {left, top, width, height, name, layer: {opacity, visible}} = psNode;
const x = left - pLeft;
const y = top - pTop;
Object.assign(dataNode, {x, y, width, height, alpha: opacity / 255, visible, name, origin: psNode, label: `${name} > [${x}, ${y}, ${width}, ${height}]`});
if (psNode.children() && psNode.children().length > 0){
dataNode.children = [];
}
let children = psNode.children();
for (let i = children.length - 1; i >= 0; i--) {
const childPsNode = children[i];
const childDataNode = {};
dataNode.children.push(childDataNode);
walk(childPsNode, childDataNode);
}
}
/**
* Created by rockyl on 2019-08-10.
*/
async function walkNode(node, callback, includeSelf = false) {
if (includeSelf) {
await callback(node, null);
}
if (node.children && node.children.length > 0) {
for (let childNode of node.children) {
await callback(childNode, node);
const result = await walkNode(childNode, callback);
if (result === true) {
break;
}
}
}
}
async function walkObject(obj, callback) {
if(typeof obj === "object"){
for (let key of Object.keys(obj)) {
const value = obj[key];
await callback(key, value, obj);
const result = await walkObject(value, callback);
if (result === true) {
break;
}
}
}
}
/**
* Created by rockyl on 2019-08-10.
*
* 导出exml
*/
const elementTpls = {
'e:Group': [],
'e:Image': {_attr: {source: '{res}'}},
'e:Button': [
{_attr: {label: '{1}',}},
{
'e:skinName': [
{
'e:Skin': [
{_attr: {states: 'up,down,disabled'}},
{
'e:Image': {_attr: {width: '100%', height: '100%', source: '{res}'}},
},
{
'e:Label': {_attr: {id: 'labelDisplay', horizontalCenter: '0', verticalCenter: '0'}},
}
]
}
]
}
]
};
async function execute(psdFile, options) {
const {skinFilePath, skinClassName, resPath, resGroupName} = options;
const tree = await getTree(psdFile);
const exmlRoot = [
{
_attr: {
class: skinClassName,
width: tree.width,
height: tree.height,
'xmlns:e': "http://ns.egret.com/eui",
'xmlns:w': "http://ns.egret.com/wing",
},
},
];
const exmlData = {
'e:Skin': exmlRoot
};
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible} = node;
let attributes = {width, height, alpha, visible};
if (x !== 0) {
attributes.x = x;
}
if (y !== 0) {
attributes.y = y;
}
let element;
let tagName;
let imageResName;
let params;
let hasChild = node.hasOwnProperty('children');
if (hasChild) {
tagName = 'e:Group';
} else {
const nameParams = node.name.split('|');
const nodeName = nameParams[0];
attributes.name = nodeName;
imageResName = resGroupName + '_' + nodeName;
const imageFilePath = path.join(resPath, resGroupName + '_p', nodeName + '.png');
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
if (nameParams.length === 1) {
tagName = 'e:Image';
} else {
params = nameParams[1].split(',');
tagName = 'e:' + params[0];
}
//element[tagName] = {_attr: attributes};
}
let elementTpl = elementTpls[tagName];
let elementContent;
if (elementTpl) {
elementContent = JSON.parse(JSON.stringify(elementTpl));
} else {
elementContent = {};
}
element = {
[tagName]: elementContent,
};
let attr;
if (Array.isArray(elementContent)) {
attr = elementContent.find(item => item._attr);
if (!attr) {
attr = {_attr: {}};
elementContent.unshift(attr);
}
} else {
attr = elementContent;
}
Object.assign(attr._attr, attributes);
if (imageResName) {
await walkObject(element, function (key, value, obj) {
if (value === '{res}') {
obj[key] = imageResName;
} else if (typeof value === 'string') {
const result = value.match(/{(\d+)}/g);
if(result){
for(let item of result){
const pi = parseInt(item.match(/{(\d+)}/)[1]);
value = value.replace(item, params[pi]);
}
obj[key] = value;
}
}
});
}
if (hasChild) {
node.exmlNode = elementContent;
}
const exmlNode = parent.exmlNode || exmlRoot;
exmlNode.push(element);
});
let exmlStr = xml(exmlData, {declaration: true, indent: true});
await fs.ensureDir(path.dirname(skinFilePath));
await fs.writeFile(skinFilePath, exmlStr);
}
/**
* Created by rockyl on 2019-09-26.
*
* 导出zeroing的视图
*/
async function execute$1(psdFile, options) {
const {
imagesPath,
} = options;
const tree = await getTree(psdFile);
let viewRoot = {
name: path.basename(psdFile, '.psd'),
type: 'node',
};
const assets = [];
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible, origin: {layer: {typeTool, solidColor}}} = node;
let properties = {
width, height, alpha, visible,
};
let viewNode = {
name: node.name,
properties,
};
if (x !== 0) {
properties.x = x;
}
if (y !== 0) {
properties.y = y;
}
if(typeTool){
let fontInfo= typeTool();
const fonts = fontInfo.fonts();
const styles = fontInfo.styles();
const {RunLengthArray} = fontInfo.engineData.EngineDict.StyleRun;
properties.text = fontInfo.textValue;
properties.textflow = {
fonts, styles, RunLengthArray,
};
viewNode.type = 'label';
}else if(solidColor){
const {r, g, b} = solidColor();
let color = Color({r, g, b});
viewNode.type = 'rect';
properties.fillColor = '#' + color.rgbNumber().toString(16);
}else{
if(node.hasOwnProperty('children')){
viewNode.type = 'node';
}else{
viewNode.type = 'image';
const uuid = generateUUID();
const fileName = Date.now().valueOf();
const ext = '.png';
properties.source = 'asset|' + uuid;
const imageFilePath = path.join(imagesPath, fileName + ext);
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
assets.push({
name: fileName,
ext,
uuid,
});
}
}
let viewParent = parent.view || viewRoot;
if (!viewParent.hasOwnProperty('children')) {
viewParent.children = [];
}
viewParent.children.push(viewNode);
node.view = viewNode;
});
return {
view: viewRoot,
assets,
}
}
export { getTree, execute as toEgret, execute$1 as toZeroing };
//# sourceMappingURL=index.es.js.map
This diff is collapsed.
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var xml = _interopDefault(require('xml'));
var path = _interopDefault(require('path'));
var fs = _interopDefault(require('fs-extra'));
var Color = _interopDefault(require('color'));
var generateUUID = _interopDefault(require('uuid/v4'));
/**
* Created by rockyl on 2019-08-09.
*/
const PSD = require('psd');
async function getTree(psdFilePath) {
const psd = await PSD.open(psdFilePath);
const root = {};
walk(psd.tree(), root);
return root;
}
function walk(psNode, dataNode) {
const {left: pLeft = 0, top: pTop = 0,} = psNode.parent || {};
const {left, top, width, height, name, layer: {opacity, visible}} = psNode;
const x = left - pLeft;
const y = top - pTop;
Object.assign(dataNode, {x, y, width, height, alpha: opacity / 255, visible, name, origin: psNode, label: `${name} > [${x}, ${y}, ${width}, ${height}]`});
if (psNode.children() && psNode.children().length > 0){
dataNode.children = [];
}
let children = psNode.children();
for (let i = children.length - 1; i >= 0; i--) {
const childPsNode = children[i];
const childDataNode = {};
dataNode.children.push(childDataNode);
walk(childPsNode, childDataNode);
}
}
/**
* Created by rockyl on 2019-08-10.
*/
async function walkNode(node, callback, includeSelf = false) {
if (includeSelf) {
await callback(node, null);
}
if (node.children && node.children.length > 0) {
for (let childNode of node.children) {
await callback(childNode, node);
const result = await walkNode(childNode, callback);
if (result === true) {
break;
}
}
}
}
async function walkObject(obj, callback) {
if(typeof obj === "object"){
for (let key of Object.keys(obj)) {
const value = obj[key];
await callback(key, value, obj);
const result = await walkObject(value, callback);
if (result === true) {
break;
}
}
}
}
/**
* Created by rockyl on 2019-08-10.
*
* 导出exml
*/
const elementTpls = {
'e:Group': [],
'e:Image': {_attr: {source: '{res}'}},
'e:Button': [
{_attr: {label: '{1}',}},
{
'e:skinName': [
{
'e:Skin': [
{_attr: {states: 'up,down,disabled'}},
{
'e:Image': {_attr: {width: '100%', height: '100%', source: '{res}'}},
},
{
'e:Label': {_attr: {id: 'labelDisplay', horizontalCenter: '0', verticalCenter: '0'}},
}
]
}
]
}
]
};
async function execute(psdFile, options) {
const {skinFilePath, skinClassName, resPath, resGroupName} = options;
const tree = await getTree(psdFile);
const exmlRoot = [
{
_attr: {
class: skinClassName,
width: tree.width,
height: tree.height,
'xmlns:e': "http://ns.egret.com/eui",
'xmlns:w': "http://ns.egret.com/wing",
},
},
];
const exmlData = {
'e:Skin': exmlRoot
};
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible} = node;
let attributes = {width, height, alpha, visible};
if (x !== 0) {
attributes.x = x;
}
if (y !== 0) {
attributes.y = y;
}
let element;
let tagName;
let imageResName;
let params;
let hasChild = node.hasOwnProperty('children');
if (hasChild) {
tagName = 'e:Group';
} else {
const nameParams = node.name.split('|');
const nodeName = nameParams[0];
attributes.name = nodeName;
imageResName = resGroupName + '_' + nodeName;
const imageFilePath = path.join(resPath, resGroupName + '_p', nodeName + '.png');
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
if (nameParams.length === 1) {
tagName = 'e:Image';
} else {
params = nameParams[1].split(',');
tagName = 'e:' + params[0];
}
//element[tagName] = {_attr: attributes};
}
let elementTpl = elementTpls[tagName];
let elementContent;
if (elementTpl) {
elementContent = JSON.parse(JSON.stringify(elementTpl));
} else {
elementContent = {};
}
element = {
[tagName]: elementContent,
};
let attr;
if (Array.isArray(elementContent)) {
attr = elementContent.find(item => item._attr);
if (!attr) {
attr = {_attr: {}};
elementContent.unshift(attr);
}
} else {
attr = elementContent;
}
Object.assign(attr._attr, attributes);
if (imageResName) {
await walkObject(element, function (key, value, obj) {
if (value === '{res}') {
obj[key] = imageResName;
} else if (typeof value === 'string') {
const result = value.match(/{(\d+)}/g);
if(result){
for(let item of result){
const pi = parseInt(item.match(/{(\d+)}/)[1]);
value = value.replace(item, params[pi]);
}
obj[key] = value;
}
}
});
}
if (hasChild) {
node.exmlNode = elementContent;
}
const exmlNode = parent.exmlNode || exmlRoot;
exmlNode.push(element);
});
let exmlStr = xml(exmlData, {declaration: true, indent: true});
await fs.ensureDir(path.dirname(skinFilePath));
await fs.writeFile(skinFilePath, exmlStr);
}
/**
* Created by rockyl on 2019-09-26.
*
* 导出zeroing的视图
*/
async function execute$1(psdFile, options) {
const {
imagesPath,
} = options;
const tree = await getTree(psdFile);
let viewRoot = {
name: path.basename(psdFile, '.psd'),
type: 'node',
};
const assets = [];
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible, origin: {layer: {typeTool, solidColor}}} = node;
let properties = {
width, height, alpha, visible,
};
let viewNode = {
name: node.name,
properties,
};
if (x !== 0) {
properties.x = x;
}
if (y !== 0) {
properties.y = y;
}
if(typeTool){
let fontInfo= typeTool();
const fonts = fontInfo.fonts();
const styles = fontInfo.styles();
const {RunLengthArray} = fontInfo.engineData.EngineDict.StyleRun;
properties.text = fontInfo.textValue;
properties.textflow = {
fonts, styles, RunLengthArray,
};
viewNode.type = 'label';
}else if(solidColor){
const {r, g, b} = solidColor();
let color = Color({r, g, b});
viewNode.type = 'rect';
properties.fillColor = '#' + color.rgbNumber().toString(16);
}else{
if(node.hasOwnProperty('children')){
viewNode.type = 'node';
}else{
viewNode.type = 'image';
const uuid = generateUUID();
const fileName = Date.now().valueOf();
const ext = '.png';
properties.source = 'asset|' + uuid;
const imageFilePath = path.join(imagesPath, fileName + ext);
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
assets.push({
name: fileName,
ext,
uuid,
});
}
}
let viewParent = parent.view || viewRoot;
if (!viewParent.hasOwnProperty('children')) {
viewParent.children = [];
}
viewParent.children.push(viewNode);
node.view = viewNode;
});
return {
view: viewRoot,
assets,
}
}
exports.getTree = getTree;
exports.toEgret = execute;
exports.toZeroing = execute$1;
//# sourceMappingURL=index.js.map
This diff is collapsed.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('xml'), require('path'), require('fs-extra'), require('color'), require('uuid/v4')) :
typeof define === 'function' && define.amd ? define(['exports', 'xml', 'path', 'fs-extra', 'color', 'uuid/v4'], factory) :
(global = global || self, factory(global['psd-parse'] = {}, global.xml, global.path, global.fs, global.Color, global.generateUUID));
}(this, function (exports, xml, path, fs, Color, generateUUID) { 'use strict';
xml = xml && xml.hasOwnProperty('default') ? xml['default'] : xml;
path = path && path.hasOwnProperty('default') ? path['default'] : path;
fs = fs && fs.hasOwnProperty('default') ? fs['default'] : fs;
Color = Color && Color.hasOwnProperty('default') ? Color['default'] : Color;
generateUUID = generateUUID && generateUUID.hasOwnProperty('default') ? generateUUID['default'] : generateUUID;
/**
* Created by rockyl on 2019-08-09.
*/
const PSD = require('psd');
async function getTree(psdFilePath) {
const psd = await PSD.open(psdFilePath);
const root = {};
walk(psd.tree(), root);
return root;
}
function walk(psNode, dataNode) {
const {left: pLeft = 0, top: pTop = 0,} = psNode.parent || {};
const {left, top, width, height, name, layer: {opacity, visible}} = psNode;
const x = left - pLeft;
const y = top - pTop;
Object.assign(dataNode, {x, y, width, height, alpha: opacity / 255, visible, name, origin: psNode, label: `${name} > [${x}, ${y}, ${width}, ${height}]`});
if (psNode.children() && psNode.children().length > 0){
dataNode.children = [];
}
let children = psNode.children();
for (let i = children.length - 1; i >= 0; i--) {
const childPsNode = children[i];
const childDataNode = {};
dataNode.children.push(childDataNode);
walk(childPsNode, childDataNode);
}
}
/**
* Created by rockyl on 2019-08-10.
*/
async function walkNode(node, callback, includeSelf = false) {
if (includeSelf) {
await callback(node, null);
}
if (node.children && node.children.length > 0) {
for (let childNode of node.children) {
await callback(childNode, node);
const result = await walkNode(childNode, callback);
if (result === true) {
break;
}
}
}
}
async function walkObject(obj, callback) {
if(typeof obj === "object"){
for (let key of Object.keys(obj)) {
const value = obj[key];
await callback(key, value, obj);
const result = await walkObject(value, callback);
if (result === true) {
break;
}
}
}
}
/**
* Created by rockyl on 2019-08-10.
*
* 导出exml
*/
const elementTpls = {
'e:Group': [],
'e:Image': {_attr: {source: '{res}'}},
'e:Button': [
{_attr: {label: '{1}',}},
{
'e:skinName': [
{
'e:Skin': [
{_attr: {states: 'up,down,disabled'}},
{
'e:Image': {_attr: {width: '100%', height: '100%', source: '{res}'}},
},
{
'e:Label': {_attr: {id: 'labelDisplay', horizontalCenter: '0', verticalCenter: '0'}},
}
]
}
]
}
]
};
async function execute(psdFile, options) {
const {skinFilePath, skinClassName, resPath, resGroupName} = options;
const tree = await getTree(psdFile);
const exmlRoot = [
{
_attr: {
class: skinClassName,
width: tree.width,
height: tree.height,
'xmlns:e': "http://ns.egret.com/eui",
'xmlns:w': "http://ns.egret.com/wing",
},
},
];
const exmlData = {
'e:Skin': exmlRoot
};
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible} = node;
let attributes = {width, height, alpha, visible};
if (x !== 0) {
attributes.x = x;
}
if (y !== 0) {
attributes.y = y;
}
let element;
let tagName;
let imageResName;
let params;
let hasChild = node.hasOwnProperty('children');
if (hasChild) {
tagName = 'e:Group';
} else {
const nameParams = node.name.split('|');
const nodeName = nameParams[0];
attributes.name = nodeName;
imageResName = resGroupName + '_' + nodeName;
const imageFilePath = path.join(resPath, resGroupName + '_p', nodeName + '.png');
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
if (nameParams.length === 1) {
tagName = 'e:Image';
} else {
params = nameParams[1].split(',');
tagName = 'e:' + params[0];
}
//element[tagName] = {_attr: attributes};
}
let elementTpl = elementTpls[tagName];
let elementContent;
if (elementTpl) {
elementContent = JSON.parse(JSON.stringify(elementTpl));
} else {
elementContent = {};
}
element = {
[tagName]: elementContent,
};
let attr;
if (Array.isArray(elementContent)) {
attr = elementContent.find(item => item._attr);
if (!attr) {
attr = {_attr: {}};
elementContent.unshift(attr);
}
} else {
attr = elementContent;
}
Object.assign(attr._attr, attributes);
if (imageResName) {
await walkObject(element, function (key, value, obj) {
if (value === '{res}') {
obj[key] = imageResName;
} else if (typeof value === 'string') {
const result = value.match(/{(\d+)}/g);
if(result){
for(let item of result){
const pi = parseInt(item.match(/{(\d+)}/)[1]);
value = value.replace(item, params[pi]);
}
obj[key] = value;
}
}
});
}
if (hasChild) {
node.exmlNode = elementContent;
}
const exmlNode = parent.exmlNode || exmlRoot;
exmlNode.push(element);
});
let exmlStr = xml(exmlData, {declaration: true, indent: true});
await fs.ensureDir(path.dirname(skinFilePath));
await fs.writeFile(skinFilePath, exmlStr);
}
/**
* Created by rockyl on 2019-09-26.
*
* 导出zeroing的视图
*/
async function execute$1(psdFile, options) {
const {
imagesPath,
} = options;
const tree = await getTree(psdFile);
let viewRoot = {
name: path.basename(psdFile, '.psd'),
type: 'node',
};
const assets = [];
await walkNode(tree, async function (node, parent) {
const {x, y, width, height, alpha, visible, origin: {layer: {typeTool, solidColor}}} = node;
let properties = {
width, height, alpha, visible,
};
let viewNode = {
name: node.name,
properties,
};
if (x !== 0) {
properties.x = x;
}
if (y !== 0) {
properties.y = y;
}
if(typeTool){
let fontInfo= typeTool();
const fonts = fontInfo.fonts();
const styles = fontInfo.styles();
const {RunLengthArray} = fontInfo.engineData.EngineDict.StyleRun;
properties.text = fontInfo.textValue;
properties.textflow = {
fonts, styles, RunLengthArray,
};
viewNode.type = 'label';
}else if(solidColor){
const {r, g, b} = solidColor();
let color = Color({r, g, b});
viewNode.type = 'rect';
properties.fillColor = '#' + color.rgbNumber().toString(16);
}else{
if(node.hasOwnProperty('children')){
viewNode.type = 'node';
}else{
viewNode.type = 'image';
const uuid = generateUUID();
const fileName = Date.now().valueOf();
const ext = '.png';
properties.source = 'asset|' + uuid;
const imageFilePath = path.join(imagesPath, fileName + ext);
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
assets.push({
name: fileName,
ext,
uuid,
});
}
}
let viewParent = parent.view || viewRoot;
if (!viewParent.hasOwnProperty('children')) {
viewParent.children = [];
}
viewParent.children.push(viewNode);
node.view = viewNode;
});
return {
view: viewRoot,
assets,
}
}
exports.getTree = getTree;
exports.toEgret = execute;
exports.toZeroing = execute$1;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=index.umd.js.map
This diff is collapsed.
{
"name": "psd-parse",
"version": "1.0.0",
"main": "dist/index.js",
"license": "MIT",
"dependencies": {
"color": "^3.1.2",
"fs-extra": "^8.1.0",
"psd": "^3.2.0",
"uuid": "^3.3.3",
"xml": "^1.0.1"
},
"scripts": {
"build": "rollup -c"
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
/**
* Created by rockyl on 2018/11/16.
*/
const name = 'psd-parse';
export default {
input: 'src/index.js',
output: [
{
file: `dist/index.js`,
format: 'cjs',
sourcemap: true,
},
{
file: `dist/index.es.js`,
format: 'es',
sourcemap: true,
},
{
file: `dist/index.umd.js`,
format: 'umd',
sourcemap: true,
name,
}
],
plugins: [
]
};
{
"version": "0.2.0",
"configurations": [
{
"name": "Wing 内置播放器调试",
"type": "chrome",
"request": "launch",
"file": "index.html",
//"url": "http://mysite.com/index.html",
"runtimeExecutable": "${execPath}",
"sourceMaps": true,
"webRoot": "${workspaceRoot}",
"preLaunchTask":"build",
"port":5773
},
{
"name": "使用本机 Chrome 调试",
"type": "chrome",
"request": "launch",
"file": "index.html",
//"url": "http://mysite.com/index.html",
"runtimeExecutable": "",
"sourceMaps": true,
"webRoot": "${workspaceRoot}",
"preLaunchTask":"build",
"userDataDir":"${tmpdir}",
"port":5773
}
]
}
\ No newline at end of file
{
"version": "0.1.0",
"command": "egret",
"isShellCommand": true,
"tasks": [
{
"taskName": "build",
"showOutput": "always",
"args": [
"build",
"-sourcemap"
],
"problemMatcher": "$tsc"
},
{
"taskName": "clean",
"showOutput": "always",
"args": [
"build",
"-e"
],
"problemMatcher": "$tsc"
},
{
"taskName": "publish",
"showOutput": "always",
"args": [
"publish"
],
"problemMatcher": "$tsc"
}
]
}
\ No newline at end of file
{"/Users/rockyl/WorkSpaces/VisualEditor/psd-parse/samples/egret-demo/design/images/main_p":43863000}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
{
"engineVersion": "5.2.25",
"compilerVersion": "5.2.25",
"template": {},
"target": {
"current": "web"
},
"modules": [
{
"name": "egret"
},
{
"name": "eui"
},
{
"name": "assetsmanager"
},
{
"name": "tween"
},
{
"name": "promise"
}
]
}
\ No newline at end of file
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var xml = _interopDefault(require('xml'));
var path = _interopDefault(require('path'));
var fs = _interopDefault(require('fs-extra'));
/**
* Created by rockyl on 2019-08-09.
*/
const PSD = require('psd');
async function getTree(psdFilePath) {
const psd = await PSD.open(psdFilePath);
const root = {};
walk(psd.tree(), root);
return root;
}
function walk(psNode, dataNode) {
const {left: pLeft = 0, top: pTop = 0,} = psNode.parent || {};
const {left, top, width, height, name} = psNode;
const x = left - pLeft;
const y = top - pTop;
Object.assign(dataNode, {x, y, width, height, name, origin: psNode, label: `${name} > [${x}, ${y}, ${width}, ${height}]`});
if (psNode.children() && psNode.children().length > 0){
dataNode.children = [];
}
let children = psNode.children();
for (let i = children.length - 1; i >= 0; i--) {
const childPsNode = children[i];
const childDataNode = {};
dataNode.children.push(childDataNode);
walk(childPsNode, childDataNode);
}
}
/**
* Created by rockyl on 2019-08-10.
*/
async function walkNode(node, callback, includeSelf = false) {
if (includeSelf) {
await callback(node, null);
}
if (node.children && node.children.length > 0) {
for (let childNode of node.children) {
await callback(childNode, node);
const result = await walkNode(childNode, callback);
if (result === true) {
break;
}
}
}
}
async function walkObject(obj, callback) {
if(typeof obj === "object"){
for (let key of Object.keys(obj)) {
const value = obj[key];
await callback(key, value, obj);
const result = await walkObject(value, callback);
if (result === true) {
break;
}
}
}
}
/**
* Created by rockyl on 2019-08-10.
*/
const elementTpls = {
'e:Group': [],
'e:Image': {_attr: {source: '{res}'}},
'e:Button': [
{_attr: {label: '{1}',}},
{
'e:skinName': [
{
'e:Skin': [
{_attr: {states: 'up,down,disabled'}},
{
'e:Image': {_attr: {width: '100%', height: '100%', source: '{res}'}},
},
{
'e:Label': {_attr: {id: 'labelDisplay', horizontalCenter: '0', verticalCenter: '0'}},
}
]
}
]
}
]
};
async function execute(psdFile, options) {
const {skinFilePath, skinClassName, resPath, resGroupName} = options;
const tree = await getTree(psdFile);
const exmlRoot = [
{
_attr: {
class: skinClassName,
width: tree.width,
height: tree.height,
'xmlns:e': "http://ns.egret.com/eui",
'xmlns:w': "http://ns.egret.com/wing",
},
},
];
const exmlData = {
'e:Skin': exmlRoot
};
await walkNode(tree, async function (node, parent) {
const {x, y, width, height} = node;
let attributes = {width, height};
if (x !== 0) {
attributes.x = x;
}
if (y !== 0) {
attributes.y = y;
}
let element;
let tagName;
let imageResName;
let params;
let hasChild = node.hasOwnProperty('children');
if (hasChild) {
tagName = 'e:Group';
} else {
const nameParams = node.name.split('|');
const nodeName = nameParams[0];
attributes.name = nodeName;
imageResName = resGroupName + '_' + nodeName;
const imageFilePath = path.join(resPath, resGroupName + '_p', nodeName + '.png');
await fs.ensureDir(path.dirname(imageFilePath));
await node.origin.saveAsPng(imageFilePath);
if (nameParams.length === 1) {
tagName = 'e:Image';
} else {
params = nameParams[1].split(',');
tagName = 'e:' + params[0];
}
//element[tagName] = {_attr: attributes};
}
let elementTpl = elementTpls[tagName];
let elementContent;
if (elementTpl) {
elementContent = JSON.parse(JSON.stringify(elementTpl));
} else {
elementContent = {};
}
element = {
[tagName]: elementContent,
};
let attr;
if (Array.isArray(elementContent)) {
attr = elementContent.find(item => item._attr);
if (!attr) {
attr = {_attr: {}};
elementContent.unshift(attr);
}
} else {
attr = elementContent;
}
Object.assign(attr._attr, attributes);
if (imageResName) {
await walkObject(element, function (key, value, obj) {
if (value === '{res}') {
obj[key] = imageResName;
} else if (typeof value === 'string') {
const result = value.match(/{(\d+)}/g);
if(result){
for(let item of result){
const pi = parseInt(item.match(/{(\d+)}/)[1]);
value = value.replace(item, params[pi]);
}
obj[key] = value;
}
}
});
}
if (hasChild) {
node.exmlNode = elementContent;
}
const exmlNode = parent.exmlNode || exmlRoot;
exmlNode.push(element);
});
let exmlStr = xml(exmlData, {declaration: true, indent: true});
await fs.ensureDir(path.dirname(skinFilePath));
await fs.writeFile(skinFilePath, exmlStr);
}
/**
* Created by rockyl on 2019-08-08.
*/
/**
* Created by rockyl on 2019-08-10.
*/
(async function generate() {
await execute('psd/test.psd', {
skinFilePath: '/Users/rockyl/WorkSpaces/VisualEditor/psd-parse/samples/egret-demo/resource/eui_skins/MainStageSkin.exml',
skinClassName: 'MainStageSkin',
resPath: '/Users/rockyl/WorkSpaces/VisualEditor/psd-parse/samples/egret-demo/design/images',
resGroupName: 'main',
});
})();
//# sourceMappingURL=generator.cjs.js.map
This diff is collapsed.
/**
* Created by rockyl on 2019-08-10.
*/
import {toEgret} from "../../src/index";
(async function generate() {
await toEgret('psd/test.psd', {
skinFilePath: '/Users/rockyl/WorkSpaces/VisualEditor/psd-parse/samples/egret-demo/resource/eui_skins/MainStageSkin.exml',
skinClassName: 'MainStageSkin',
resPath: '/Users/rockyl/WorkSpaces/VisualEditor/psd-parse/samples/egret-demo/design/images',
resGroupName: 'main',
});
})();
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Egret</title>
<meta name="viewport" content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="full-screen" content="true" />
<meta name="screen-orientation" content="portrait" />
<meta name="x5-fullscreen" content="true" />
<meta name="360-fullscreen" content="true" />
<style>
html, body {
-ms-touch-action: none;
background: #888888;
padding: 0;
border: 0;
margin: 0;
height: 100%;
}
</style>
</head>
<body>
<div style="margin: auto;width: 100%;height: 100%;" class="egret-player"
data-entry-class="Main"
data-orientation="auto"
data-scale-mode="showAll"
data-frame-rate="30"
data-content-width="640"
data-content-height="1136"
data-multi-fingered="2"
data-show-fps="false" data-show-log="false"
data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
</div>
<script>
var loadScript = function (list, callback) {
var loaded = 0;
var loadNext = function () {
loadSingleScript(list[loaded], function () {
loaded++;
if (loaded >= list.length) {
callback();
}
else {
loadNext();
}
})
};
loadNext();
};
var loadSingleScript = function (src, callback) {
var s = document.createElement('script');
s.async = false;
s.src = src;
s.addEventListener('load', function () {
s.parentNode.removeChild(s);
s.removeEventListener('load', arguments.callee, false);
callback();
}, false);
document.body.appendChild(s);
};
var xhr = new XMLHttpRequest();
xhr.open('GET', './manifest.json?v=' + Math.random(), true);
xhr.addEventListener("load", function () {
var manifest = JSON.parse(xhr.response);
var list = manifest.initial.concat(manifest.game);
loadScript(list, function () {
/**
* {
* "renderMode":, //Engine rendering mode, "canvas" or "webgl"
* "audioType": 0 //Use the audio type, 0: default, 2: web audio, 3: audio
* "antialias": //Whether the anti-aliasing is enabled in WebGL mode, true: on, false: off, defaults to false
* "calculateCanvasScaleFactor": //a function return canvas scale factor
* }
**/
egret.runEgret({ renderMode: "webgl", audioType: 0, calculateCanvasScaleFactor:function(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}});
});
});
xhr.send(null);
</script>
</body>
</html>
\ No newline at end of file
{
"initial": [
"libs/modules/egret/egret.js",
"libs/modules/egret/egret.web.js",
"libs/modules/eui/eui.js",
"libs/modules/assetsmanager/assetsmanager.js",
"libs/modules/tween/tween.js",
"libs/modules/promise/promise.js"
],
"game": [
"bin-debug/AssetAdapter.js",
"bin-debug/LoadingUI.js",
"bin-debug/Main.js",
"bin-debug/Platform.js",
"bin-debug/ThemeAdapter.js"
]
}
\ No newline at end of file
{
"file": "sheet_main.png",
"frames": {
"main_bg": {
"x": 1,
"y": 1,
"w": 375,
"h": 667,
"offX": 0,
"offY": 0,
"sourceW": 375,
"sourceH": 667
},
"main_hello": {
"x": 378,
"y": 1,
"w": 141,
"h": 50,
"offX": 0,
"offY": 0,
"sourceW": 141,
"sourceH": 50
},
"main_btn0": {
"x": 1,
"y": 670,
"w": 346,
"h": 89,
"offX": 0,
"offY": 0,
"sourceW": 346,
"sourceH": 89
},
"main_btn1": {
"x": 1,
"y": 761,
"w": 346,
"h": 89,
"offX": 0,
"offY": 0,
"sourceW": 346,
"sourceH": 89
}
}
}
\ No newline at end of file
[
"<font color=0x00ff0c>Open-source</font>,<font color=0x00ff0c>Free</font>,<font color=0x00ff0c>Multi-platform</font>",
"Push <font color=0x00ff0c>Game </font>Forward",
"<font color=0x00ff0c>HTML5 </font>Game Engine"
]
\ No newline at end of file
{
"groups": [
{
"keys": "checkbox_select_disabled_png,checkbox_select_down_png,checkbox_select_up_png,checkbox_unselect_png,selected_png,border_png,header_png,radiobutton_select_disabled_png,radiobutton_select_down_png,radiobutton_select_up_png,radiobutton_unselect_png,roundthumb_png,thumb_png,track_png,tracklight_png,handle_png,off_png,on_png,button_down_png,button_up_png,thumb_pb_png,track_pb_png,track_sb_png,bg_jpg,egret_icon_png,description_json",
"name": "preload"
}
],
"resources": [
{
"url": "assets/CheckBox/checkbox_select_disabled.png",
"type": "image",
"name": "checkbox_select_disabled_png"
},
{
"url": "assets/CheckBox/checkbox_select_down.png",
"type": "image",
"name": "checkbox_select_down_png"
},
{
"url": "assets/CheckBox/checkbox_select_up.png",
"type": "image",
"name": "checkbox_select_up_png"
},
{
"url": "assets/CheckBox/checkbox_unselect.png",
"type": "image",
"name": "checkbox_unselect_png"
},
{
"url": "assets/ItemRenderer/selected.png",
"type": "image",
"name": "selected_png"
},
{
"url": "assets/Panel/border.png",
"type": "image",
"name": "border_png"
},
{
"url": "assets/Panel/header.png",
"type": "image",
"name": "header_png"
},
{
"url": "assets/RadioButton/radiobutton_select_disabled.png",
"type": "image",
"name": "radiobutton_select_disabled_png"
},
{
"url": "assets/RadioButton/radiobutton_select_down.png",
"type": "image",
"name": "radiobutton_select_down_png"
},
{
"url": "assets/RadioButton/radiobutton_select_up.png",
"type": "image",
"name": "radiobutton_select_up_png"
},
{
"url": "assets/RadioButton/radiobutton_unselect.png",
"type": "image",
"name": "radiobutton_unselect_png"
},
{
"url": "assets/ScrollBar/roundthumb.png",
"type": "image",
"name": "roundthumb_png"
},
{
"url": "assets/Slider/thumb.png",
"type": "image",
"name": "thumb_png"
},
{
"url": "assets/Slider/track.png",
"type": "image",
"name": "track_png"
},
{
"url": "assets/Slider/tracklight.png",
"type": "image",
"name": "tracklight_png"
},
{
"url": "assets/ToggleSwitch/handle.png",
"type": "image",
"name": "handle_png"
},
{
"url": "assets/ToggleSwitch/off.png",
"type": "image",
"name": "off_png"
},
{
"url": "assets/ToggleSwitch/on.png",
"type": "image",
"name": "on_png"
},
{
"url": "assets/Button/button_down.png",
"type": "image",
"name": "button_down_png"
},
{
"url": "assets/Button/button_up.png",
"type": "image",
"name": "button_up_png"
},
{
"url": "assets/ProgressBar/thumb_pb.png",
"type": "image",
"name": "thumb_pb_png"
},
{
"url": "assets/ProgressBar/track_pb.png",
"type": "image",
"name": "track_pb_png"
},
{
"url": "assets/ScrollBar/track_sb.png",
"type": "image",
"name": "track_sb_png"
},
{
"url": "assets/bg.jpg",
"type": "image",
"name": "bg_jpg"
},
{
"url": "assets/egret_icon.png",
"type": "image",
"name": "egret_icon_png"
},
{
"url": "config/description.json",
"type": "json",
"name": "description_json"
},
{
"url": "assets/sheets/sheet_main.json",
"type": "sheet",
"name": "sheet_main",
"subkeys": "main_bg,main_btn0,main_btn1,main_hello"
}
]
}
\ No newline at end of file
{
"skins": {
"eui.Button": "resource/eui_skins/ButtonSkin.exml",
"eui.CheckBox": "resource/eui_skins/CheckBoxSkin.exml",
"eui.HScrollBar": "resource/eui_skins/HScrollBarSkin.exml",
"eui.HSlider": "resource/eui_skins/HSliderSkin.exml",
"eui.Panel": "resource/eui_skins/PanelSkin.exml",
"eui.TextInput": "resource/eui_skins/TextInputSkin.exml",
"eui.ProgressBar": "resource/eui_skins/ProgressBarSkin.exml",
"eui.RadioButton": "resource/eui_skins/RadioButtonSkin.exml",
"eui.Scroller": "resource/eui_skins/ScrollerSkin.exml",
"eui.ToggleSwitch": "resource/eui_skins/ToggleSwitchSkin.exml",
"eui.VScrollBar": "resource/eui_skins/VScrollBarSkin.exml",
"eui.VSlider": "resource/eui_skins/VSliderSkin.exml",
"eui.ItemRenderer": "resource/eui_skins/ItemRendererSkin.exml"
},
"autoGenerateExmlsList": true,
"exmls": [
"resource/eui_skins/ButtonSkin.exml",
"resource/eui_skins/CheckBoxSkin.exml",
"resource/eui_skins/HScrollBarSkin.exml",
"resource/eui_skins/HSliderSkin.exml",
"resource/eui_skins/ItemRendererSkin.exml",
"resource/eui_skins/PanelSkin.exml",
"resource/eui_skins/ProgressBarSkin.exml",
"resource/eui_skins/RadioButtonSkin.exml",
"resource/eui_skins/ScrollerSkin.exml",
"resource/eui_skins/TextInputSkin.exml",
"resource/eui_skins/ToggleSwitchSkin.exml",
"resource/eui_skins/VScrollBarSkin.exml",
"resource/eui_skins/VSliderSkin.exml"
]
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<e:Skin class="skins.ButtonSkin" states="up,down,disabled" minHeight="50" minWidth="100" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" alpha.disabled="0.5"
source="button_up_png"
source.down="button_down_png"/>
<e:Label id="labelDisplay" top="8" bottom="8" left="8" right="8"
size="20"
textColor="0xFFFFFF" verticalAlign="middle" textAlign="center"/>
<e:Image id="iconDisplay" horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.CheckBoxSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Group width="100%" height="100%">
<e:layout>
<e:HorizontalLayout verticalAlign="middle"/>
</e:layout>
<e:Image fillMode="scale" alpha="1" alpha.disabled="0.5" alpha.down="0.7"
source="checkbox_unselect_png"
source.upAndSelected="checkbox_select_up_png"
source.downAndSelected="checkbox_select_down_png"
source.disabledAndSelected="checkbox_select_disabled_png"/>
<e:Label id="labelDisplay" size="20" textColor="0x707070"
textAlign="center" verticalAlign="middle"
fontFamily="Tahoma"/>
</e:Group>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.HScrollBarSkin" minWidth="20" minHeight="8" xmlns:e="http://ns.egret.com/eui">
<e:Image id="thumb" source="roundthumb_png" scale9Grid="3,3,2,2" height="8" width="30" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.HSliderSkin" minWidth="20" minHeight="8" xmlns:e="http://ns.egret.com/eui">
<e:Image id="track" source="track_sb_png" scale9Grid="1,1,4,4" width="100%"
height="6" verticalCenter="0"/>
<e:Image id="thumb" source="thumb_png" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8" ?>
<e:Skin class="skins.ItemRendererSkin" states="up,down,disabled" minHeight="50" minWidth="100" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" alpha.disabled="0.5"
source="button_up_png"
source.down="button_down_png"/>
<e:Label id="labelDisplay" top="8" bottom="8" left="8" right="8"
size="20" fontFamily="Tahoma"
textColor="0xFFFFFF" text="{data}" verticalAlign="middle" textAlign="center"/>
</e:Skin>
<?xml version="1.0" encoding="UTF-8"?>
<e:Skin class="MainStageSkin" width="375" height="667" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Image source="main_bg" width="375" height="667" name="bg"/>
<e:Group width="358" height="228" x="14" y="54">
<e:Button label="button1" width="346" height="89" x="12" y="139" name="btn1">
<e:skinName>
<e:Skin states="up,down,disabled">
<e:Image width="100%" height="100%" source="main_btn1"/>
<e:Label id="labelDisplay" horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
</e:skinName>
</e:Button>
<e:Button label="button0" width="346" height="89" name="btn0">
<e:skinName>
<e:Skin states="up,down,disabled">
<e:Image width="100%" height="100%" source="main_btn0"/>
<e:Label id="labelDisplay" horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
</e:skinName>
</e:Button>
</e:Group>
<e:Image source="main_hello" width="141" height="50" x="104" y="387" name="hello"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.PanelSkin" minHeight="230" minWidth="450" xmlns:e="http://ns.egret.com/eui">
<e:Image left="0" right="0" bottom="0" top="0" source="border_png" scale9Grid="2,2,12,12" />
<e:Group id="moveArea" left="0" right="0" top="0" height="45">
<e:Image left="0" right="0" bottom="0" top="0" source="header_png"/>
<e:Label id="titleDisplay" size="20" fontFamily="Tahoma" textColor="0xFFFFFF"
wordWrap="false" left="15" right="5" verticalCenter="0"/>
</e:Group>
<e:Button id="closeButton" label="close" bottom="5" horizontalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ProgressBarSkin" minWidth="30" minHeight="18" xmlns:e="http://ns.egret.com/eui">
<e:Image source="track_pb_png" scale9Grid="1,1,4,4" width="100%"
height="100%" verticalCenter="0"/>
<e:Image id="thumb" height="100%" width="100%" source="thumb_pb_png"/>
<e:Label id="labelDisplay" textAlign="center" verticalAlign="middle"
size="15" fontFamily="Tahoma" textColor="0x707070"
horizontalCenter="0" verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.RadioButtonSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Group width="100%" height="100%">
<e:layout>
<e:HorizontalLayout verticalAlign="middle"/>
</e:layout>
<e:Image fillMode="scale" alpha="1" alpha.disabled="0.5" alpha.down="0.7"
source="radiobutton_unselect_png"
source.upAndSelected="radiobutton_select_up_png"
source.downAndSelected="radiobutton_select_down_png"
source.disabledAndSelected="radiobutton_select_disabled_png"/>
<e:Label id="labelDisplay" size="20" textColor="0x707070"
textAlign="center" verticalAlign="middle"
fontFamily="Tahoma"/>
</e:Group>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ScrollerSkin" minWidth="20" minHeight="20" xmlns:e="http://ns.egret.com/eui">
<e:HScrollBar id="horizontalScrollBar" width="100%" bottom="0"/>
<e:VScrollBar id="verticalScrollBar" height="100%" right="0"/>
</e:Skin>
\ No newline at end of file
<?xml version='1.0' encoding='utf-8'?>
<e:Skin class="skins.TextInputSkin" minHeight="40" minWidth="300" states="normal,disabled,normalWithPrompt,disabledWithPrompt" xmlns:e="http://ns.egret.com/eui">
<e:Image width="100%" height="100%" scale9Grid="1,3,8,8" source="button_up_png"/>
<e:Rect height="100%" width="100%" fillColor="0xffffff"/>
<e:EditableText id="textDisplay" verticalCenter="0" left="10" right="10"
textColor="0x000000" textColor.disabled="0xff0000" width="100%" height="24" size="20" />
<e:Label id="promptDisplay" verticalCenter="0" left="10" right="10"
textColor="0xa9a9a9" width="100%" height="24" size="20" touchEnabled="false" includeIn="normalWithPrompt,disabledWithPrompt"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.ToggleSwitchSkin" states="up,down,disabled,upAndSelected,downAndSelected,disabledAndSelected" xmlns:e="http://ns.egret.com/eui">
<e:Image source="on_png"
source.up="off_png"
source.down="off_png"
source.disabled="off_png"/>
<e:Image source="handle_png"
horizontalCenter="-18"
horizontalCenter.upAndSelected="18"
horizontalCenter.downAndSelected="18"
horizontalCenter.disabledAndSelected="18"
verticalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.VScrollBarSkin" minWidth="8" minHeight="20" xmlns:e="http://ns.egret.com/eui">
<e:Image id="thumb" source="roundthumb_png" scale9Grid="3,3,2,2" height="30" width="8" horizontalCenter="0"/>
</e:Skin>
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="skins.VSliderSkin" minWidth="25" minHeight="30" xmlns:e="http://ns.egret.com/eui">
<e:Image id="track" source="track_png" scale9Grid="1,1,4,4" width="7" height="100%" horizontalCenter="0"/>
<e:Image id="thumb" source="thumb_png" horizontalCenter="0" />
</e:Skin>
This diff is collapsed.
import * as fs from 'fs';
import * as path from 'path';
export class BaidugamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "game.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布百度小游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "game.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.deviceOrientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
\ No newline at end of file
import * as fs from 'fs';
import * as path from 'path';
type ManifestConfig = {
initial: string[],
game: string[]
}
export class BricksPlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
const filename = file.basename;
if (filename == 'manifest.json') {
const contents = file.contents.toString();
const jsonData: ManifestConfig = JSON.parse(contents);
let content = '';
content += `BK.Script.loadlib("GameRes://js/promise.js");\n`;
for (let item of jsonData.initial) {
if (item != 'js/promise.js' && item != 'js/promise.min.js') {
content += `BK.Script.loadlib("GameRes://${item}");\n`
}
}
for (let item of jsonData.game) {
content += `BK.Script.loadlib("GameRes://${item}");\n`
}
content += `BK.Script.loadlib("GameRes://egret.bricks.js");\n`
file.path = file.dirname + '/manifest.js'
file.contents = new Buffer(content);
} else if (filename == 'main.js') {
const content = file.contents.toString();
let result = content.replace(/RES\.loadConfig\("resource\/default\.res\.json", "resource\/"\)/gm, 'RES.loadConfig("GameRes://resource/default.res.json", "GameRes://resource/")');
result = result.replace(/eui\.Theme\("resource\/default\.thm\.json", _this\.stage\)/gm, 'eui.Theme("GameRes://resource/default.thm.json", _this.stage)');
result += ";global.Main = Main;";
file.path = file.dirname + '/main.js'
file.contents = new Buffer(result);
} else if (filename == 'promise.js') {
return null;
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步index.html 配置到main.js
let mainJSPath = path.join(pluginContext.outputDir, 'main.js');
let mainJSContent = fs.readFileSync(mainJSPath, { encoding: "utf8" });
let projectConfig = pluginContext.buildConfig.projectConfig;
mainJSContent = mainJSContent.replace(/frameRate: 30/gm, `frameRate: ${projectConfig.frameRate}`);
mainJSContent = mainJSContent.replace(/contentWidth: 640/gm, `contentWidth: ${projectConfig.contentWidth}`);
mainJSContent = mainJSContent.replace(/contentHeight: 1136/gm, `contentHeight: ${projectConfig.contentHeight}`);
mainJSContent = mainJSContent.replace(/entryClassName: "Main"/gm, `entryClassName: ${projectConfig.entryClassName}`);
mainJSContent = mainJSContent.replace(/scaleMode: "showAll"/gm, `scaleMode: ${projectConfig.scaleMode}`);
mainJSContent = mainJSContent.replace(/orientation: "auto"/gm, `orientation: ${projectConfig.orientation}`);
fs.writeFileSync(mainJSPath, mainJSContent);
}
}
declare var egret;
\ No newline at end of file
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_android/assets/game`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.json' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { BaidugamePlugin } from './baidugame/baidugame';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_baidugame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new BaidugamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new BaidugamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { BricksPlugin } from './bricks/bricks';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_bricks/PublicBrickEngineGame/Res`;
if (command == 'build') {
return {
outputDir,
commands: [
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' }),
new BricksPlugin()
]
}
}
else if (command == 'publish') {
console.log('执行publish')
return {
outputDir,
commands: [
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' }),
new UglifyPlugin([{
sources: ["main.js"],
target: "js/main.min.js"
}
]),
new BricksPlugin(),
]
}
} else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_ios/assets/game`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.json' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, ResSplitPlugin, CleanPlugin } from 'built-in';
import { OppogamePlugin } from './oppogame/oppogame';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_oppogame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new OppogamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new OppogamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, ResSplitPlugin, CleanPlugin } from 'built-in';
import { MiqgamePlugin } from './qgame/qgame';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_qgame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new MiqgamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new MiqgamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { QQgamePlugin } from './qqgame/qqgame';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_qqgame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new QQgamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new QQgamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, IncrementCompilePlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, RenamePlugin } from 'built-in';
import { WxgamePlugin } from './wxgame/wxgame';
import { BricksPlugin } from './bricks/bricks';
import { CustomPlugin } from './myplugin';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
if (command == 'build') {
const outputDir = '.';
return {
outputDir,
commands: [
// new EmitResConfigFilePlugin({
// output: "resource/default.res.json",
// typeSelector: config.typeSelector,
// nameSelector: p => path.basename(p).replace(/\./gi, "_"),
// groupSelector: p => "preload"
// }),
new ExmlPlugin('debug'), // 非 EUI 项目关闭此设置
new IncrementCompilePlugin(),
]
}
}
else if (command == 'publish') {
const outputDir = `bin-release/web/${version}`;
return {
outputDir,
commands: [
new CustomPlugin(),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}]),
new RenamePlugin({
verbose: true, hash: 'crc32', matchers: [
{ from: "**/*.js", to: "[path][name]_[hash].[ext]" }
]
}),
new ManifestPlugin({ output: "manifest.json" })
]
}
}
else {
throw `unknown command : ${params.command}`
}
},
mergeSelector: (path) => {
if (path.indexOf("assets/bitmap/") >= 0) {
return "assets/bitmap/sheet.sheet"
}
else if (path.indexOf("armature") >= 0 && path.indexOf(".json") >= 0) {
return "assets/armature/1.zip";
}
},
typeSelector: (path) => {
const ext = path.substr(path.lastIndexOf(".") + 1);
const typeMap = {
"jpg": "image",
"png": "image",
"webp": "image",
"json": "json",
"fnt": "font",
"pvr": "pvr",
"mp3": "sound",
"zip": "zip",
"sheet": "sheet",
"exml": "text"
}
let type = typeMap[ext];
if (type == "json") {
if (path.indexOf("sheet") >= 0) {
type = "sheet";
} else if (path.indexOf("movieclip") >= 0) {
type = "movieclip";
};
}
return type;
}
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, ResSplitPlugin, CleanPlugin } from 'built-in';
import { VivogamePlugin } from './vivogame/vivogame';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_vivogame/src`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["../engine", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new VivogamePlugin(),
new ManifestPlugin({ output: 'manifest.js', info: { target: 'vivogame' } })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["../engine", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new VivogamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js', info: { target: 'vivogame' } })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { WxgamePlugin } from './wxgame/wxgame';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_wxgame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/**
* 示例自定义插件,您可以查阅 http://developer.egret.com/cn/github/egret-docs/Engine2D/projectConfig/cmdExtensionPlugin/index.html
* 了解如何开发一个自定义插件
*/
export class CustomPlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
return file;
}
async onFinish(commandContext: plugins.CommandContext) {
}
}
\ No newline at end of file
This diff is collapsed.
import * as fs from 'fs';
import * as path from 'path';
export class OppogamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
if(filename == "libs/modules/eui/eui.js"){
content = content.replace("function getRepeatedIds","window.getRepeatedIds=function getRepeatedIds");
content = content.replace("function getIds","window.getIds=function getIds");
content = content.replace("function toXMLString","window.toXMLString=function toXMLString");
content = content.replace("function checkDeclarations","window.checkDeclarations=function checkDeclarations");
content = content.replace("function getPropertyStr","window.getPropertyStr=function getPropertyStr");
}
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "main.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布Oppo快游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "manifest.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.orientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
import * as fs from 'fs';
import * as path from 'path';
export class MiqgamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
if(filename == "libs/modules/eui/eui.js"){
content = content.replace("function getRepeatedIds","window.getRepeatedIds=function getRepeatedIds");
content = content.replace("function getIds","window.getIds=function getIds");
content = content.replace("function toXMLString","window.toXMLString=function toXMLString");
content = content.replace("function checkDeclarations","window.checkDeclarations=function checkDeclarations");
content = content.replace("function getPropertyStr","window.getPropertyStr=function getPropertyStr");
}
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "main.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布小米快游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "manifest.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.orientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
import * as fs from 'fs';
import * as path from 'path';
export class QQgamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "game.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布QQ小游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "game.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.deviceOrientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
\ No newline at end of file
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
"lib": [
"es5",
"es2015.promise"
], /* Specify library files to be included in the compilation: */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
/* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
\ No newline at end of file
import * as fs from 'fs';
import * as path from 'path';
export class VivogamePlugin implements plugins.Command {
jsFileList: any = []
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
this.jsFileList.push(file.basename)
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
if (filename == "libs/modules/eui/eui.js") {
content = content.replace("function getRepeatedIds", "window.getRepeatedIds=function getRepeatedIds");
content = content.replace("function getIds", "window.getIds=function getIds");
content = content.replace("function toXMLString", "window.toXMLString=function toXMLString");
content = content.replace("function checkDeclarations", "window.checkDeclarations=function checkDeclarations");
content = content.replace("function getPropertyStr", "window.getPropertyStr=function getPropertyStr");
}
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "game.js");
if (!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布 Vivo 小游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "manifest.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.deviceOrientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
let isPublish = pluginContext.buildConfig.command == "publish" ? true : false;
let configOption = "webpackConf.externals = Object.assign(webpackConf.externals || {\n\t\t"
for (var i = 0, len = this.jsFileList.length; i < len; i++) {
let jsFile = this.jsFileList[i];
if(isPublish && jsFile == "main.js"){
jsFile = 'main.min.js'
}
configOption += `"js/${jsFile}":"commonjs js/${jsFile}"`
if (i < len - 1) {
configOption += ",\n\t\t"
} else {
configOption += "\n\t\t"
}
}
configOption += "})"
const replaceConfigStr = '\/\/----auto option start----\n\t\t' + configOption + '\n\t\t\/\/----auto option end----';
const webpackConfigPath = path.join(pluginContext.outputDir, '../config', "webpack.config.js");
let configJSContent = fs.readFileSync(webpackConfigPath, { encoding: "utf8" });
configJSContent = configJSContent.replace(reg, replaceConfigStr);
fs.writeFileSync(webpackConfigPath, configJSContent);
}
}
import * as fs from 'fs';
import * as path from 'path';
export class WxgamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "game.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布微信小游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "game.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.deviceOrientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
\ No newline at end of file
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
class AssetAdapter implements eui.IAssetAdapter {
/**
* @language zh_CN
* 解析素材
* @param source 待解析的新素材标识符
* @param compFunc 解析完成回调函数,示例:callBack(content:any,source:string):void;
* @param thisObject callBack的 this 引用
*/
public getAsset(source: string, compFunc:Function, thisObject: any): void {
function onGetRes(data: any): void {
compFunc.call(thisObject, data, source);
}
if (RES.hasRes(source)) {
let data = RES.getRes(source);
if (data) {
onGetRes(data);
}
else {
RES.getResAsync(source, onGetRes, this);
}
}
else {
RES.getResByUrl(source, onGetRes, this, RES.ResourceItem.TYPE_IMAGE);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
class LoadingUI extends egret.Sprite implements RES.PromiseTaskReporter {
public constructor() {
super();
this.createView();
}
private textField: egret.TextField;
private createView(): void {
this.textField = new egret.TextField();
this.addChild(this.textField);
this.textField.y = 300;
this.textField.width = 480;
this.textField.height = 100;
this.textField.textAlign = "center";
}
public onProgress(current: number, total: number): void {
this.textField.text = `Loading...${current}/${total}`;
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.addLifecycleListener((context) => {
// custom lifecycle plugin
})
egret.lifecycle.onPause = () => {
egret.ticker.pause();
}
egret.lifecycle.onResume = () => {
egret.ticker.resume();
}
//inject the custom material parser
//注入自定义的素材解析器
let assetAdapter = new AssetAdapter();
egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
this.runGame().catch(e => {
console.log(e);
})
}
private async runGame() {
await this.loadResource()
this.createGameScene();
const result = await RES.getResAsync("description_json")
this.startAnimation(result);
await platform.login();
const userInfo = await platform.getUserInfo();
console.log(userInfo);
}
private async loadResource() {
try {
const loadingView = new LoadingUI();
this.stage.addChild(loadingView);
await RES.loadConfig("resource/default.res.json", "resource/");
await this.loadTheme();
await RES.loadGroup("preload", 0, loadingView);
this.stage.removeChild(loadingView);
}
catch (e) {
console.error(e);
}
}
private loadTheme() {
return new Promise((resolve, reject) => {
// load skin theme configuration file, you can manually modify the file. And replace the default skin.
//加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
let theme = new eui.Theme("resource/default.thm.json", this.stage);
theme.addEventListener(eui.UIEvent.COMPLETE, () => {
resolve();
}, this);
})
}
private textfield: egret.TextField;
/**
* 创建场景界面
* Create scene interface
*/
protected createGameScene(): void {
let sky = this.createBitmapByName("bg_jpg");
this.addChild(sky);
let stageW = this.stage.stageWidth;
let stageH = this.stage.stageHeight;
sky.width = stageW;
sky.height = stageH;
let topMask = new egret.Shape();
topMask.graphics.beginFill(0x000000, 0.5);
topMask.graphics.drawRect(0, 0, stageW, 172);
topMask.graphics.endFill();
topMask.y = 33;
this.addChild(topMask);
let icon: egret.Bitmap = this.createBitmapByName("egret_icon_png");
this.addChild(icon);
icon.x = 26;
icon.y = 33;
let line = new egret.Shape();
line.graphics.lineStyle(2, 0xffffff);
line.graphics.moveTo(0, 0);
line.graphics.lineTo(0, 117);
line.graphics.endFill();
line.x = 172;
line.y = 61;
this.addChild(line);
let colorLabel = new egret.TextField();
colorLabel.textColor = 0xffffff;
colorLabel.width = stageW - 172;
colorLabel.textAlign = "center";
colorLabel.text = "Hello Egret";
colorLabel.size = 24;
colorLabel.x = 172;
colorLabel.y = 80;
this.addChild(colorLabel);
let textfield = new egret.TextField();
this.addChild(textfield);
textfield.alpha = 0;
textfield.width = stageW - 172;
textfield.textAlign = egret.HorizontalAlign.CENTER;
textfield.size = 24;
textfield.textColor = 0xffffff;
textfield.x = 172;
textfield.y = 135;
this.textfield = textfield;
let button = new eui.Button();
button.label = "Click!";
button.horizontalCenter = 0;
button.verticalCenter = 0;
this.addChild(button);
button.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClick, this);
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
*/
private createBitmapByName(name: string): egret.Bitmap {
let result = new egret.Bitmap();
let texture: egret.Texture = RES.getRes(name);
result.texture = texture;
return result;
}
/**
* 描述文件加载成功,开始播放动画
* Description file loading is successful, start to play the animation
*/
private startAnimation(result: Array<any>): void {
let parser = new egret.HtmlTextParser();
let textflowArr = result.map(text => parser.parse(text));
let textfield = this.textfield;
let count = -1;
let change = () => {
count++;
if (count >= textflowArr.length) {
count = 0;
}
let textFlow = textflowArr[count];
// 切换描述内容
// Switch to described content
textfield.textFlow = textFlow;
let tw = egret.Tween.get(textfield);
tw.to({ "alpha": 1 }, 200);
tw.wait(2000);
tw.to({ "alpha": 0 }, 200);
tw.call(change, this);
};
change();
}
/**
* 点击按钮
* Click the button
*/
private onButtonClick(e: egret.TouchEvent) {
let panel = new eui.Panel();
panel.title = "Title";
panel.horizontalCenter = 0;
panel.verticalCenter = 0;
this.addChild(panel);
}
}
/**
* 平台数据接口。
* 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息
* 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定
* 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式
*/
declare interface Platform {
getUserInfo(): Promise<any>;
login(): Promise<any>
}
class DebugPlatform implements Platform {
async getUserInfo() {
return { nickName: "username" }
}
async login() {
}
}
if (!window.platform) {
window.platform = new DebugPlatform();
}
declare let platform: Platform;
declare interface Window {
platform: Platform
}
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
class ThemeAdapter implements eui.IThemeAdapter {
/**
* 解析主题
* @param url 待解析的主题url
* @param onSuccess 解析完成回调函数,示例:compFunc(e:egret.Event):void;
* @param onError 解析失败回调函数,示例:errorFunc():void;
* @param thisObject 回调的this引用
*/
public getTheme(url: string, onSuccess: Function, onError: Function, thisObject: any): void {
function onResGet(e: string): void {
onSuccess.call(thisObject, e);
}
function onResError(e: RES.ResourceEvent): void {
if (e.resItem.url == url) {
RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
onError.call(thisObject);
}
}
if (typeof generateEUI !== 'undefined') {
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI);
}, this);
}
else if (typeof generateEUI2 !== 'undefined') {
RES.getResByUrl("resource/gameEui.json", (data, url) => {
window["JSONParseClass"]["setData"](data);
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI2);
}, this);
}, this, RES.ResourceItem.TYPE_JSON);
}
else if (typeof generateJSON !== 'undefined') {
if (url.indexOf(".exml") > -1) {
let dataPath = url.split("/");
dataPath.pop();
let dirPath = dataPath.join("/") + "_EUI.json";
if (!generateJSON.paths[url]) {
RES.getResByUrl(dirPath, (data) => {
window["JSONParseClass"]["setData"](data);
egret.callLater(() => {
onSuccess.call(thisObject, generateJSON.paths[url]);
}, this);
}, this, RES.ResourceItem.TYPE_JSON);
} else {
egret.callLater(() => {
onSuccess.call(thisObject, generateJSON.paths[url]);
}, this);
}
}
else {
egret.callLater(() => {
onSuccess.call(thisObject, generateJSON);
}, this);
}
}
else {
RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
RES.getResByUrl(url, onResGet, this, RES.ResourceItem.TYPE_TEXT);
}
}
}
declare var generateEUI: { paths: string[], skins: any }
declare var generateEUI2: { paths: string[], skins: any }
declare var generateJSON: { paths: string[], skins: any }
\ No newline at end of file
require("launcher/native_require.js");
egret_native.egtMain = function () {
egret_native.nativeType = "native";
egret_native.egretInit();
egret_native.egretStart();
};
var manifest = JSON.parse(egret_native.readFileSync("manifest.json"));
var game_file_list = manifest.initial.concat(manifest.game);
var window = this;
egret_native.setSearchPaths([""]);
egret_native.requireFiles = function () {
for (var key in game_file_list) {
var src = game_file_list[key];
require(src);
}
};
egret_native.egretInit = function () {
if(egret_native.featureEnable) {
//控制一些优化方案是否开启
//Control whether some optimization options are open
var result = egret_native.featureEnable({
});
}
egret_native.requireFiles();
egret.dom = {};
egret.dom.drawAsCanvas = function () {
};
};
egret_native.egretStart = function () {
var option = {
//以下为自动修改,请勿修改
//The following is automatically modified, please do not modify
//----auto option start----
//----auto option end----
};
egret.native.NativePlayer.option = option;
egret.runEgret();
egret_native.Label.createLabel("/system/fonts/DroidSansFallback.ttf", 20, "", 0);
egret_native.EGTView.preSetOffScreenBufferEnable(true);
};
\ No newline at end of file
require("launcher/native_require.js");
egret_native.egtMain = function () {
egret_native.nativeType = "runtime";
egret_native.egretInit();
egret_native.egretStart();
};
\ No newline at end of file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Egret</title>
<meta name="viewport" content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="full-screen" content="true" />
<meta name="screen-orientation" content="portrait" />
<meta name="x5-fullscreen" content="true" />
<meta name="360-fullscreen" content="true" />
<style>
html, body {
-ms-touch-action: none;
background: #888888;
padding: 0;
border: 0;
margin: 0;
height: 100%;
}
</style>
</head>
<body>
<div style="margin: auto;width: 100%;height: 100%;" class="egret-player"
data-entry-class="Main"
data-orientation="auto"
data-scale-mode="showAll"
data-frame-rate="30"
data-content-width="640"
data-content-height="1136"
data-show-paint-rect="false"
data-multi-fingered="2"
data-show-fps="false" data-show-log="false"
data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
</div>
<script>
var loadScript = function (list, callback) {
var loaded = 0;
var loadNext = function () {
loadSingleScript(list[loaded], function () {
loaded++;
if (loaded >= list.length) {
callback();
}
else {
loadNext();
}
})
};
loadNext();
};
var loadSingleScript = function (src, callback) {
var s = document.createElement('script');
s.async = false;
s.src = src;
s.addEventListener('load', function () {
s.parentNode.removeChild(s);
s.removeEventListener('load', arguments.callee, false);
callback();
}, false);
document.body.appendChild(s);
};
var xhr = new XMLHttpRequest();
xhr.open('GET', './manifest.json?v=' + Math.random(), true);
xhr.addEventListener("load", function () {
var manifest = JSON.parse(xhr.response);
var list = manifest.initial.concat(manifest.game);
loadScript(list, function () {
/**
* {
* "renderMode":, //Engine rendering mode, "canvas" or "webgl"
* "audioType": 0 //Use the audio type, 0: default, 2: web audio, 3: audio
* "antialias": //Whether the anti-aliasing is enabled in WebGL mode, true: on, false: off, defaults to false
* "calculateCanvasScaleFactor": //a function return canvas scale factor
* }
**/
egret.runEgret({ renderMode: "webgl", audioType: 0, calculateCanvasScaleFactor:function(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}});
});
});
xhr.send(null);
</script>
</body>
</html>
\ No newline at end of file
{
"compilerOptions": {
"target": "es5",
"outDir": "bin-debug",
"experimentalDecorators": true,
"lib": [
"es5",
"dom",
"es2015.promise"
],
"types": []
},
"include": [
"src",
"libs"
]
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment