Commit 53470397 authored by rockyl's avatar rockyl

暂时去掉svga

增加数据绑定功能
完善视图解析器
增加Label
parent 808d1115
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -30,10 +30,10 @@
<body>
<script type="text/javascript" src="../build/render.min.js"></script>
<script type="text/javascript" src="../dist/index.js"></script>
<div id="cusEngine" style="line-height:0;font-size:0"></div>
<script src="scripts/ScriptDemo.js"></script>
<script src="view-data.js"></script>
<script src="view-interpreter.js"></script>
<script src="game-stage.js"></script>
......
......@@ -2,35 +2,29 @@
* Created by rockyl on 2019-11-06.
*/
let stage = new engine.Stage(
"cusEngine",
750,
1334,
60,
engine.StageScaleMode.FIXED_WIDTH,
engine.RENDERER_TYPE.WEBGL
);
//启动循环
engine.Stage.flushAll();
//todo 星速台ID绑定
let gameStage = new engine.GameStage(stage);
stage.addChild(gameStage);
engine.registerScriptDef(ScriptDemo);
engine.loadAssets(data.assets, function (loaded, total) {
//console.log(`assets process: ${loaded}/${total}`)
}).then(
() => {
console.log('assets loaded');
start();
const gameStage = engine.launch(data);
const dataCenter = gameStage.dataCenter;
dataCenter.registerGroup('test', {
hello: {
aaa: {
name: 'tom',
id: 1001,
age: 29,
avatar: '0a5f2064-f5b4-41a9-8a54-2085e208d20f',
}
}
).catch(e=>{
console.log(e);
});
function start() {
let sceneEntry = instantiate(data.views[0]);
gameStage.sceneContainer.push(sceneEntry);
let dialog = instantiate(data.views[1]);
gameStage.popupContainer.push(dialog);
}
/*console.log(dataCenter.getDataByPath('test.hello.aaa.name'));*/
let i = 0;
setInterval(()=>{
//dataCenter.mutate('test', 'jerry' + Math.random(), 'hello.aaa.name');
dataCenter.mutate('test', data.assets[i % data.assets.length].uuid, 'hello.aaa.avatar');
i++;
}, 1000);
/**
* Created by rockyl on 2019-11-07.
*/
class ScriptDemo {
static name = 'ScriptDemo';
mounted(){
console.log('mounted', this.duration);
this.host.anchorX = this.host.width / 2;
this.host.anchorY = this.host.height / 2;
}
destroy(){
console.log('destroy');
}
update(t){
//console.log('update', t);
this.host.rotation = t * 0.1;
}
awake(){
console.log('awake');
}
sleep(){
console.log('sleep');
}
}
......@@ -3,6 +3,15 @@
*/
const data = {
launchOptions: {
entrySceneView: 'view1',
containerID: 'cusEngine',
designWidth: 750,
designHeight: 1334,
frameRate: 60,
scaleMode: 'fixedWidth',
rendererType: 'webgl',
},
"views": [
{
name: 'view1',
......@@ -14,27 +23,44 @@ const data = {
},
uuid: '3a357816-5581-41ba-aa6f-4a6cc40ae396',
children: [
{
/*{
name: "bg",
type: "rect",
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a",
properties: {
width: '100%',
height: '100%',
fillColor: "#1E2127",
},
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a",
},
{
},*/
/*{
name: "label",
type: "label",
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a",
properties: {
width: '100%',
height: '100%',
fillColor: "#44ff00",
text: 'Hello',
text: 'Hello ${nickname}',
size: 30,
},
},*/
{
name: "img",
type: "image",
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a",
properties: {
source: 'asset://${avatar}'
},
/*scripts: [
{
script: 'ScriptDemo',
disabled: false,
properties: {
duration: 1000,
},
}
]*/
},
]
},
......@@ -228,7 +254,10 @@ const data = {
"uuid": "2b0cc6bd-fc10-43ee-a217-aaf1c40a0ad3",
"url": "//yun.duiba.com.cn/aurora/93fbb49529a3b4617f4cdc41dba7c297989baa5e.png"
}],
"dataMapping": [],
"dataMapping": [
{name: 'nickname', path: 'test.hello.aaa.name'},
{name: 'avatar', path: 'test.hello.aaa.avatar'},
],
processes: [
{
id: 'main',
......
......@@ -5,15 +5,20 @@
"main": "index.js",
"types": "index.d.ts",
"dependencies": {
"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-uglify": "^6.0.3",
"ts-loader": "^4.0.0",
"webpack": "^4.1.0",
"webpack-dev-server": "^3.1.0",
"typescript": "^2.7.2",
"uglifyjs-webpack-plugin": "^2.1.2"
"uglifyjs-webpack-plugin": "^2.1.2",
"webpack": "^4.1.0",
"webpack-dev-server": "^3.1.0"
},
"devDependencies": {
"webpack-cli": "^3.3.2",
"protobufjs": "^6.8.0"
"protobufjs": "^6.8.0",
"webpack-cli": "^3.3.2"
},
"scripts": {
"build": "webpack",
......
/**
* Created by rockyl on 2018/11/16.
*/
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const progress = require('rollup-plugin-progress');
const typescript = require('rollup-plugin-typescript');
const {uglify} = require('rollup-plugin-uglify');
export default {
input: 'src/index.ts',
output: [
{
file: `dist/index.js`,
format: 'umd',
name: 'engine',
sourcemap: true,
}
],
plugins: [
progress(),
resolve({
//only: [/^\.{0,2}\//],
}),
typescript(),
commonjs(),
//uglify({}),
],
onwarn: function(){
}
};
......@@ -4,7 +4,8 @@ import { Point } from '../math';
import CanvasRenderer from '../renderers/CanvasRenderer';
import {Event} from "../events/Event"
import {WebglRenderer} from '../renderers/WebglRenderer';
import {applyAutoAdjust, applyScript} from "../../zeroing";
import {applyAutoAdjust} from "../../zeroing/auto-adjust";
import {applyScript} from "../../zeroing/script-manager";
/**
* 容器类
......@@ -36,10 +37,15 @@ export default class Container extends DisplayObject {
super();
this._instanceType = "Container";
this.children = [];
this.afterConstructor();
this.applyAutoAdjust();
this.applyScripts();
}
afterConstructor() {
applyAutoAdjust() {
}
applyScripts() {
}
......@@ -492,14 +498,14 @@ export default class Container extends DisplayObject {
* 更新方法
*/
update(deltaTime: number) {
if (!this.visible) return;
/*if (!this.visible) return;*/
//更新自己的
super.update(deltaTime)
//更新儿子们的
let len = this.children.length;
for (let i = len - 1; i >= 0; i--) {
const child = this.children[i];
if (child.visible) child.update(deltaTime);
/*if (child.visible)*/ child.update(deltaTime);
}
}
......
import { EventDispatcher } from "../events/EventDispatcher";
import { Parser } from "../svga/parser";
import { VideoEntity } from "../svga/VideoEntity";
//import { Parser } from "../svga/parser";
//import { VideoEntity } from "../svga/VideoEntity";
import { TextureCache } from "../utils";
import { Texture } from "../texture";
......@@ -12,7 +12,7 @@ export class Loader extends EventDispatcher {
caches = {};
parser: Parser;
//parser: Parser;
_req: XMLHttpRequest = null;
......@@ -114,7 +114,7 @@ export class Loader extends EventDispatcher {
return img
}
loadSvga(callback: (suc: boolean, data: VideoEntity) => void, url: string) {
/*loadSvga(callback: (suc: boolean, data: VideoEntity) => void, url: string) {
if (!this.parser) this.parser = new Parser();
this.parser.load(url, function (videoItem: VideoEntity) {
callback(true, videoItem)
......@@ -123,7 +123,7 @@ export class Loader extends EventDispatcher {
callback(false, error)
// alert(error.message);
})
}
}*/
cache(name: string, data: any) {
if (this.caches[name]) {
......
import { SCALE_MODES, TEXT_ALIGN, TEXT_lINETYPE, VERTICAL_ALIGN } from "../const";
import {SCALE_MODES, TEXT_ALIGN, TEXT_lINETYPE, VERTICAL_ALIGN} from "../const";
import Texture from "../texture/Texture";
import { getRGBA, hex2string } from "../utils";
import { Rectangle } from "../math";
import {getRGBA, hex2string} from "../utils";
import {Rectangle} from "../math";
import Sprite from "../display/Sprite";
import { Event } from "../events";
import {Event} from "../events";
//文本canvas上xy的偏移量
const padding = 10;
......@@ -167,6 +167,7 @@ export class TextField extends Sprite {
this.updateText();
return this.scale.x * this.getLocalBounds().width;
}
set width(value: number) {
if (this._width !== value) {
this.dispatchEvent(Event.RESIZE);
......@@ -180,6 +181,7 @@ export class TextField extends Sprite {
this.updateText();
return this.scale.y * this.getLocalBounds().height;
}
set height(value: number) {
if (this._height !== value) {
this.dispatchEvent(Event.RESIZE);
......@@ -222,7 +224,6 @@ export class TextField extends Sprite {
this._lineType = value;
this.dirty = true;
}
;
}
public get lineType(): TEXT_lINETYPE {
......@@ -241,16 +242,19 @@ export class TextField extends Sprite {
*/
public set text(value: string) {
if (this._text != value) {
this._text = value;
this.dirty = true;
this._setText(value);
}
;
}
public get text(): string {
return this._text;
}
protected _setText(value) {
this._text = value;
this.dirty = true;
}
private _text: string = "";
/**
......@@ -513,7 +517,7 @@ export class TextField extends Sprite {
s.canvas.width = 0;
s.canvas.height = 0;
s._localBoundsSelf.clear();
this.anchorTexture = { x: 0, y: 0 };
this.anchorTexture = {x: 0, y: 0};
this.updateTexture();
return
}
......@@ -628,7 +632,7 @@ export class TextField extends Sprite {
s.offsetX = -padding;
s.offsetY = -padding;
this.anchorTexture = { x: (padding + 0.5) / can.width, y: padding / can.height }
this.anchorTexture = {x: (padding + 0.5) / can.width, y: padding / can.height}
// document.body.appendChild(can)
// s._bounds.height = maxH;
......
......@@ -2,7 +2,6 @@
// export {BitmapNumber} from "./BitmapNumber";
// export {BitmapNumbers} from "./BitmapNumbers";
export {IScrollListItem} from "./ScrollList";
export {ScrollList} from "./ScrollList";
export {ScrollPage} from "./ScrollPage";
export {Button} from "./Button";
\ No newline at end of file
......@@ -16,7 +16,7 @@ export { Matrix } from "./2d/math/Matrix";
export { Point } from "./2d/math/Point";
export { Rectangle } from "./2d/math/Rectangle";
export * from "./2d/svga";
//export * from "./2d/svga";
export * from "./2d/text";
......
......@@ -3,8 +3,10 @@
*/
import {Container, Stage} from "../2d/display";
import {Event} from "../2d/events";
import {StackContainer} from "./StackContainer";
import {loadAssets} from "./assets-manager";
import {instantiate} from "./view-interpreter";
import {dataCenter, DataCenter} from "./data-center";
/**
* 游戏舞台
......@@ -13,11 +15,15 @@ export class GameStage extends Container {
private _sceneContainer: StackContainer; //场景容器
private _popupContainer: StackContainer; //弹层容器
private _stage;
private _dataCenter: DataCenter;
private _config: any;
constructor(stage: Stage) {
super();
this._stage = stage;
this._dataCenter = dataCenter;
this['percentWidth'] = 100;
this['percentHeight'] = 100;
......@@ -39,4 +45,52 @@ export class GameStage extends Container {
get popupContainer(): StackContainer {
return this._popupContainer;
}
/**
* 数据中心
*/
get dataCenter(): DataCenter {
return this._dataCenter;
}
/**
* 启动游戏
* @param config
* @param onAssetsProgress
* @param onAssetsComplete
*/
launch(config, onAssetsProgress, onAssetsComplete) {
this._config = config;
loadAssets(config.assets, onAssetsProgress, onAssetsComplete).then(
() => {
this.start();
}
).catch(e => {
console.error('launch failed:', e);
});
}
/**
* 开始游戏
*/
start() {
const config = this._config;
this.dataCenter.registerDataMapping(config.dataMapping);
const entryViewName = config.launchOptions.entrySceneView;
let entryViewConfig = this.getViewConfigByName(entryViewName);
if (entryViewConfig) {
let sceneEntry = instantiate(entryViewConfig);
this._sceneContainer.push(sceneEntry);
} else {
console.error('entry view config not exists');
}
}
/**
* 根据name获取视图配置
* @param name
*/
getViewConfigByName(name) {
return this._config.views.find(view => view.name === name);
}
}
......@@ -6,11 +6,11 @@ import {Loader} from "..";
let assetsConfig;
const loaderMapping = {
'.png': 'Image',
'.jpg': 'Image',
'.jpeg': 'Image',
'.gif': 'Image',
'.svg': 'Image',
'.png': 'Texture',
'.jpg': 'Texture',
'.jpeg': 'Texture',
'.gif': 'Texture',
'.svg': 'Texture',
'.txt': 'Text',
'.json': 'Json',
'.svga': 'Svga',
......@@ -22,7 +22,7 @@ const loader = new Loader();
/**
* 加载素材
*/
export function loadAssets(config, onProcess) {
export function loadAssets(config, onProgress?, onComplete?) {
assetsConfig = config;
let total = assetsConfig.length;
......@@ -36,7 +36,7 @@ export function loadAssets(config, onProcess) {
loader['load' + loadFunc](function (result, payload) {
if (result) {
loaded++;
onProcess(loaded, total);
onProgress && onProgress(loaded, total);
} else {
failedList.push(assetConfig.url);
}
......@@ -48,6 +48,8 @@ export function loadAssets(config, onProcess) {
() => {
if (loaded < total) {
return Promise.reject('some asset can not loaded: ' + failedList.join(', '));
} else {
onComplete && onComplete();
}
}
)
......
......@@ -29,25 +29,25 @@ function t(v) {
* @param ctor
*/
export function applyAutoAdjust(ctor: Function) {
ctor.prototype.afterConstructor = function () {
ctor.prototype.applyAutoAdjust = function () {
let adjustData = new AdjustData();
this.__sizeDirty = true;
this.adjustData = adjustData;
this.addEventListener(Event.ADDED_TO_STAGE, this.__onAddedToStage, this);
this.addEventListener(Event.REMOVED_FROM_STAGE, this.__onRemovedFromStage, this);
this.addEventListener(Event.ADDED_TO_STAGE, this.__onAddedToStageAA, this);
this.addEventListener(Event.REMOVED_FROM_STAGE, this.__onRemovedFromStageAA, this);
};
ctor.prototype.__onAddedToStage = function () {
this.parent.addEventListener(Event.RESIZE, this.__onResize, this);
this.addEventListener(Event.ENTER_FRAME, this.__onEnterFrame, this);
ctor.prototype.__onAddedToStageAA = function () {
this.parent.addEventListener(Event.RESIZE, this.__onResizeAA, this);
this.addEventListener(Event.ENTER_FRAME, this.__onEnterFrameAA, this);
};
ctor.prototype.__onRemovedFromStage = function () {
this.parent.removeEventListener(Event.RESIZE, this.__onResize);
this.removeEventListener(Event.ENTER_FRAME, this.__onEnterFrame);
ctor.prototype.__onRemovedFromStageAA = function () {
this.parent.removeEventListener(Event.RESIZE, this.__onResizeAA);
this.removeEventListener(Event.ENTER_FRAME, this.__onEnterFrameAA);
};
ctor.prototype.__onResize = function () {
ctor.prototype.__onResizeAA = function () {
this.__sizeDirty = true;
};
ctor.prototype.__onEnterFrame = function () {
ctor.prototype.__onEnterFrameAA = function () {
if (this.__sizeDirty) {
this.__sizeDirty = false;
......
/**
* Created by rockyl on 2019-11-08.
*
* 数据中心
*/
import {EventDispatcher} from "../2d/events";
/**
* 数据中心
*/
export class DataCenter extends EventDispatcher {
store = {};
watchers = [];
constructor() {
super();
}
/**
* 注册一个分组
* @param name
* @param origin
*/
registerGroup(name, origin) {
this.store[name] = origin || {};
}
/**
* 反注册分组
* @param name
*/
unregisterGroup(name) {
delete this.store[name];
}
/**
* 获取分组
* @param name
*/
getGroup(name) {
return this.store[name];
}
/**
* 根据路径获取数据
* @param path
* @param throwException
*/
getDataByPath(path, throwException?) {
let func = new Function('scope', `return scope.${path}`);
try {
return func(this.store);
} catch (e) {
console.warn(e);
if (throwException) {
throw e;
}
}
}
/**
* 填充数据
* @param str
* @param escapes
*/
formatString(str, escapes) {
let result = str;
for (let escape of escapes) {
let watcher = this.getWatcher(escape);
try {
let data = this.getDataByPath(watcher.path, true);
result = result.replace(new RegExp('\\$\\{' + escape + '\\}', 'g'), data);
}catch (e) {
}
}
return result;
}
/**
* 修改数据
* @param name
* @param data
* @param path
*/
mutate(name, data?, path?) {
let group = this.getGroup(name);
if (!group) {
return;
}
if (data) {
if (path) {
let func = new Function('scope', 'data', `scope.${path}=data`);
try {
func(group, data);
} catch (e) {
console.warn(e);
}
} else {
this.registerGroup(name, data);
}
}
for (let watcher of this.watchers) {
if (watcher.path.indexOf(name) === 0) {
this.dispatchEvent(watcher.name, {
name: watcher.name,
path: watcher.path,
data: this.getDataByPath(watcher.path),
});
}
}
}
/**
* 添加数据侦听
* @param name
* @param path
*/
watch(name, path) {
let watcher = {name, path};
this.watchers.push(watcher);
}
/**
* 根据名字获取侦听者
* @param name
*/
getWatcher(name) {
return this.watchers.find(watcher => watcher.name === name);
}
/**
* 注册数据绑定配置
* @param dataMapping
*/
registerDataMapping(dataMapping) {
for (let item of dataMapping) {
this.watch(item.name, item.path);
}
}
}
export const dataCenter = new DataCenter();
......@@ -8,3 +8,5 @@ export * from './nodes'
export * from './assets-manager'
export * from './auto-adjust'
export * from './script-manager'
export * from './view-interpreter'
export * from './launcher'
/**
* Created by rockyl on 2019-11-08.
*/
import {Stage} from "../2d/display";
import {GameStage, RENDERER_TYPE, StageScaleMode} from "..";
export function launch(config, onAssetsProgress, onAssetsComplete) {
const {containerID, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.launchOptions;
let stage = window['stage'] = new Stage(
containerID || "cusEngine",
designWidth || 750,
designHeight || 1334,
frameRate || 60,
scaleMode || StageScaleMode.FIXED_WIDTH,
rendererType || RENDERER_TYPE.WEBGL
);
Stage.flushAll();
let gameStage = new GameStage(stage);
stage.addChild(gameStage);
setTimeout(() => {
gameStage.launch(config, onAssetsProgress, onAssetsComplete);
});
return gameStage;
}
......@@ -4,10 +4,16 @@
import {Sprite} from "../../2d/display";
import Texture from "../../2d/texture/Texture";
import {getAssetByUUID} from "../assets-manager";
import {dataCenter} from "../data-center";
import {ESCAPE_REG_EXP} from "../utils";
const assetScheme = 'asset://';
export class Image extends Sprite {
private _originText;
private _escapes = [];
private _registeredEvents = [];
private _source: string;
get source() {
......@@ -16,8 +22,7 @@ export class Image extends Sprite {
set source(v) {
if (this._source !== v) {
this._source = v;
this.updateSource();
this._setSource(v);
}
}
......@@ -30,4 +35,46 @@ export class Image extends Sprite {
}
this.texture = Texture.fromImage(url);
}
private _setSourceDirect(value){
this._source = value;
this.updateSource();
}
private _setSource(value){
let matchResult = value.match(ESCAPE_REG_EXP);
if (matchResult) {
this.unregisterEvents();
this._originText = value;
this._escapes.splice(0);
for (let item of matchResult) {
let eventName = item.substr(2, item.length - 3);
this._escapes.push(eventName);
dataCenter.addEventListener(eventName, this.onDataMutated, this);
this._registeredEvents.push(eventName);
}
this.onDataMutated();
} else {
this._setSourceDirect(value);
}
}
/**
* 把之前侦听的全部移除
*/
private unregisterEvents() {
for (let item of this._registeredEvents) {
dataCenter.removeEventListener(item, this.onDataMutated, this);
}
this._registeredEvents.splice(0);
}
/**
* 当数据改变时
* @param e
*/
private onDataMutated(e = null) {
this._setSourceDirect(dataCenter.formatString(this._originText, this._escapes));
}
}
/**
* Created by rockyl on 2019-11-08.
*/
import {TextField} from "../../2d/text";
import {dataCenter} from "../data-center";
import {ESCAPE_REG_EXP} from "../utils";
/**
* 文本
*/
export class Label extends TextField {
private _originText;
private _escapes = [];
private _registeredEvents = [];
/**
* 重载文本设置
* @param value
* @private
*/
protected _setText(value) {
let matchResult = value.match(ESCAPE_REG_EXP);
if (matchResult) {
this.unregisterEvents();
this._originText = value;
this._escapes.splice(0);
for (let item of matchResult) {
let eventName = item.substr(2, item.length - 3);
this._escapes.push(eventName);
dataCenter.addEventListener(eventName, this.onDataMutated, this);
this._registeredEvents.push(eventName);
}
this.onDataMutated();
} else {
super._setText(value);
}
}
/**
* 把之前侦听的全部移除
*/
private unregisterEvents() {
for (let item of this._registeredEvents) {
dataCenter.removeEventListener(item, this.onDataMutated, this);
}
this._registeredEvents.splice(0);
}
/**
* 当数据改变时
* @param e
*/
private onDataMutated(e = null) {
super._setText(dataCenter.formatString(this._originText, this._escapes));
}
}
......@@ -4,3 +4,4 @@
export * from './shapes'
export * from './Image'
export * from './Label'
\ No newline at end of file
......@@ -3,6 +3,8 @@
*
* 脚本功能
*/
import {Container} from "../2d/display";
import {Event} from "../2d/events";
const scriptDefs = {};
......@@ -11,53 +13,108 @@ const scriptDefs = {};
* @param ctor
*/
export function applyScript(ctor: Function) {
ctor.prototype.applyScripts = function () {
this.scripts = new ScriptsContainer(this);
this.addEventListener(Event.ENTER_FRAME, this.__onEnterFrameS, this);
this.addEventListener(Event.ADDED_TO_STAGE, this.__onAddedToStageS, this);
this.addEventListener(Event.REMOVED_FROM_STAGE, this.__onRemovedFromStageS, this);
};
ctor.prototype.__onEnterFrameS = function (e) {
this.scripts.update(e.data);
};
ctor.prototype.__onAddedToStageS = function (e) {
this.scripts.awake();
};
ctor.prototype.__onRemovedFromStageS = function (e) {
this.scripts.sleep();
};
}
/**
* 脚本接口
*/
export interface IScript {
name: string;
keepAlive: boolean;
readonly host: any;
disabled: boolean;
mounted();
destroy();
update();
update(t);
awake();
sleep();
}
/**
* 注册脚本定义
* @param name
* @param def
*/
export function registerScriptDef(name, def) {
scriptDefs[name] = def;
export function registerScriptDef(def) {
scriptDefs[def.name] = def;
Object.defineProperty(def, 'disabled', {
get: function () {
return !!this._disabled;
},
set: function (v) {
if (this._disabled !== v) {
this._disabled = v;
if (this._disabled) {
this.awake();
} else {
this.sleep();
}
}
},
enumerable: true,
configurable: true
});
}
/**
* 脚本容器
*/
class ScriptsContainer {
private _host: Container;
private _scripts: IScript[] = [];
constructor(host) {
this._host = host;
}
get host() {
return this._host;
}
/**
* 增加一个脚本
* @param name
* @param options
* @param disabled
*/
add(name, options): IScript {
add(name, options, disabled): IScript {
let def = scriptDefs[name];
if (!def) {
console.warn('script def not exists');
return;
}
let script = new def();
let script: IScript = new def();
script['host'] = this._host;
script['_disabled'] = disabled;
for (let k in options) {
script[k] = options[k];
}
this._scripts.push(script);
script.mounted();
if (this._host && this._host.stage) {
script.awake();
}
return script;
}
......@@ -69,6 +126,9 @@ class ScriptsContainer {
remove(index): IScript {
let script = this._scripts.splice(index, 1)[0];
if (script) {
if (this._host && this._host.stage) {
script.sleep();
}
script.destroy();
}
return script;
......@@ -86,13 +146,39 @@ class ScriptsContainer {
* @param name
*/
get(name): IScript[] {
return this._scripts.filter(script => script.name === name);
return this._scripts.filter(script => script.constructor['name'] === name);
}
/**
* 唤醒
*/
awake() {
for (let script of this._scripts) {
if (!script.disabled) {
script.awake();
}
}
}
/**
* 睡眠
*/
sleep() {
for (let script of this._scripts) {
if (!script.disabled) {
script.sleep();
}
}
}
/**
* 更新脚本时钟
*/
update(t) {
for (let script of this._scripts) {
if (!script.disabled) {
script.update(t);
}
}
}
}
/**
* Created by rockyl on 2019-11-08.
*/
export const ESCAPE_REG_EXP = /\$\{[_a-zA-Z]\w*\}/g;
/**
* Created by rockyl on 2019-11-07.
* Created by rockyl on 2019-11-08.
*/
import {Container} from "../2d/display";
import {Rect, Image, Label} from "./nodes";
const nodeTypeMapping = {
node: 'engine.Container',
rect: 'engine.Rect',
label: 'engine.TextField',
image: 'engine.Image',
node: Container,
rect: Rect,
label: Label,
image: Image,
};
function instantiate(config) {
export function instantiate(config) {
return instantiateView(config);
}
......@@ -28,20 +31,24 @@ function propertyParse(key, node, properties) {
}
function instantiateView(config) {
const {type} = config;
const {type, scripts} = config;
const nodeTypeDef = eval(nodeTypeMapping[type]);
const nodeTypeDef = nodeTypeMapping[type];
if (!nodeTypeDef) {
console.warn('error node type:', type);
return;
}
const {name, uuid, properties, children} = config;
const node = new nodeTypeDef();
const {name, uuid, properties, children} = config;
node.name = name;
node.uuid = uuid;
for (let key in properties) {
propertyParse(key, node, properties);
injectProperties(node, properties);
if (scripts && scripts.length > 0) {
for (let scriptConfig of scripts) {
instantiateScript(node, scriptConfig);
}
}
if (children && children.length > 0) {
......@@ -55,3 +62,14 @@ function instantiateView(config) {
return node;
}
function instantiateScript(node, ScriptConfig) {
const {script: scriptName, properties, disabled} = ScriptConfig;
const script = node.scripts.add(scriptName, properties, disabled);
}
function injectProperties(target, source) {
for (let key in source) {
propertyParse(key, target, source);
}
}
......@@ -11,7 +11,7 @@ module.exports = {
path: __dirname,
filename: "build/[name].js",
libraryTarget: 'umd',
library: 'engine',
library: 'render',
},
module: {
rules: [
......@@ -24,11 +24,11 @@ module.exports = {
},
devtool: 'source-map',
plugins: [
/*new UglifyJSPlugin(
new UglifyJSPlugin(
{ sourceMap: true }
), new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})*/
})
],
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.js']
......
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