forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
373 lines (330 loc) · 12 KB
/
Copy pathscript.js
File metadata and controls
373 lines (330 loc) · 12 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
import { Debug } from '../..//core/debug.js';
import { EventHandler } from '../../core/event-handler.js';
import { SCRIPT_INITIALIZE, SCRIPT_POST_INITIALIZE } from './constants.js';
/**
* @import { AppBase } from '../app-base.js'
* @import { Entity } from '../entity.js'
*/
/**
* The `Script` class is the fundamental base class for all scripts within PlayCanvas. It provides
* the minimal interface required for a script to be compatible with both the Engine and the
* Editor.
*
* At its core, a script is simply a collection of methods that are called at various points in the
* Engine's lifecycle. These methods are:
*
* - `Script#initialize` - Called once when the script is initialized.
* - `Script#postInitialize` - Called once after all scripts have been initialized.
* - `Script#update` - Called every frame, if the script is enabled.
* - `Script#postUpdate` - Called every frame, after all scripts have been updated.
* - `Script#swap` - Called when a script is redefined.
*
* These methods are entirely optional, but provide a useful way to manage the lifecycle of a
* script and perform any necessary setup and cleanup.
*
* Below is a simple example of a script that rotates an entity every frame.
* @example
* ```javascript
* import { Script } from 'playcanvas';
*
* export class Rotator extends Script {
* static scriptName = 'rotator';
*
* update(dt) {
* this.entity.rotateLocal(0, 1, 0);
* }
* }
* ```
*
* When this script is attached to an entity, the update will be called every frame, slowly
* rotating the entity around the Y-axis.
*
* For more information on how to create scripts, see the [Scripting Overview](https://developer.playcanvas.com/user-manual/scripting/).
*
* @category Script
*/
export class Script extends EventHandler {
/**
* Fired when a script instance becomes enabled.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('enable', () => {
* // Script Instance is now enabled
* });
* }
* };
*/
static EVENT_ENABLE = 'enable';
/**
* Fired when a script instance becomes disabled.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('disable', () => {
* // Script Instance is now disabled
* });
* }
* };
*/
static EVENT_DISABLE = 'disable';
/**
* Fired when a script instance changes state to enabled or disabled. The handler is passed a
* boolean parameter that states whether the script instance is now enabled or disabled.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('state', (enabled) => {
* console.log(`Script Instance is now ${enabled ? 'enabled' : 'disabled'}`);
* });
* }
* };
*/
static EVENT_STATE = 'state';
/**
* Fired when a script instance is destroyed and removed from component.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('destroy', () => {
* // no longer part of the entity
* // this is a good place to clean up allocated resources used by the script
* });
* }
* };
*/
static EVENT_DESTROY = 'destroy';
/**
* Fired when script attributes have changed. This event is available in two forms. They are as
* follows:
*
* 1. `attr` - Fired for any attribute change. The handler is passed the name of the attribute
* that changed, the value of the attribute before the change and the value of the attribute
* after the change.
* 2. `attr:[name]` - Fired for a specific attribute change. The handler is passed the value of
* the attribute before the change and the value of the attribute after the change.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('attr', (name, newValue, oldValue) => {
* console.log(`Attribute '${name}' changed from '${oldValue}' to '${newValue}'`);
* });
* }
* };
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('attr:speed', (newValue, oldValue) => {
* console.log(`Attribute 'speed' changed from '${oldValue}' to '${newValue}'`);
* });
* }
* };
*/
static EVENT_ATTR = 'attr';
/**
* Fired when a script instance had an exception. The script instance will be automatically
* disabled. The handler is passed an Error object containing the details of the
* exception and the name of the method that threw the exception.
*
* @event
* @example
* export class PlayerController extends Script {
* static scriptName = 'playerController';
* initialize() {
* this.on('error', (err, method) => {
* // caught an exception
* console.log(err.stack);
* });
* }
* };
*/
static EVENT_ERROR = 'error';
/**
* The {@link AppBase} that the instance of this script belongs to.
*
* @type {AppBase}
*/
app;
/**
* The {@link Entity} that the instance of this script belongs to.
*
* @type {Entity}
*/
entity;
/** @private */
_enabled;
/** @private */
_enabledOld;
/** @private */
_initialized;
/** @private */
_postInitialized;
/** @private */
__destroyed;
/** @private */
__scriptType;
/**
* The order in the script component that the methods of this script instance will run
* relative to other script instances in the component.
*
* @type {number}
* @private
*/
__executionOrder;
/**
* Create a new Script instance.
*
* @param {object} args - The input arguments object.
* @param {AppBase} args.app - The {@link AppBase} that is running the script.
* @param {Entity} args.entity - The {@link Entity} that the script is attached to.
*/
constructor(args) {
super();
this.initScript(args);
}
/**
* True if the instance of this script is in running state. False when script is not running,
* because the Entity or any of its parents are disabled or the {@link ScriptComponent} is
* disabled or the Script Instance is disabled. When disabled, no update methods will be called
* on each tick. `initialize` and `postInitialize` methods will run once when the script
* instance is in the `enabled` state during an app tick.
*
* @type {boolean}
*/
set enabled(value) {
this._enabled = !!value;
if (this.enabled === this._enabledOld) return;
this._enabledOld = this.enabled;
this.fire(this.enabled ? 'enable' : 'disable');
this.fire('state', this.enabled);
// initialize script if not initialized yet and script is enabled
if (!this._initialized && this.enabled) {
this._initialized = true;
this.fire('preInitialize');
if (this.initialize) {
this.entity.script._scriptMethod(this, SCRIPT_INITIALIZE);
}
}
// post initialize script if not post initialized yet and still enabled
// (initialize might have disabled the script so check this.enabled again)
// Warning: Do not do this if the script component is currently being enabled
// because in this case post initialize must be called after all the scripts
// in the script component have been initialized first
if (this._initialized && !this._postInitialized && this.enabled && !this.entity.script._beingEnabled) {
this._postInitialized = true;
if (this.postInitialize) {
this.entity.script._scriptMethod(this, SCRIPT_POST_INITIALIZE);
}
}
}
get enabled() {
return this._enabled && !this._destroyed && this.entity.script.enabled && this.entity.enabled;
}
/**
* @typedef {object} ScriptInitializationArgs
* @property {boolean} [enabled] - True if the script instance is in running state.
* @property {AppBase} app - The {@link AppBase} that is running the script.
* @property {Entity} entity - The {@link Entity} that the script is attached to.
*/
/**
* @param {ScriptInitializationArgs} args - The input arguments object.
* @protected
*/
initScript(args) {
const script = this.constructor; // get script type, i.e. function (class)
Debug.assert(args && args.app && args.entity, `script [${script.__name}] has missing arguments in constructor`);
this.app = args.app;
this.entity = args.entity;
this._enabled = typeof args.enabled === 'boolean' ? args.enabled : true;
this._enabledOld = this.enabled;
this.__destroyed = false;
this.__scriptType = script;
this.__executionOrder = -1;
}
/**
* @type {string|null}
* @private
*/
static __name = null; // Will be assigned when calling createScript or registerScript.
/**
* @param {*} constructorFn - The constructor function of the script type.
* @returns {string} The script name.
* @private
*/
static __getScriptName = getScriptName;
/**
* Sets the unique name of the script.
*
* @type {string|null}
*/
static set scriptName(value) {
this.__name = value;
}
/**
* Gets the unique name of the script.
*
* @type {string|null}
*/
static get scriptName() {
return this.__name;
}
/**
* @function
* @name Script#[initialize]
* @description Called when script is about to run for the first time.
*/
/**
* @function
* @name Script#[postInitialize]
* @description Called after all initialize methods are executed in the same tick or enabling chain of actions.
*/
/**
* @function
* @name Script#[update]
* @description Called for enabled (running state) scripts on each tick.
* @param {number} dt - The delta time in seconds since the last frame.
*/
/**
* @function
* @name Script#[postUpdate]
* @description Called for enabled (running state) scripts on each tick, after update.
* @param {number} dt - The delta time in seconds since the last frame.
*/
/**
* @function
* @name Script#[swap]
* @description Called when a Script that already exists in the registry gets redefined. If the
* new Script has a `swap` method, then it will be executed to perform hot-reload at runtime.
* @param {Script} old - Old instance of the scriptType to copy data to the new instance.
*/
}
// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/no-useless-escape
const funcNameRegex = /^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s\/]*)\s*/;
/**
* @param {Function} constructorFn - The constructor function of the script type.
* @returns {string|undefined} The script name.
*/
export function getScriptName(constructorFn) {
if (typeof constructorFn !== 'function') return undefined;
if (constructorFn.scriptName) return constructorFn.scriptName;
if ('name' in Function.prototype) return constructorFn.name;
if (constructorFn === Function || constructorFn === Function.prototype.constructor) return 'Function';
const match = (`${constructorFn}`).match(funcNameRegex);
return match ? match[1] : undefined;
}