Commit 245cfb8d authored by rockyl's avatar rockyl

修改了好多东西啊

parent d45fe6f0
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
......@@ -5,15 +5,16 @@
"main": "index.js",
"types": "index.d.ts",
"dependencies": {
"glob": "^7.1.6",
"rollup-plugin-typescript": "^1.0.1"
"color": "^3.1.2"
},
"devDependencies": {
"dts-bundle": "^0.7.3",
"glob": "^7.1.6",
"protobufjs": "^6.8.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-progress": "^1.1.1",
"rollup-plugin-typescript": "^1.0.1",
"rollup-plugin-typescript2": "^0.25.2",
"rollup-plugin-uglify": "^6.0.3",
"ts-loader": "^4.0.0",
......@@ -25,10 +26,12 @@
},
"scripts": {
"build-webpack": "webpack",
"rollup": "rollup -c -o dist/engine.js --environment BUILD:production1",
"rollup:prod": "rollup -c -o dist/engine.js --environment BUILD:production",
"rollup": "rollup -c -o dist/engine.js",
"rollup:debug": "rollup -c -m ",
"rename": "node scripts/rename-hash.js dist/engine.js",
"build": "rm -rf dist&&yarn rollup && yarn rename && ali-oss-publish -c oss.config.js -e dist",
"build": "rm -rf dist&&yarn rollup:prod && yarn rename && ali-oss-publish -c oss.config.js -e dist",
"build:debug": "rm -rf dist&&yarn rollup && yarn rename && ali-oss-publish -c oss.config.js -e dist",
"ts": "dts-bundle --name engine --main types/src/index.d.ts --out ../../dist/index.d.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack -w",
......
......@@ -54,5 +54,5 @@ ${allExports}
}
`;
fs.writeFileSync('dist/types.d.ts', content);
fs.writeFileSync('debug/types.d.ts', content);
});
......@@ -153,9 +153,9 @@ export const DEG_TO_RAD: number = PI / 180;
* @property {number} CANVAS - Canvas render type.
*/
export enum RENDERER_TYPE {
UNKNOWN = 0,
WEBGL,
CANVAS,
UNKNOWN = 'unknown',
WEBGL = 'webgl',
CANVAS = 'canvas',
};
/**
......
import { ObservablePoint, Point, Rectangle } from '../math';
import { sign, TextureCache } from '../utils';
import {ObservablePoint, Point, Rectangle} from '../math';
import {sign, TextureCache} from '../utils';
// import { BLEND_MODES } from '../const';
import Texture from '../texture/Texture';
import {Event} from '../events/Event';
import Container from './Container';
import { DisplayObject } from "./DisplayObject";
import {DisplayObject} from "./DisplayObject";
import CanvasRenderer from '../renderers/CanvasRenderer';
import { SCALE_MODES } from '../const';
import { WebglRenderer } from '../renderers/WebglRenderer';
import {SCALE_MODES} from '../const';
import {WebglRenderer} from '../renderers/WebglRenderer';
const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
/**
......@@ -21,7 +21,7 @@ export default class Sprite extends Container {
* 关于贴图的锚点,0到1,默认为texture自己的
*
*/
private _anchorTexture: ObservablePoint
private _anchorTexture: ObservablePoint;
/**
* 使用的贴图
* @member {Texture}
......@@ -124,13 +124,13 @@ export default class Sprite extends Container {
//可用才赋值uv
if (this._texture.valid) this.uvs = this._texture._uvs.uvsFloat32;
//设置过宽高的话,就需要改变缩放值,废弃先
// if (this._width) {
// this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
// }
if (this._width) {
this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
}
// if (this._height) {
// this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
// }
if (this._height) {
this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
}
//修改_localBoundsSelf
const width = this._texture.orig.width;
......@@ -435,7 +435,6 @@ export default class Sprite extends Container {
}
//一些静态类方法
/**
* 方便创建sprite
......
......@@ -724,7 +724,7 @@ export class Stage extends Container {
for (let j = 0; j < eLen; j++) {
if (!events[j]["_bpd"]) {
//有事件,且mouseEnabled为true
if (d.hasEventListener(events[j].type) && d.mouseEnabled) {
if (d.hasEventListener(events[j].type, false) && d.mouseEnabled) {
events[j].target = d;
events[j].currentTarget = displayList[eLen - 1];
lp = d.globalToLocal(cp, DisplayObject._bp);
......
......@@ -220,7 +220,7 @@ export default class Graphics extends Container {
* 克隆该Graphics的几何绘制,不包括它自身的transform
* @return {Graphics} A clone of the graphics object
*/
clone(): Graphics {
cloneSelf(): Graphics {
const clone = new Graphics();
clone.renderable = this.renderable;
......
......@@ -4,6 +4,8 @@ import {EventDispatcher} from "../events/EventDispatcher";
import {TextureCache} from "../utils";
import {Texture} from "../texture";
import {httpRequest} from "../net";
import TextureSheet from "../texture/TextureSheet";
import {createTextureSheet} from "../../zeroing/game-warpper/texture-sheet";
export class Loader extends EventDispatcher {
......@@ -11,12 +13,10 @@ export class Loader extends EventDispatcher {
* 记录原始数据,json和image,贴图在建立时会被缓存
*/
caches = {};
crossOrigin: boolean = true;
//parser: Parser;
_req: XMLHttpRequest = null;
/**
*
*/
......@@ -27,75 +27,73 @@ export class Loader extends EventDispatcher {
/**
*
* @param callback
* @param url 图集一般是png格式,传的是json,在callback自行拆分
* @param url
*/
loadSheet(callback: Function, url: string) {
let pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
this.loadImage((suc, data) => {
if (suc) {
if (this.caches[url]) {
callback(true, {json: this.caches[url], img: data})
}
} else {
callback(false, data)
}
}, pngFile);
this.loadJson((suc, data) => {
if (suc) {
if (this.caches[pngFile]) {
callback(true, {json: data, img: this.caches[pngFile]})
}
} else {
callback(false, data)
}
}, url)
loadSheet(url: string) {
let config;
return this.loadJson(url)
.then(json => {
const {file} = config = json;
return this.loadTexture(file)
})
.then(texture => {
createTextureSheet(texture.baseTexture, config.frames);
})
}
loadRaw(callback: Function, url: string, type: 'text' | 'json') {
httpRequest((s, p) => {
if (s) {
this.cache(url, p);
}
callback(s, p);
}, url, 'get', {}, type);
loadRaw(url: string, uuid?: string, type?: 'text' | 'json') {
let data = this.caches[uuid || url];
if (data) {
return Promise.resolve(data);
} else {
return httpRequest(url, 'get', {}, type)
.then(data => {
this.cache(uuid || url, data);
return data;
});
}
}
loadJson(callback: Function, url: string) {
this.loadRaw(callback, url, 'json');
loadJson(url: string, uuid?: string) {
return this.loadRaw(url, uuid, 'json');
}
loadText(callback: Function, url: string) {
this.loadRaw(callback, url, 'text');
loadText(url: string, uuid?: string) {
return this.loadRaw(url, uuid, 'text');
}
loadTexture(callback: Function, url: string) {
this.loadImage((s, payload) => {
if (s) {
this.cache(url, payload);
callback(s, TextureCache[url] = Texture.from(payload));
loadImage(url: string, uuid?: string) {
return new Promise((resolve, reject) => {
let img = this.caches[uuid || url];
if (img) {
resolve(img);
} else {
callback(s, payload);
img = new Image();
if (this.crossOrigin) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = () => {
this.cache(uuid || url, img);
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
img.src = url;
}
}, url)
})
}
loadImage(callback: Function, url: string, crossOrigin: boolean = true) {
let self = this
let img = new Image();
if (crossOrigin) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = function (e) {
self.cache(url, img);
callback(true, img);
};
img.onerror = function (e) {
callback(false, e);
};
img.src = url;
return img
/**
* 加载纹理
* @param url
* @param uuid
*/
loadTexture(url: string, uuid?: string) {
return this.loadImage(url)
.then(image => {
return TextureCache[uuid || url] = Texture.from(image);
})
}
/*loadSvga(callback: (suc: boolean, data: VideoEntity) => void, url: string) {
......@@ -113,10 +111,8 @@ export class Loader extends EventDispatcher {
if (this.caches[name]) {
//console.log("覆盖原先数据:" + name);
}
this.caches[name] = data
this.caches[name] = data;
}
}
async function fetchAsync(url: string) {
......
......@@ -6,69 +6,77 @@ import {obj2query} from "../zeroing/utils";
/**
* http请求
* @param callback
* @param url
* @param method
* @param params
* @param type
*/
export function httpRequest(callback: Function, url: string, method: string = 'get', params?: any, type: 'text' | 'json' | 'jsonp' = 'text') {
export function httpRequest(url: string, method: string = 'get', params?: any, type: 'text' | 'json' | 'jsonp' = 'text') {
if (type === "jsonp") {
jsonp(callback, url, params);
return jsonp(url, params);
} else {
let _req;
if (window["XMLHttpRequest"]) {
_req = new XMLHttpRequest();
} else if (window["ActiveXObject"]) {
_req = new window["ActiveXObject"]();
} else {
console.log('no xhr');
}
if (_req != null) {
const isGet = method.toUpperCase() === 'GET';
const queryStr = obj2query(params);
if (isGet) {
url = urlJoin(url, queryStr);
}
_req.open(method, url, true);
if(!isGet){
_req.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
}
_req.responseType = type;
if (isGet) {
_req.send();
return new Promise((resolve, reject) => {
let _req;
if (window["XMLHttpRequest"]) {
_req = new XMLHttpRequest();
} else if (window["ActiveXObject"]) {
_req = new window["ActiveXObject"]();
} else {
_req.send(queryStr);
console.log('no xhr');
}
_req.onreadystatechange = () => {
if (_req.readyState == 4 && _req.status == 200) {
callback && callback(true, _req.response)
if (_req != null) {
const isGet = method.toUpperCase() === 'GET';
const queryStr = obj2query(params);
if (isGet) {
url = urlJoin(url, queryStr);
}
_req.open(method, url, true);
if (!isGet) {
_req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
}
_req.responseType = type;
if (isGet) {
_req.send();
} else {
_req.send(queryStr);
}
_req.onreadystatechange = () => {
if (_req.readyState == 4 && _req.status == 200) {
resolve(_req.response)
}
};
_req.onerror = (reason): void => {
reject(reason)
}
};
_req.onerror = (reason): void => {
callback && callback(false, reason)
}
}
});
}
}
export function jsonp(callback, url, params) {
const src = urlJoin(url, obj2query(params));
const scriptEl = document.createElement('script');
scriptEl.src = src;
scriptEl.onload = function () {
callback && callback(true);
document.body.removeChild(scriptEl);
};
scriptEl.onerror = function () {
callback && callback(false);
document.body.removeChild(scriptEl);
};
/*const callbackFuncName = '__zeroing_jsonp_callback__' + Math.random();
window[callbackFuncName] = function () {
callback(result);
};*/
document.body.appendChild(scriptEl);
/**
* jsonp请求
* @param url
* @param params
*/
export function jsonp(url, params) {
return new Promise((resolve, reject) => {
const src = urlJoin(url, obj2query(params));
const scriptEl = document.createElement('script');
scriptEl.src = src;
scriptEl.onload = function () {
resolve();
document.body.removeChild(scriptEl);
};
scriptEl.onerror = function () {
reject();
document.body.removeChild(scriptEl);
};
/*const callbackFuncName = '__zeroing_jsonp_callback__' + Math.random();
window[callbackFuncName] = function () {
callback(result);
};*/
document.body.appendChild(scriptEl);
})
}
export function urlJoin(url, query) {
......
......@@ -113,7 +113,7 @@ export class EditableText extends TextField {
}
//font包括字体和大小
s.htmlElement.style.font = s.size + "px " + this.font;
s.htmlElement.style.color = s.textColor;
s.htmlElement.style.colorD = s.textColor;
s.htmlElement.style.textAlign = s["_textWidth"] ? s.textAlign : TEXT_ALIGN.LEFT;
// s.htmlElement.setAttribute("class", "inputTextFor");
// .inputTextFor:: -webkit - input - placeholder {
......
......@@ -127,7 +127,7 @@ export class InputText extends FloatDisplay {
s.htmlElement.placeholder = text;
//font包括字体和大小
s.htmlElement.style.font = size + "px " + font;
s.htmlElement.style.color = color;
s.htmlElement.style.colorD = color;
s.htmlElement.style.textAlign = align;
/////////////////////设置边框//////////////
s.border = showBorder;
......@@ -233,11 +233,11 @@ export class InputText extends FloatDisplay {
*/
public set color(value: string) {
var ss = this.htmlElement.style;
ss.color = value;
ss.colorD = value;
}
public get color(): string {
return this.htmlElement.style.color;
return this.htmlElement.style.colorD;
}
/**
......
......@@ -12,7 +12,7 @@ export default class TextureSheet {
/**
* Reference to ths source texture
*/
baseTexture: BaseTexture;
baseTexture;
/**
* A map containing all textures of the sprite sheet.
* Can be used to create a {@link Sprite|Sprite}:
......@@ -56,7 +56,7 @@ export default class TextureSheet {
* @param {BaseTexture} baseTexture Reference to the source BaseTexture object.
* @param {Object} data - TextureSheet image data.
*/
constructor(baseTexture: BaseTexture, data: any) {
constructor(baseTexture: BaseTexture | Texture, data: any) {
this.baseTexture = baseTexture;
this.textures = {};
this.animations = {};
......
......@@ -6,20 +6,6 @@ import {SCROLL_DIRECTION} from "../const";
// import Tween from "../../tweenSimple/Tween";
let queue: ScrollContainer[] = [];
function registerScrollInstance(scrollContainer?) {
while (queue.length > 0) {
let item = queue.shift();
if(scrollContainer){
item.cancelScroll();
}
}
if(scrollContainer){
queue.push(scrollContainer);
}
}
/**
* 滚动视图
* @class ScrollPage
......@@ -200,7 +186,7 @@ export class ScrollContainer extends Container {
s.stage.removeEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
s.stage.removeEventListener(MouseEvent.MOUSE_MOVE, s.onMouseEvent, s);
});
s.addEventListener(MouseEvent.MOUSE_DOWN, s.onMouseEvent, s);
s.addEventListener(MouseEvent.MOUSE_DOWN, s.onMouseEvent, s, false);
// s.addEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
// s.addEventListener(MouseEvent.MOUSE_OUT, s.onMouseEvent, s);
s.addEventListener(Event.ENTER_FRAME, function () {
......@@ -327,6 +313,7 @@ export class ScrollContainer extends Container {
let view: any = s.viewPort;
// if (s.distance < s.maxDistance) {
if (e.type == MouseEvent.MOUSE_DOWN) {
e.stopPropagation();
if (!s.isStop) {
s.isStop = true;
}
......@@ -341,8 +328,6 @@ export class ScrollContainer extends Container {
}
s.speed = 0;
s.isMouseDownState = 1;
registerScrollInstance(this);
} else if (e.type == MouseEvent.MOUSE_MOVE) {
if (s.isMouseDownState == 0) return;
if (s.isMouseDownState == 1) {
......@@ -385,8 +370,6 @@ export class ScrollContainer extends Container {
s.dispatchEvent(Event.ON_SCROLL_STOP);
}
s.isMouseDownState = 0;
registerScrollInstance();
}
// }
}
......
......@@ -55,14 +55,11 @@ export class ScrollList extends ScrollContainer {
* @param {Class} itemClassName 可以做为Item的类
* @param {number} itemWidth item宽
* @param {number} itemHeight item高
* @param {number} vW 列表的宽
* @param {number} vH 列表的高
* @param {boolean} isVertical 是横向滚动还是纵向滚动 默认是纵向
* @param {number} cols 分几列,默认是1列
* @since 1.0.9
*/
constructor(itemClassName: any, itemWidth: number, itemHeight: number, vW: number, vH: number, isVertical: boolean = true, cols: number = 1) {
super(vW, vH, 0, isVertical);
constructor(itemClassName: any, itemWidth: number, itemHeight: number, cols: number = 1) {
super();
let s = this;
s._instanceType = "ScrollList";
s._itemW = itemWidth;
......@@ -145,14 +142,11 @@ export class ScrollList extends ScrollContainer {
/**
* 设置可见区域,可见区域的坐标始终在本地坐标中0,0点位置
* @method setViewRect
* @param {number}w 设置可见区域的宽
* @param {number}h 设置可见区域的高
* @param {boolean} isVertical 方向
* @public
* @since 1.1.1
*/
public updateViewRect(w: number, h: number, isVertical: boolean): void {
super.updateViewRect(w, h, isVertical);
public updateViewRect(): void {
super.updateViewRect();
let s = this;
if (s._itemRow && s._itemCol) {
s._updateViewRect();
......
......@@ -35,10 +35,7 @@ export * from './2d/const'
export * from './zeroing'
export {default as Color} from 'color'
// function aa(){
// HashObject
......
......@@ -8,11 +8,13 @@ import {getDataByPath, linkedFlag, nodeScheme, objClone} from "../utils";
import {findNodeByUUID} from "../node-utils";
import {dataCenter} from "../game-warpper/data-center";
import {env} from "../game-warpper/enviroment";
import {getLogSwitch, Logs} from "../log-switch";
const log = true;
const log = getLogSwitch(Logs.PROCESS);
const linkScheme = 'link://';
export class Process {
private readonly id;
private _config;
private _parent: Process;
private _vm: VM;
......@@ -21,8 +23,8 @@ export class Process {
private _target;
private _originProps;
constructor() {
constructor(id) {
this.id = id;
}
get processConfig() {
......@@ -45,8 +47,8 @@ export class Process {
this._sequence = sequence;
this._target = target;
if (!this._originProps && this._config.props) {
this._originProps = objClone(this._config.props)
if (!this._config._originProps && this._config.props) {
this._config._originProps = objClone(this._config.props)
}
}
......@@ -98,7 +100,7 @@ export class Process {
if (this._meta) {
let metaConfig = this._meta;
if (metaConfig) {
this.updateProps(this._config.props = {}, payload, this._originProps, this._meta.props);
this.updateProps(this._config.props = {}, payload, this._config._originProps, this._meta.props);
if (metaConfig.script) {
let func;
if (metaConfig.script.indexOf(linkScheme) === 0) {
......@@ -106,12 +108,18 @@ export class Process {
} else {
func = new Function('args', 'props', 'target', 'global', 'vm', warpAsyncScript(metaConfig.script));
}
if (!func) {
console.log();
if (func) {
let globalContext = this._vm.globalContext;
globalContext.dataCenter = globalContext.gameStage.dataCenter;
result = await func(payload, this._config.props, this._target, globalContext, this._vm);
if (log){
console.log(`[${this._vm.id}:${this.id}] output: <${result.type}>`, result.payload ? JSON.stringify(result.payload) : '');
}
} else {
if (log){
console.log('script lose');
}
}
let globalContext = this._vm.globalContext;
globalContext.dataCenter = globalContext.gameStage.dataCenter;
result = await func(payload, this._config.props, this._target, globalContext, this._vm);
}
} else {
console.warn(`process meta [${meta}] not found`)
......
......@@ -14,6 +14,8 @@ export class VM {
_id;
_scriptMap;
_pid = 0;
setup(context) {
const {processMetaLibs, globalContext, target, scriptMap} = context;
......@@ -25,7 +27,7 @@ export class VM {
}
async executeProcess(sequence, id, parentProcess, args) {
const process = new Process();
const process = new Process(this._pid++);
process.init({
sequence,
id,
......@@ -46,7 +48,7 @@ export class VM {
}
}
getScript(hash){
getScript(hash) {
return this._scriptMap[hash];
}
......
......@@ -3,6 +3,9 @@
*/
import {VM} from "./VM";
import {getLogSwitch, Logs} from "../log-switch";
const log = getLogSwitch(Logs.PROCESS);
let processMetaLibs = [];
let globalContext = {};
......@@ -14,7 +17,9 @@ let scriptMap = {};
*/
export function setProcessMetaLibs(...metaContexts) {
for (let context of metaContexts) {
processMetaLibs.push(context);
if(context){
processMetaLibs.push(context);
}
}
}
......
/**
* Created by rockyl on 2019-11-08.
*/
import {propertyParse} from "../utils";
import {injectProperties, instantiateScript, propertyParse} from "../utils";
const cloneFields = [
/*node*/ 'x', 'y', 'width', 'height', 'rotation', 'alpha', 'scaleX', 'scaleY', 'visible',
......@@ -22,17 +22,29 @@ export function afterConstructor(ctor: Function) {
this.applyEvents();
};
ctor.prototype.clone = function () {
ctor.prototype.clone = function (withEvents = false, withScripts: false) {
let target = this.constructor.apply(Object.create(this.constructor.prototype));
let originConfig = this.__originConfig;
target.name = originConfig.name;
for (let field in originConfig.properties) {
propertyParse(field, target, originConfig.properties);
const {name, properties, events, scripts} = this.__originConfig;
target.name = name;
injectProperties(target, properties);
if(withScripts){
if (scripts && scripts.length > 0) {
for (let scriptConfig of scripts) {
instantiateScript(target, scriptConfig);
}
}
}
if(withEvents){
if (events) {
target.eventsProxy.eventsConfig = events;
}
target.eventsProxy.start();
}
for(let child of this.children){
let childCopy = child.clone();
let childCopy = child.clone(withEvents, withScripts);
target.addChild(childCopy);
}
......
......@@ -98,8 +98,8 @@ export function registerScriptDef(id, def) {
}
export function registerScripts(scripts) {
for (let id in scripts) {
let code = scripts[id];
for (let script of scripts) {
let {id, code} = script;
let def = importCJSCode(code);
registerScriptDef(id, def);
}
......
......@@ -15,6 +15,7 @@ import {injectEnv} from "./enviroment";
import {registerCustomModuleFromConfig} from "./custom-module";
import {hideLoadingView, showLoadingView} from "./loading-view";
import {Toast} from "./Toast";
import {arrayFind} from "../utils";
/**
* 游戏舞台
......@@ -104,18 +105,22 @@ export class GameStage extends Container {
let total = assets.length;
if (customs) {
for (let custom of customs) {
if(custom.assets){
if (custom.assets) {
total += custom.assets.length;
}
}
}
showLoadingView();
await loadAssets(assets, p);
await loadAssets(assets, p).catch(e => {
console.log(e);
});
if (customs) {
for (let custom of customs) {
if(custom.assets){
await loadAssets(custom.assets, p);
if (custom.assets) {
await loadAssets(custom.assets, p).catch(e => {
console.log(e);
});
}
}
}
......@@ -183,7 +188,7 @@ export class GameStage extends Container {
* @param name
*/
getViewConfigByName(name) {
return this._config.views.find(view => view.name === name);
return arrayFind(this._config.views, view => view.name === name);
}
/**
......
......@@ -3,6 +3,7 @@
*/
import {globalLoader} from "../../2d/loader/Loader";
import {arrayFind} from "../utils";
let assetsConfig = [];
......@@ -16,6 +17,7 @@ const loaderMapping = {
'.json': 'Json',
'.svga': 'Svga',
'.sht': 'Sheet',
'': 'Raw',
};
/**
......@@ -29,18 +31,17 @@ export function loadAssets(config, onProgress?, onComplete?) {
return Promise.all(
config.map(assetConfig => {
assetsConfig.push(assetConfig);
return new Promise((resolve) => {
const loadFunc = loaderMapping[assetConfig.ext] || 'Raw';
globalLoader['load' + loadFunc](function (result, payload) {
if (result) {
loaded++;
onProgress && onProgress(loaded, total);
} else {
failedList.push(assetConfig.url);
}
resolve();
}, assetConfig.url);
})
const loadFunc = loaderMapping[assetConfig.ext] || 'Raw';
let method = globalLoader['load' + loadFunc] || globalLoader.loadRaw;
return method.call(globalLoader, assetConfig.url, assetConfig.uuid).then(
(data)=>{
loaded++;
onProgress && onProgress(loaded, total);
},
(error)=>{
failedList.push(assetConfig.url);
}
);
})
).then(
() => {
......@@ -58,7 +59,7 @@ export function loadAssets(config, onProgress?, onComplete?) {
* @param uuid
*/
export function getAssetByUUID(uuid) {
return assetsConfig.find(item => item.uuid === uuid);
return arrayFind(assetsConfig,item => item.uuid === uuid);
}
/**
......@@ -66,5 +67,5 @@ export function getAssetByUUID(uuid) {
* @param name
*/
export function getAssetByName(name) {
return assetsConfig.find(item => item.name === name);
return arrayFind(assetsConfig,item => item.name === name);
}
......@@ -24,7 +24,7 @@ export class DataCenter extends EventDispatcher {
* @param origin
*/
registerGroup(name, origin?) {
this.store[name] = origin || {};
return this.store[name] = origin || {};
}
/**
......@@ -125,7 +125,7 @@ export class DataCenter extends EventDispatcher {
let group = this.getGroup(groupName);
if (!group) {
this.registerGroup(groupName);
group = this.registerGroup(groupName);
}
if (data !== undefined) {
if (path) {
......
......@@ -32,11 +32,12 @@ export class Image extends Sprite {
if(url.indexOf('://') >= 0){ //如果是有协议的地址
if (url.indexOf(assetScheme) === 0) {
let uuid = url.replace(assetScheme, '');
const assetConfig = getAssetByUUID(uuid);
/*const assetConfig = getAssetByUUID(uuid);
if(assetConfig){
url = assetConfig.url;
this.texture = Texture.fromImage(url);
}
}*/
this.texture = Texture.from(uuid);
}
} else{ //否则就使用素材名
const assetConfig = getAssetByName(url);
......
/**
* Created by rockyl on 2019-11-06.
*/
import Color from "color";
import {Shape} from "../../../";
import {Event} from "../../../2d/events";
import {dirtyFieldDetector} from "../../decorators";
import Graphics from "../../../2d/graphics/Graphics";
/**
* 图形基类
*/
class ShapeBase extends Shape {
class ShapeBase extends Graphics {
protected __fieldDirty = true;
@dirtyFieldDetector
......@@ -36,15 +38,12 @@ class ShapeBase extends Shape {
const {fillColor, strokeColor, strokeWidth} = this;
this.clear();
this.beginFill(fillColor);
this.beginFill(new Color(fillColor).rgbNumber());
if (strokeWidth > 0) {
this.beginStroke(strokeColor, strokeWidth);
this.lineStyle(strokeWidth, new Color(strokeColor).rgbNumber());
}
this.redraw();
this.endFill();
if (strokeWidth > 0) {
this.endStroke();
}
}
}
......@@ -64,7 +63,7 @@ export class Rect extends ShapeBase {
const {width, height, borderRadius,} = this;
if (borderRadius > 0) {
this.drawRoundRect(0, 0, width, height, borderRadius, borderRadius, borderRadius, borderRadius)
this.drawRoundedRect(0, 0, width, height, borderRadius);
} else {
this.drawRect(0, 0, width, height);
}
......
/**
* Created by rockyl on 2019-12-09.
*/
import BaseTexture from "../../2d/texture/BaseTexture";
import {Rectangle} from "../../2d/math";
import Texture from "../../2d/texture/Texture";
interface dataTm {
x: number, //x,y,w,h为图集上的切图位置数据
y: number,
w: number,
h: number,
ox: number, //ox,oy为偏移数据,trim裁剪的数据,在orig上的偏移{x:0,y:0,width:200,height:200}
oy: number,
sw: number, //sw,sh为原始宽高
sh: number,
ro: boolean, //是否旋转
}
export function createTextureSheet(baseTexture: BaseTexture, altaData) {
var frames = altaData;
var frameKeys = Object.keys(frames);
let frameIndex = 0;
while (frameIndex < frameKeys.length) {
//名字
const i = frameKeys[frameIndex];
//数据
const data: dataTm = frames[i];
//切图上的数据
let frame: Rectangle = null;
//裁切的数据
let trim: Rectangle = null;
//贴图原始尺寸
const orig = new Rectangle(
0,
0,
Math.floor(data.sw),
Math.floor(data.sh)
);
//如果旋转过
if (data.ro) {
frame = new Rectangle(
Math.floor(data.x),
Math.floor(data.y),
Math.floor(data.h),
Math.floor(data.w)
);
} else {
frame = new Rectangle(
Math.floor(data.x),
Math.floor(data.y),
Math.floor(data.w),
Math.floor(data.h)
);
}
//如果是被截掉过透明边界的
if (data.ox || data.oy) {
//其实就是在orig上切图,偏移
trim = new Rectangle(
Math.floor(data.ox),
Math.floor(data.oy),
Math.floor(data.w),
Math.floor(data.h)
);
}
var texture = new Texture(
baseTexture,
frame,
orig,
trim,
data.ro ? 2 : 0,
// data.anchor
);
//缓存下
Texture.addToCache(texture, i);
frameIndex++;
}
}
\ No newline at end of file
......@@ -4,7 +4,7 @@
import {Container} from "../../2d/display";
import {Rect, Image, Label, Circle, ScrollView} from "./nodes";
import {propertyParse} from "../utils";
import {injectProperties, instantiateScript, propertyParse} from "../utils";
const nodeTypeMapping = {
node: Container,
......@@ -20,7 +20,7 @@ export function instantiate(config) {
}
function instantiateView(config) {
const {type, scripts} = config;
const {type} = config;
const nodeTypeDef = nodeTypeMapping[type];
if (!nodeTypeDef) {
......@@ -29,7 +29,7 @@ function instantiateView(config) {
}
const node = new nodeTypeDef();
const {name, uuid, properties, children, events} = config;
const {name, uuid, properties, children, events, scripts} = config;
node.name = name;
node.uuid = uuid;
node.__originConfig = config;
......@@ -56,14 +56,3 @@ function instantiateView(config) {
return node;
}
function instantiateScript(node, ScriptConfig) {
const {script: scriptName, props, disabled} = ScriptConfig;
const script = node.scriptsProxy.add(scriptName, props, disabled);
}
function injectProperties(target, source) {
for (let key in source) {
propertyParse(key, target, source);
}
}
......@@ -9,6 +9,8 @@ export * from './utils'
export * from './decorators'
export * from './game-warpper'
export * from './behavior-runtime'
export * from './web'
export * from './log-switch'
import {instantiate} from './game-warpper/view-interpreter'
export {
......
......@@ -3,43 +3,38 @@
*/
import {Stage} from "../2d/display";
import {RENDERER_TYPE, StageScaleMode} from "..";
import {registerCustomModuleFromConfig, registerScripts, RENDERER_TYPE, setProcessMetaLibs, StageScaleMode} from "..";
import {GameStage} from "./game-warpper";
import {setGlobalContext} from "./behavior-runtime";
import {globalLoader} from "../2d/loader/Loader";
import {Event} from "../2d/events/Event";
export let gameStage;
export let gameStage: GameStage;
export function launch(url, onAssetsProgress, onAssetsComplete) {
return new Promise((resolve, reject) => {
globalLoader.loadJson((s, payload) => {
if(s){
resolve(payload);
}else{
reject(payload);
}
}, url);
}).then(
config=>{
return globalLoader.loadJson(url)
.then(config => {
return launchWithConfig(config, onAssetsProgress, onAssetsComplete);
}
)
});
}
export function launchWithLocalStorage(id, onAssetsProgress, onAssetsComplete){
export function launchWithLocalStorage(id, onAssetsProgress, onAssetsComplete) {
const storeKey = 'preview-project-' + id;
let data = localStorage.getItem(storeKey);
let dataObj = JSON.parse(data);
let storeData = localStorage.getItem(storeKey);
let {data, processes, scripts, customs,} = JSON.parse(storeData);
setProcessMetaLibs(processes);
registerScripts(scripts);
registerCustomModuleFromConfig(customs);
return launchWithConfig(dataObj, onAssetsProgress, onAssetsComplete);
return launchWithConfig(data, onAssetsProgress, onAssetsComplete);
}
export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) {
return new Promise(resolve => {
const {containerID, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.options;
const {containerId, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.options;
let stage = window['stage'] = new Stage(
containerID || "game-container",
containerId || "game-container",
designWidth || 750,
designHeight || 1334,
frameRate || 60,
......@@ -48,7 +43,7 @@ export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) {
);
Stage.flushAll();
stage.addEventListener(Event.ON_INIT_STAGE, ()=>{
stage.addEventListener(Event.ON_INIT_STAGE, () => {
gameStage = new GameStage(stage);
setGlobalContext({
gameStage
......
/**
* Created by rockyl on 2019-12-11.
*/
const storeKey = 'zlog-switch';
export enum Logs{
PROCESS = 'process',
}
let store;
try {
store = JSON.parse(localStorage.getItem(storeKey));
store = store === null ? false : store;
} catch (e) {
store = false;
localStorage.setItem(storeKey, JSON.stringify(store));
}
export function getLogSwitch(id) {
return typeof store === 'object' ? (!!store[id]) : !!store;
}
......@@ -8,11 +8,14 @@ export const ESCAPE_REG_EXP = /\$\{[\u4e00-\u9fa5_a-zA-Z0-9\|]+\}/g;
export const linkedFlag = '$_linked_$';
export const nodeScheme = 'node://';
export function arrayFind(arr, callback) {
export function arrayFind(arr, predicate) {
if(!arr){
return ;
}
for (let i = 0, li = arr.length; i < li; i++) {
const item = arr[i];
if (callback(item, i, arr)) {
if (predicate(item, i, arr)) {
return item;
}
}
......@@ -212,9 +215,49 @@ export function htmlToPureText(htmlText) {
el = document.createElement('div');
}
el.innerHTML = htmlText;
document.body.append(el);
document.body.appendChild(el);
let pureText = el.innerText;
document.body.removeChild(el);
return pureText;
}
const zhReg = /[\u4e00-\u9fa5]/;
export function strLen(str){
let len = 0;
for(let char of str){
len += char.match(zhReg) ? 2 : 1;
}
return len;
}
export function strShort(str, limit, replace = '…'){
let result = '';
if(strLen(str) > limit){
let len = 0;
for (let i = 0, li = str.length; i < li; i++) {
const char = str[i];
len += char.match(zhReg) ? 2 : 1;
if(len > limit){
result += replace;
break;
}else{
result += char;
}
}
}else{
result = str;
}
return result;
}
export function instantiateScript(node, ScriptConfig) {
const {script: scriptName, props, disabled} = ScriptConfig;
const script = node.scriptsProxy.add(scriptName, props, disabled);
}
export function injectProperties(target, source) {
for (let key in source) {
propertyParse(key, target, source);
}
}
/**
* Created by rockyl on 2019-12-10.
*/
export let queryParams:any = {};
for(let item of location.search.replace('?', '').split('&')){
let arr = item.split('=');
queryParams[arr[0]] = arr.length === 1 ? true : arr[1];
}
......@@ -811,7 +811,7 @@ collection-visit@^1.0.0:
map-visit "^1.0.0"
object-visit "^1.0.0"
color-convert@^1.9.0:
color-convert@^1.9.0, color-convert@^1.9.1:
version "1.9.3"
resolved "https://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcolor-convert%2Fdownload%2Fcolor-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
integrity sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=
......@@ -823,6 +823,27 @@ color-name@1.1.3:
resolved "https://registry.npm.taobao.org/color-name/download/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
color-name@^1.0.0:
version "1.1.4"
resolved "https://registry.npm.taobao.org/color-name/download/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha1-wqCah6y95pVD3m9j+jmVyCbFNqI=
color-string@^1.5.2:
version "1.5.3"
resolved "https://registry.npm.taobao.org/color-string/download/color-string-1.5.3.tgz#c9bbc5f01b58b5492f3d6857459cb6590ce204cc"
integrity sha1-ybvF8BtYtUkvPWhXRZy2WQziBMw=
dependencies:
color-name "^1.0.0"
simple-swizzle "^0.2.2"
color@^3.1.2:
version "3.1.2"
resolved "https://registry.npm.taobao.org/color/download/color-3.1.2.tgz#68148e7f85d41ad7649c5fa8c8106f098d229e10"
integrity sha1-aBSOf4XUGtdknF+oyBBvCY0inhA=
dependencies:
color-convert "^1.9.1"
color-string "^1.5.2"
commander@^2.20.0, commander@^2.9.0, commander@~2.20.3:
version "2.20.3"
resolved "https://registry.npm.taobao.org/commander/download/commander-2.20.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcommander%2Fdownload%2Fcommander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
......@@ -2054,6 +2075,11 @@ is-arguments@^1.0.4:
resolved "https://registry.npm.taobao.org/is-arguments/download/is-arguments-1.0.4.tgz#3faf966c7cba0ff437fb31f6250082fcf0448cf3"
integrity sha1-P6+WbHy6D/Q3+zH2JQCC/PBEjPM=
is-arrayish@^0.3.1:
version "0.3.2"
resolved "https://registry.npm.taobao.org/is-arrayish/download/is-arrayish-0.3.2.tgz#4574a2ae56f7ab206896fb431eaeed066fdf8f03"
integrity sha1-RXSirlb3qyBolvtDHq7tBm/fjwM=
is-binary-path@^1.0.0:
version "1.0.1"
resolved "https://registry.npm.taobao.org/is-binary-path/download/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898"
......@@ -3636,6 +3662,13 @@ signal-exit@^3.0.0:
resolved "https://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d"
integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=
simple-swizzle@^0.2.2:
version "0.2.2"
resolved "https://registry.npm.taobao.org/simple-swizzle/download/simple-swizzle-0.2.2.tgz#a4da6b635ffcccca33f70d17cb92592de95e557a"
integrity sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=
dependencies:
is-arrayish "^0.3.1"
snapdragon-node@^2.0.1:
version "2.1.1"
resolved "https://registry.npm.taobao.org/snapdragon-node/download/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
......@@ -4005,7 +4038,7 @@ ts-loader@^4.0.0:
micromatch "^3.1.4"
semver "^5.0.1"
tslib@1.10.0, tslib@^1.10.0, tslib@^1.9.0:
tslib@1.10.0, tslib@^1.9.0:
version "1.10.0"
resolved "https://registry.npm.taobao.org/tslib/download/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a"
integrity sha1-w8GflZc/sKYpc/sJ2Q2WHuQ+XIo=
......
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