Commit a8f6f07e authored by rockyl's avatar rockyl

增加加点拷贝功能

修复过程污染的问题
parent 3f014a42
This diff is collapsed.
This diff is collapsed.
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
<script type="text/javascript" src="../dist/index.js"></script> <script type="text/javascript" src="../dist/index.js"></script>
<div id="game-container" style="line-height:0;font-size:0"></div> <div id="game-container" style="line-height:0;font-size:0"></div>
<script src="scripts/ScriptDemo.js"></script> <script src="scripts/ScriptDemo.js"></script>
<script src="view-data.js"></script> <script src="scripts/ZoomButton.js"></script>
<script src="game-stage.js"></script> <script src="game-stage.js"></script>
......
...@@ -3,5 +3,6 @@ ...@@ -3,5 +3,6 @@
*/ */
engine.registerScriptDef(ScriptDemo); engine.registerScriptDef(ScriptDemo);
engine.registerScriptDef(ZoomButton);
const gameStage = engine.launch(data); engine.launch('http://localhost:63342/VisualEditor/renderingengine/examples/mock/test.json');
This diff is collapsed.
/**
* Created by rockyl on 2019-11-07.
*/
class ZoomButton {
static name = 'ZoomButton';
mounted(){
console.log('mounted', this.duration);
this.host.anchorX = this.host.width / 2;
this.host.anchorY = this.host.height / 2;
this.host.addEventListener(engine.MouseEvent.MOUSE_DOWN, this._onMouseDown, this);
this.host.addEventListener(engine.MouseEvent.MOUSE_UP, this._onMouseUp, this);
}
destroy(){
console.log('destroy');
}
update(t){
//console.log('update', t);
//this.host.rotation = t * 0.1;
}
awake(){
console.log('awake');
}
sleep(){
console.log('sleep');
}
_onMouseDown(e){
this.host.scaleX = this.host.scaleY = 1.1;
}
_onMouseUp(e){
this.host.scaleX = this.host.scaleY = 1;
}
}
...@@ -37,10 +37,12 @@ const data = { ...@@ -37,10 +37,12 @@ const data = {
{ {
name: "button", name: "button",
type: "rect", type: "rect",
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a", uuid: "aaaa",
properties: { properties: {
y: 20,
width: 150, width: 150,
height: 50, height: 50,
horizonCenter: 0,
borderRadius: 10, borderRadius: 10,
fillColor: "#27ADB8", fillColor: "#27ADB8",
mouseChildren: false, mouseChildren: false,
...@@ -49,7 +51,7 @@ const data = { ...@@ -49,7 +51,7 @@ const data = {
{ {
name: "label", name: "label",
type: "label", type: "label",
uuid: "f97bbf76-6923-4669-b5a3-e6382753e49a", uuid: "bbbb",
properties: { properties: {
width: '100%', width: '100%',
height: '100%', height: '100%',
...@@ -76,6 +78,15 @@ const data = { ...@@ -76,6 +78,15 @@ const data = {
] ]
} }
}, },
scripts: [
{
script: 'ZoomButton',
disabled: false,
properties: {
duration: 1000,
},
}
],
}, },
/*{ /*{
name: "img", name: "img",
...@@ -326,6 +337,7 @@ const data = { ...@@ -326,6 +337,7 @@ const data = {
meta: 'test', meta: 'test',
props: { props: {
text: 'hello', text: 'hello',
node: 'node://bbbb'
}, },
output: { output: {
success: [], success: [],
...@@ -367,6 +379,7 @@ const data = { ...@@ -367,6 +379,7 @@ const data = {
node: {alias: '节点', type: 'node',}, node: {alias: '节点', type: 'node',},
}, },
output: ['success', 'failed'], output: ['success', 'failed'],
//script: "console.log('test');let b = target.clone();b.y = global.by = (global.by || 0) + 80; target.parent.addChild(b);resolve({type: 'success', payload: args})",
script: "console.log('test');resolve({type: 'success', payload: args})", script: "console.log('test');resolve({type: 'success', payload: args})",
}, },
{ {
...@@ -458,3 +471,5 @@ resolve({type: result ? 'equal' : 'unequal'}); ...@@ -458,3 +471,5 @@ resolve({type: result ? 'equal' : 'unequal'});
}, },
], ],
}; };
console.log(JSON.stringify(data));
import { DisplayObject } from './DisplayObject'; import {DisplayObject} from './DisplayObject';
import { Rectangle } from "../math/Rectangle"; import {Rectangle} from "../math/Rectangle";
import { Point } from '../math'; import {Point} from '../math';
import CanvasRenderer from '../renderers/CanvasRenderer'; import CanvasRenderer from '../renderers/CanvasRenderer';
import { Event } from "../events/Event" import {Event} from "../events/Event"
import { WebglRenderer } from '../renderers/WebglRenderer'; import {WebglRenderer} from '../renderers/WebglRenderer';
import { applyAutoAdjust } from "../../zeroing/decorators/auto-adjust"; import {applyAutoAdjust} from "../../zeroing/decorators/auto-adjust";
import { applyScript } from "../../zeroing/decorators/scripts"; import {applyScript} from "../../zeroing/decorators/scripts";
import { applyEvents } from "../../zeroing/decorators/events"; import {applyEvents} from "../../zeroing/decorators/events";
import {afterConstructor} from "../../zeroing/decorators/after-constructor";
/** /**
* 容器类 * 容器类
* @class * @class
* @extends DisplayObject * @extends DisplayObject
*/ */
@afterConstructor
@applyAutoAdjust @applyAutoAdjust
@applyScript @applyScript
@applyEvents @applyEvents
...@@ -40,20 +42,10 @@ export default class Container extends DisplayObject { ...@@ -40,20 +42,10 @@ export default class Container extends DisplayObject {
super(); super();
this._instanceType = "Container"; this._instanceType = "Container";
this.children = []; this.children = [];
this.applyAutoAdjust(); this.afterConstructor();
this.applyScripts();
this.applyEvents();
} }
applyAutoAdjust() { afterConstructor() {
}
applyScripts() {
}
applyEvents() {
} }
...@@ -514,7 +506,8 @@ export default class Container extends DisplayObject { ...@@ -514,7 +506,8 @@ export default class Container extends DisplayObject {
let len = this.children.length; let len = this.children.length;
for (let i = len - 1; i >= 0; i--) { for (let i = len - 1; i >= 0; i--) {
const child = this.children[i]; const child = this.children[i];
/*if (child.visible)*/ child.update(deltaTime); /*if (child.visible)*/
child.update(deltaTime);
} }
} }
......
...@@ -4,17 +4,19 @@ ...@@ -4,17 +4,19 @@
* 过程 * 过程
*/ */
import {VM} from "./VM"; import {VM} from "./VM";
import {linkedFlag} from "../utils"; import {linkedFlag, nodeScheme, objClone} from "../utils";
import {findNodeByUUID} from "../node-utils";
const log = true; const log = false;
export class Process { export class Process {
private _heap = {};
private _config; private _config;
private _parent: Process; private _parent: Process;
private _vm: VM; private _vm: VM;
private _sequence; private _sequence;
private _meta; private _meta;
private _target;
private _originProps;
constructor() { constructor() {
...@@ -28,20 +30,21 @@ export class Process { ...@@ -28,20 +30,21 @@ export class Process {
return this._parent; return this._parent;
} }
get heap() {
return this._heap;
}
get sequence() { get sequence() {
return this._sequence; return this._sequence;
} }
init(context) { init(context) {
const {vm, parent, sequence, id} = context; const {vm, parent, sequence, id, target} = context;
this._vm = vm; this._vm = vm;
this._parent = parent; this._parent = parent;
this._config = sequence[id]; this._config = sequence[id];
this._sequence = sequence; this._sequence = sequence;
this._target = target;
if (!this._originProps && this._config.props) {
this._originProps = objClone(this._config.props)
}
} }
async execute(args) { async execute(args) {
...@@ -73,9 +76,6 @@ export class Process { ...@@ -73,9 +76,6 @@ export class Process {
} else { } else {
const scriptResult = await this._executeMetaScript('', args, metaConfig); const scriptResult = await this._executeMetaScript('', args, metaConfig);
const subProcessResult = await this._executeSubProcess(scriptResult.type, scriptResult.payload); const subProcessResult = await this._executeSubProcess(scriptResult.type, scriptResult.payload);
if (!subProcessResult) {
console.log();
}
result = await this._executeNextProcess(subProcessResult.type, subProcessResult.payload); result = await this._executeNextProcess(subProcessResult.type, subProcessResult.payload);
} }
...@@ -91,9 +91,9 @@ export class Process { ...@@ -91,9 +91,9 @@ export class Process {
let metaConfig = this._meta; let metaConfig = this._meta;
if (metaConfig) { if (metaConfig) {
if (metaConfig.script) { if (metaConfig.script) {
let func = new Function('args', 'props', 'global', warpAsyncScript(metaConfig.script)); let func = new Function('args', 'props', 'target', 'global', warpAsyncScript(metaConfig.script));
this.updateProps(); this.updateProps();
result = await func(payload, this._config.props, this._vm.getGlobalContext()); result = await func(payload, this._config.props, this._target, this._vm.getGlobalContext());
} }
} else { } else {
console.warn(`process meta [${meta}] not found`) console.warn(`process meta [${meta}] not found`)
...@@ -110,7 +110,7 @@ export class Process { ...@@ -110,7 +110,7 @@ export class Process {
if (this._meta) { if (this._meta) {
let {sub, subEntry} = this._meta; let {sub, subEntry} = this._meta;
if (sub) { if (sub) {
result = await this._vm.executeProcess(sub, subEntry, this, payload); result = await this._vm.executeProcess(objClone(sub), subEntry, this, payload);
} }
} }
...@@ -162,14 +162,18 @@ export class Process { ...@@ -162,14 +162,18 @@ export class Process {
* 更新props * 更新props
*/ */
updateProps() { updateProps() {
let props = this._config.props; if (this._originProps) {
for (let key in props) { let props = this._config.props;
let value = props[key]; for (let key in props) {
if (value === linkedFlag) { let value = this._originProps[key];
if (this._parent) { if (value === linkedFlag) {
let pProp = this._parent.getProps(key); if (this._parent) {
if (pProp !== undefined) { props[key] = this._parent.getProps(key);
props[key] = pProp; }
} else if (value.indexOf(nodeScheme) === 0) {
let uuid = value.replace(nodeScheme, '');
if (uuid) {
props[key] = findNodeByUUID(this._vm.getGlobalContext().gameStage, uuid);
} }
} }
} }
......
...@@ -8,12 +8,14 @@ import {arrayFind} from "../utils"; ...@@ -8,12 +8,14 @@ import {arrayFind} from "../utils";
export class VM { export class VM {
_processMetaLibs; _processMetaLibs;
_globalContext; _globalContext;
_target;
setup(context) { setup(context) {
const {processMetaLibs, globalContext} = context; const {processMetaLibs, globalContext, target} = context;
this._processMetaLibs = processMetaLibs; this._processMetaLibs = processMetaLibs;
this._globalContext = globalContext; this._globalContext = globalContext;
this._target = target;
} }
async executeProcess(sequence, id, parentProcess, args) { async executeProcess(sequence, id, parentProcess, args) {
...@@ -23,6 +25,7 @@ export class VM { ...@@ -23,6 +25,7 @@ export class VM {
id, id,
vm: this, vm: this,
parent: parentProcess, parent: parentProcess,
target: this._target,
}); });
return await process.execute(args); return await process.execute(args);
......
...@@ -7,12 +7,20 @@ import {VM} from "./VM"; ...@@ -7,12 +7,20 @@ import {VM} from "./VM";
let processMetaLibs = []; let processMetaLibs = [];
let globalContext = {}; let globalContext = {};
/**
* 设置过程库
* @param metaContexts
*/
export function setProcessMetaLibs(...metaContexts) { export function setProcessMetaLibs(...metaContexts) {
for (let context of metaContexts) { for (let context of metaContexts) {
processMetaLibs.push(context); processMetaLibs.push(context);
} }
} }
/**
* 设置去全局上下文
* @param context
*/
export function setGlobalContext(context) { export function setGlobalContext(context) {
globalContext = context; globalContext = context;
for (let key in context) { for (let key in context) {
...@@ -20,11 +28,19 @@ export function setGlobalContext(context) { ...@@ -20,11 +28,19 @@ export function setGlobalContext(context) {
} }
} }
export function executeBehavior(sequence, subEntry = 'main', args?) { /**
* 执行行为
* @param sequence
* @param subEntry
* @param target
* @param args
*/
export function executeBehavior(sequence, subEntry = 'main', target, args?) {
const vm = new VM(); const vm = new VM();
vm.setup({ vm.setup({
processMetaLibs, processMetaLibs,
globalContext, globalContext,
target,
}); });
vm.executeProcess(sequence, subEntry, null, args) vm.executeProcess(sequence, subEntry, null, args)
.then(result => { .then(result => {
......
/**
* Created by rockyl on 2019-11-08.
*/
import {propertyParse} from "../utils";
const cloneFields = [
/*node*/ 'x', 'y', 'width', 'height', 'rotation', 'alpha', 'scaleX', 'scaleY', 'visible',
/*label*/ 'text', 'color', 'size', 'textAlign', 'verticalAlign',
/*image*/ 'source',
/*rect*/ 'fillColor', 'strokeColor', 'strokeWidth',
/*autoadjust*/ 'left', 'top', 'right', 'bottom',
];
/**
* 构造方法后执行
* @param ctor
*/
export function afterConstructor(ctor: Function) {
ctor.prototype.afterConstructor = function () {
this.applyAutoAdjust();
this.applyScripts();
this.applyEvents();
};
ctor.prototype.clone = function () {
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);
}
for(let child of this.children){
let childCopy = child.clone();
target.addChild(childCopy);
}
return target;
};
}
...@@ -71,6 +71,12 @@ class AdjustProxy { ...@@ -71,6 +71,12 @@ class AdjustProxy {
this._host.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame); this._host.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
} }
setFrom(adjustProxy: AdjustProxy) {
for (let k in adjustProxy.data) {
this.data[k] = adjustProxy.data[k];
}
}
private onResize(e) { private onResize(e) {
this._sizeDirty = true; this._sizeDirty = true;
} }
......
...@@ -42,7 +42,7 @@ class EventsProxy extends HashObject { ...@@ -42,7 +42,7 @@ class EventsProxy extends HashObject {
if (eventConfig) { if (eventConfig) {
executeBehavior({ executeBehavior({
main: eventConfig.behaviors[0], main: eventConfig.behaviors[0],
}, 'main') }, 'main', e.target);
} }
} }
} }
......
/** /**
* Created by rockyl on 2019-11-07. * Created by rockyl on 2019-11-07.
*/ */
import {Loader} from "../..";
import {globalLoader} from "../../2d/loader/Loader";
let assetsConfig; let assetsConfig;
...@@ -17,8 +18,6 @@ const loaderMapping = { ...@@ -17,8 +18,6 @@ const loaderMapping = {
'.sht': 'Sheet', '.sht': 'Sheet',
}; };
const loader = new Loader();
/** /**
* 加载素材 * 加载素材
*/ */
...@@ -33,7 +32,7 @@ export function loadAssets(config, onProgress?, onComplete?) { ...@@ -33,7 +32,7 @@ export function loadAssets(config, onProgress?, onComplete?) {
assetsConfig.map(assetConfig => { assetsConfig.map(assetConfig => {
return new Promise((resolve) => { return new Promise((resolve) => {
const loadFunc = loaderMapping[assetConfig.ext] || 'Raw'; const loadFunc = loaderMapping[assetConfig.ext] || 'Raw';
loader['load' + loadFunc](function (result, payload) { globalLoader['load' + loadFunc](function (result, payload) {
if (result) { if (result) {
loaded++; loaded++;
onProgress && onProgress(loaded, total); onProgress && onProgress(loaded, total);
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
import {Container} from "../../2d/display"; import {Container} from "../../2d/display";
import {Rect, Image, Label} from "./nodes"; import {Rect, Image, Label} from "./nodes";
import {propertyParse} from "../utils";
const nodeTypeMapping = { const nodeTypeMapping = {
node: Container, node: Container,
...@@ -16,20 +17,6 @@ export function instantiate(config) { ...@@ -16,20 +17,6 @@ export function instantiate(config) {
return instantiateView(config); return instantiateView(config);
} }
const percentKeys = ['width', 'height'];
function propertyParse(key, node, properties) {
let value = properties[key];
let targetKey = key;
if (percentKeys.indexOf(key) >= 0) {
if (typeof value === 'string') {
targetKey = 'percent' + key[0].toUpperCase() + key.substr(1);
value = parseInt(value);
}
}
node[targetKey] = value;
}
function instantiateView(config) { function instantiateView(config) {
const {type, scripts} = config; const {type, scripts} = config;
...@@ -43,6 +30,7 @@ function instantiateView(config) { ...@@ -43,6 +30,7 @@ function instantiateView(config) {
const {name, uuid, properties, children, events} = config; const {name, uuid, properties, children, events} = config;
node.name = name; node.name = name;
node.uuid = uuid; node.uuid = uuid;
node.__originConfig = config;
injectProperties(node, properties); injectProperties(node, properties);
if (scripts && scripts.length > 0) { if (scripts && scripts.length > 0) {
...@@ -68,7 +56,7 @@ function instantiateView(config) { ...@@ -68,7 +56,7 @@ function instantiateView(config) {
function instantiateScript(node, ScriptConfig) { function instantiateScript(node, ScriptConfig) {
const {script: scriptName, properties, disabled} = ScriptConfig; const {script: scriptName, properties, disabled} = ScriptConfig;
const script = node.scripts.add(scriptName, properties, disabled); const script = node.scriptsProxy.add(scriptName, properties, disabled);
} }
function injectProperties(target, source) { function injectProperties(target, source) {
......
...@@ -3,31 +3,51 @@ ...@@ -3,31 +3,51 @@
*/ */
import {Stage} from "../2d/display"; import {Stage} from "../2d/display";
import { RENDERER_TYPE, StageScaleMode} from ".."; import {RENDERER_TYPE, StageScaleMode} from "..";
import {GameStage} from "./game-warpper"; import {GameStage} from "./game-warpper";
import {setGlobalContext} from "./behavior-runtime"; import {setGlobalContext} from "./behavior-runtime";
import {globalLoader} from "../2d/loader/Loader";
export function launch(config, onAssetsProgress, onAssetsComplete) { export function launch(url, onAssetsProgress, onAssetsComplete) {
const {containerID, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.launchOptions; return new Promise((resolve, reject) => {
let stage = window['stage'] = new Stage( globalLoader.loadJson((s, payload) => {
containerID || "game-container", if(s){
designWidth || 750, resolve(payload);
designHeight || 1334, }else{
frameRate || 60, reject(payload);
scaleMode || StageScaleMode.FIXED_WIDTH, }
rendererType || RENDERER_TYPE.WEBGL }, url);
); }).then(
Stage.flushAll(); config=>{
return launchWithConfig(config, onAssetsProgress, onAssetsComplete);
}
)
}
export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) {
return new Promise(resolve => {
const {containerID, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.launchOptions;
let stage = window['stage'] = new Stage(
containerID || "game-container",
designWidth || 750,
designHeight || 1334,
frameRate || 60,
scaleMode || StageScaleMode.FIXED_WIDTH,
rendererType || RENDERER_TYPE.WEBGL
);
Stage.flushAll();
let gameStage = new GameStage(stage); let gameStage = new GameStage(stage);
setGlobalContext({ setGlobalContext({
gameStage gameStage
}); });
stage.addChild(gameStage); stage.addChild(gameStage);
setTimeout(() => { setTimeout(() => {
gameStage.launch(config, onAssetsProgress, onAssetsComplete); gameStage.launch(config, onAssetsProgress, onAssetsComplete);
}); });
return gameStage; resolve(gameStage);
})
} }
/**
* Created by rockyl on 2019-11-13.
*/
export function findNodeByUUID(node, uuid) {
if (node.uuid === uuid) {
return node;
}
for (let child of node.children) {
let target = findNodeByUUID(child, uuid);
if (target) {
return target;
}
}
}
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
export const ESCAPE_REG_EXP = /\$\{[_a-zA-Z]\w*\}/g; export const ESCAPE_REG_EXP = /\$\{[_a-zA-Z]\w*\}/g;
export const linkedFlag = '$_linked_$'; export const linkedFlag = '$_linked_$';
export const nodeScheme = 'node://';
export function arrayFind(arr, callback) { export function arrayFind(arr, callback) {
for (let i = 0, li = arr.length; i < li; i++) { for (let i = 0, li = arr.length; i < li; i++) {
...@@ -14,3 +15,23 @@ export function arrayFind(arr, callback) { ...@@ -14,3 +15,23 @@ export function arrayFind(arr, callback) {
} }
} }
} }
export function objClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
const percentKeys = ['width', 'height'];
export function propertyParse(key, node, properties) {
let value = properties[key];
let targetKey = key;
if (percentKeys.indexOf(key) >= 0) {
if (typeof value === 'string') {
if(value[value.length-1] === '%'){
targetKey = 'percent' + key[0].toUpperCase() + key.substr(1);
}
value = parseInt(value);
}
}
node[targetKey] = value;
}
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