forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_system.js
More file actions
527 lines (459 loc) · 20.8 KB
/
script_system.js
File metadata and controls
527 lines (459 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
pc.extend(pc.fw, function () {
var INITIALIZE = "initialize";
var POST_INITIALIZE = "postInitialize";
var UPDATE = "update";
var POST_UPDATE = "postUpdate";
var FIXED_UPDATE = "fixedUpdate";
var TOOLS_UPDATE = "toolsUpdate";
var ON_ENABLE = 'onEnable';
var ON_DISABLE = 'onDisable';
/**
* @name pc.fw.ScriptComponentSystem
* @constructor Create a new ScriptComponentSystem
* @class Allows scripts to be attached to an Entity and executed
* @param {Object} context
* @extends pc.fw.ComponentSystem
*/
var ScriptComponentSystem = function ScriptComponentSystem(context) {
this.id = 'script';
this.description = "Allows the Entity to run JavaScript fragments to implement custom behavior.";
context.systems.add(this.id, this);
this.ComponentType = pc.fw.ScriptComponent;
this.DataType = pc.fw.ScriptComponentData;
this.schema = [{
name: 'enabled',
displayName: 'Enabled',
description: 'Disabled components are not updated',
type: 'boolean',
defaultValue: true
},{
name: "scripts",
displayName: "URLs",
description: "Attach scripts to this Entity",
type: "script",
defaultValue: []
}, {
name: 'instances',
exposed: false
}, {
name: 'runInTools',
description: 'Allows scripts to be loaded and executed while in the tools',
defaultValue: false,
exposed: false
}];
this.exposeProperties();
// arrays to cache script instances for fast iteration
this.instancesWithUpdate = [];
this.instancesWithFixedUpdate = [];
this.instancesWithPostUpdate = [];
this.instancesWithToolsUpdate = [];
this.on('beforeremove', this.onBeforeRemove, this);
pc.fw.ComponentSystem.on(INITIALIZE, this.onInitialize, this);
pc.fw.ComponentSystem.on(POST_INITIALIZE, this.onPostInitialize, this);
pc.fw.ComponentSystem.on(UPDATE, this.onUpdate, this);
pc.fw.ComponentSystem.on(FIXED_UPDATE, this.onFixedUpdate, this);
pc.fw.ComponentSystem.on(POST_UPDATE, this.onPostUpdate, this);
pc.fw.ComponentSystem.on(TOOLS_UPDATE, this.onToolsUpdate, this);
};
ScriptComponentSystem = pc.inherits(ScriptComponentSystem, pc.fw.ComponentSystem);
pc.extend(ScriptComponentSystem.prototype, {
initializeComponentData: function (component, data, properties) {
properties = ['runInTools', 'enabled', 'scripts'];
ScriptComponentSystem._super.initializeComponentData.call(this, component, data, properties);
},
cloneComponent: function (entity, clone) {
// overridden to make sure urls list is duplicated
var src = this.dataStore[entity.getGuid()];
var data = {
runInTools: src.data.runInTools,
scripts: pc.extend([], src.data.scripts),
enabled: src.data.enabled
};
return this.addComponent(clone, data);
},
/**
* @private
* @name pc.fw.ScriptComponentSystem#onBeforeRemove
* @description Handler for 'beforeremove' event which is fired when a script component is about to be removed from an entity;
* @param {pc.fw.Entity} entity The entity that the component will be removed from
* @param {pc.fw.Component} component The component about to be removed
*/
onBeforeRemove: function (entity, component) {
// if the script component is enabled
// call onDisable on all its instances first
if (component.enabled) {
this._disableScriptComponent(component);
}
// then call destroy on all the script instances
this._destroyScriptComponent(component);
},
/**
* @function
* @private
* @name pc.fw.ScriptComponentSystem#onInitialize
* @description Handler for the 'initialize' event which is fired immediately after the Entity hierarchy is loaded, but before the first update loop
* @param {pc.fw.Entity} root The root of the hierarchy to initialize.
*/
onInitialize: function (root) {
this._registerInstances(root);
if (root.enabled) {
if (root.script && root.script.enabled) {
this._initializeScriptComponent(root.script);
}
var children = root.getChildren();
var i, len = children.length;
for (i = 0; i < len; i++) {
if (children[i] instanceof pc.fw.Entity) {
this.onInitialize(children[i]);
}
}
}
},
/**
* @function
* @private
* @name pc.fw.ScriptComponentSystem#onPostInitialize
* @description Handler for the 'postInitialize' event which is fired immediately after the 'initialize' event and before the first update loop
* @param {pc.fw.Entity} root The root of the hierarchy to initialize.
*/
onPostInitialize: function (root) {
if (root.enabled) {
if (root.script && root.script.enabled) {
this._postInitializeScriptComponent(root.script);
}
var children = root.getChildren();
var i, len = children.length;
for (i = 0; i < len; i++) {
if (children[i] instanceof pc.fw.Entity) {
this.onPostInitialize(children[i]);
}
};
}
},
_callInstancesMethod: function (script, method) {
var instances = script.data.instances;
for (var name in instances) {
if (instances.hasOwnProperty(name)) {
var instance = instances[name].instance;
if (instance[method]) {
instance[method].call(instance);
}
}
}
},
_initializeScriptComponent: function (script) {
this._callInstancesMethod(script, INITIALIZE);
script.data.initialized = true;
// check again if the script and the entity are enabled
// in case they got disabled during initialize
if (script.enabled && script.entity.enabled) {
this._enableScriptComponent(script);
}
},
_enableScriptComponent: function (script) {
this._callInstancesMethod(script, ON_ENABLE);
},
_disableScriptComponent: function (script) {
this._callInstancesMethod(script, ON_DISABLE);
},
_destroyScriptComponent: function (script) {
var index;
var instances = script.data.instances;
for (var name in instances) {
if (instances.hasOwnProperty(name)) {
var instance = instances[name].instance;
if(instance.destroy) {
instance.destroy();
}
if (instance.update) {
index = this.instancesWithUpdate.indexOf(instance);
if (index >= 0) {
this.instancesWithUpdate.splice(index, 1);
}
}
if (instance.fixedUpdate) {
index = this.instancesWithFixedUpdate.indexOf(instance);
if (index >= 0) {
this.instancesWithFixedUpdate.splice(index, 1);
}
}
if (instance.postUpdate) {
index = this.instancesWithPostUpdate.indexOf(instance);
if (index >= 0) {
this.instancesWithPostUpdate.splice(index, 1);
}
}
if (instance.toolsUpdate) {
index = this.instancesWithToolsUpdate.indexOf(instance);
if (index >= 0) {
this.instancesWithToolsUpdate.splice(index, 1);
}
}
if (script.instances[name].instance === script[name]) {
delete script[name];
}
delete script.instances[name];
}
}
},
_postInitializeScriptComponent: function (script) {
this._callInstancesMethod(script, POST_INITIALIZE);
script.data.postInitialized = true;
},
_updateInstances: function (method, updateList, dt) {
var item;
for (var i=0, len=updateList.length; i<len; i++) {
item = updateList[i];
if (item && item.entity.script.enabled && item.entity.enabled) {
item[method].call(item, dt);
}
}
},
/**
* @private
* @function
* @name pc.fw.ScriptComponentSystem#onUpdate
* @description Handler for the 'update' event which is fired every frame
* @param {Number} dt The time delta since the last update in seconds
*/
onUpdate: function (dt) {
this._updateInstances(UPDATE, this.instancesWithUpdate, dt);
},
/**
* @private
* @function
* @name pc.fw.ScriptComponentSystem#onFixedUpdate
* @description Handler for the 'fixedUpdate' event which is fired every frame just before the 'update' event but with a fixed timestep
* @param {Number} dt A fixed timestep of 1/60 seconds
*/
onFixedUpdate: function (dt) {
this._updateInstances(FIXED_UPDATE, this.instancesWithFixedUpdate, dt);
},
/**
* @private
* @function
* @name pc.fw.ScriptComponentSystem#onPostUpdate
* @description Handler for the 'postUpdate' event which is fired every frame just after the 'update' event
* @param {Number} dt The time delta since the last update in seconds
*/
onPostUpdate: function (dt) {
this._updateInstances(POST_UPDATE, this.instancesWithPostUpdate, dt);
},
onToolsUpdate: function (dt) {
this._updateInstances(TOOLS_UPDATE, this.instancesWithToolsUpdate, dt);
},
/**
* @function
* @name pc.fw.ScriptComponentSystem#broadcast
* @description Send a message to all Script Objects with a specific name.
* Sending a message is similar to calling a method on a Script Object, except that the message will not fail if the method isn't present
* @param {String} name The name of the script to send the message to
* @param {String} functionName The name of the functio nto call on the Script Object
* @example
* // Call doDamage(10) on all 'enemy' scripts
* entityEntity.script.broadcast('enemy', 'doDamage', 10);
*/
broadcast: function (name, functionName) {
var args = pc.makeArray(arguments).slice(2);
var id, data, fn;
var dataStore = this.store;
// var results = [];
for (id in dataStore) {
if (dataStore.hasOwnProperty(id)) {
data = dataStore[id].data;
if (data.instances[name]) {
fn = data.instances[name].instance[functionName];
if(fn) {
fn.apply(data.instances[name].instance, args);
}
}
}
}
},
/**
* @private
* @function
* @name pc.fw.ScriptComponentSystem#_preRegisterInstance
* @description Internal method used to store a instance of a script created while loading. Instances are preregistered while loadeding
* and then all registered at the same time once loading is complete
* @param {pc.fw.Entity} entity The Entity the script instance is attached to
* @param {String} url The url of the script
* @param {String} name The name of the script
* @param {Object} instance The instance of the Script Object
*/
_preRegisterInstance: function (entity, url, name, instance) {
if (entity.script) {
entity.script.data._instances = entity.script.data._instances || {};
if (entity.script.data._instances[name]) {
throw Error(pc.string.format("Script name collision '{0}'. Scripts from '{1}' and '{2}' {{3}}", name, url, entity.script.data._instances[name].url, entity.getGuid()));
}
entity.script.data._instances[name] = {
url: url,
name: name,
instance: instance
};
}
},
/**
* @private
* @function
* @name pc.fw.ScriptComponentSystem#_registerInstance
* @description Get all preregistered instances for an entity and 'register' then. This means storing the instance in the ComponentData
* and binding events for the update, fixedUpdate, postUpdate and toolsUpdate methods.
* This function is recursive and calls itself for the complete hierarchy down from the supplied Entity
* @param {pc.fw.Entity} entity The Entity the instances are attached to
*/
_registerInstances: function (entity) {
var preRegistered, instance, instanceName;
if (entity.script) {
if (entity.script.data._instances) {
entity.script.instances = entity.script.data._instances;
for (instanceName in entity.script.instances) {
preRegistered = entity.script.instances[instanceName];
instance = preRegistered.instance;
pc.events.attach(instance);
if (instance.update) {
this.instancesWithUpdate.push(instance);
}
if (instance.fixedUpdate) {
this.instancesWithFixedUpdate.push(instance);
}
if (instance.postUpdate) {
this.instancesWithPostUpdate.push(instance);
}
if (instance.toolsUpdate) {
this.instancesWithToolsUpdate.push(instance);
}
if (entity.script.scripts) {
this._createAccessors(entity, preRegistered);
}
// Make instance accessible from the script component of the Entity
if (entity.script[instanceName]) {
throw Error(pc.string.format("Script with name '{0}' is already attached to Script Component", instanceName));
} else {
entity.script[instanceName] = instance;
}
}
// Remove temp storage
delete entity.script.data._instances;
}
}
var children = entity.getChildren();
var i, len = children.length;
for (i = 0; i < len; i++) {
if (children[i] instanceof pc.fw.Entity) {
this._registerInstances(children[i]);
}
}
},
_createAccessors: function (entity, instance) {
var self = this;
var i;
var len = entity.script.scripts.length;
var url = instance.url;
for (i=0; i<len; i++) {
var script = entity.script.scripts[i];
if (script.url === url) {
var attributes = script.attributes;
if (script.name && attributes) {
attributes.forEach(function (attribute, index) {
self._createAccessor(attribute, instance);
});
entity.script.data.attributes[script.name] = pc.extend([], attributes);
}
break;
}
}
},
_createAccessor: function (attribute, instance) {
var self = this;
self._convertAttributeValue(attribute);
Object.defineProperty(instance.instance, attribute.name, {
get: function () {
return attribute.value;
},
set: function (value) {
var oldValue = attribute.value;
attribute.value = value;
self._convertAttributeValue(attribute);
instance.instance.fire("set", attribute.name, oldValue, attribute.value);
},
configurable: true
});
},
_updateAccessors: function (entity, instance) {
var self = this;
var i, k, h;
var len = entity.script.scripts.length;
var url = instance.url;
var scriptComponent, script, name, attributes;
var removedAttributes;
var previousAttributes;
var oldAttribute, newAttribute;
for (i=0; i<len; i++) {
scriptComponent = entity.script;
script = scriptComponent.scripts[i];
if (script.url === url) {
name = script.name;
attributes = script.attributes;
if (name) {
if (attributes) {
// create / update attribute accessors
attributes.forEach(function (attribute, index) {
self._createAccessor(attribute, instance);
});
}
// delete accessors for attributes that no longer exist
// and fire onAttributeChange when an attribute value changed
previousAttributes = scriptComponent.data.attributes[name];
if (previousAttributes) {
k = previousAttributes.length;
while(k--) {
oldAttribute = previousAttributes[k];
newAttribute = null;
h = attributes.length;
while (h--) {
if (oldAttribute.name === attributes[h].name) {
newAttribute = attributes[h];
break;
}
}
if (!newAttribute) {
delete instance.instance[oldAttribute.name];
} else {
if (oldAttribute.value !== newAttribute.value) {
if (instance.instance.onAttributeChanged) {
instance.instance.onAttributeChanged(oldAttribute.name, oldAttribute.value, newAttribute.value);
}
}
}
}
}
if (attributes) {
scriptComponent.data.attributes[name] = pc.extend([], attributes);
} else {
delete scriptComponent.data.attributes[name];
}
}
break;
}
}
},
_convertAttributeValue: function (attribute) {
if (attribute.type === 'rgb' || attribute.type === 'rgba') {
if (pc.type(attribute.value) === 'array') {
attribute.value = attribute.value.length === 3 ?
new pc.Color(attribute.value[0], attribute.value[1], attribute.value[2]) :
new pc.Color(attribute.value[0], attribute.value[1], attribute.value[2], attribute.value[3]);
}
} else if (attribute.type === 'vector') {
if (pc.type(attribute.value) === 'array') {
attribute.value = new pc.Vec3(attribute.value[0], attribute.value[1], attribute.value[2]);
}
}
}
});
return {
ScriptComponentSystem: ScriptComponentSystem
};
}());