-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
main.js
727 lines (667 loc) · 23.4 KB
/
main.js
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/**
* @module Structure
* @submodule Structure
* @for p5
* @requires constants
*/
'use strict';
require('./shim');
// Core needs the PVariables object
var constants = require('./constants');
/**
* This is the p5 instance constructor.
*
* A p5 instance holds all the properties and methods related to
* a p5 sketch. It expects an incoming sketch closure and it can also
* take an optional node parameter for attaching the generated p5 canvas
* to a node. The sketch closure takes the newly created p5 instance as
* its sole argument and may optionally set <a href="#/p5/preload">preload()</a>, <a href="#/p5/setup">setup()</a>, and/or
* <a href="#/p5/draw">draw()</a> properties on it for running a sketch.
*
* A p5 sketch can run in "global" or "instance" mode:
* "global" - all properties and methods are attached to the window
* "instance" - all properties and methods are bound to this p5 object
*
* @class p5
* @constructor
* @param {function} sketch a closure that can set optional <a href="#/p5/preload">preload()</a>,
* <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> properties on the
* given p5 instance
* @param {HTMLElement|Boolean} [node] element to attach canvas to, if a
* boolean is passed in use it as sync
* @param {Boolean} [sync] start synchronously (optional)
* @return {p5} a p5 instance
*/
var p5 = function(sketch, node, sync) {
if (typeof node === 'boolean' && typeof sync === 'undefined') {
sync = node;
node = undefined;
}
//////////////////////////////////////////////
// PUBLIC p5 PROPERTIES AND METHODS
//////////////////////////////////////////////
/**
* Called directly before <a href="#/p5/setup">setup()</a>, the <a href="#/p5/preload">preload()</a> function is used to handle
* asynchronous loading of external files in a blocking way. If a preload
* function is defined, <a href="#/p5/setup">setup()</a> will wait until any load calls within have
* finished. Nothing besides load calls (<a href="#/p5/loadImage">loadImage</a>, <a href="#/p5/loadJSON">loadJSON</a>, <a href="#/p5/loadFont">loadFont</a>,
* <a href="#/p5/loadStrings">loadStrings</a>, etc.) should be inside the preload function. If asynchronous
* loading is preferred, the load methods can instead be called in <a href="#/p5/setup">setup()</a>
* or anywhere else with the use of a callback parameter.
* <br><br>
* By default the text "loading..." will be displayed. To make your own
* loading page, include an HTML element with id "p5_loading" in your
* page. More information <a href="http://bit.ly/2kQ6Nio">here</a>.
*
* @method preload
* @example
* <div><code>
* let img;
* let c;
* function preload() {
* // preload() runs once
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* // setup() waits until preload() is done
* img.loadPixels();
* // get color of middle pixel
* c = img.get(img.width / 2, img.height / 2);
* }
*
* function draw() {
* background(c);
* image(img, 25, 25, 50, 50);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
/**
* The <a href="#/p5/setup">setup()</a> function is called once when the program starts. It's used to
* define initial environment properties such as screen size and background
* color and to load media such as images and fonts as the program starts.
* There can only be one <a href="#/p5/setup">setup()</a> function for each program and it shouldn't
* be called again after its initial execution.
* <br><br>
* Note: Variables declared within <a href="#/p5/setup">setup()</a> are not accessible within other
* functions, including <a href="#/p5/draw">draw()</a>.
*
* @method setup
* @example
* <div><code>
* let a = 0;
*
* function setup() {
* background(0);
* noStroke();
* fill(102);
* }
*
* function draw() {
* rect(a++ % width, 10, 2, 80);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
/**
* Called directly after <a href="#/p5/setup">setup()</a>, the <a href="#/p5/draw">draw()</a> function continuously executes
* the lines of code contained inside its block until the program is stopped
* or <a href="#/p5/noLoop">noLoop()</a> is called. Note if <a href="#/p5/noLoop">noLoop()</a> is called in <a href="#/p5/setup">setup()</a>, <a href="#/p5/draw">draw()</a> will
* still be executed once before stopping. <a href="#/p5/draw">draw()</a> is called automatically and
* should never be called explicitly.
* <br><br>
* It should always be controlled with <a href="#/p5/noLoop">noLoop()</a>, <a href="#/p5/redraw">redraw()</a> and <a href="#/p5/loop">loop()</a>. After
* <a href="#/p5/noLoop">noLoop()</a> stops the code in <a href="#/p5/draw">draw()</a> from executing, <a href="#/p5/redraw">redraw()</a> causes the
* code inside <a href="#/p5/draw">draw()</a> to execute once, and <a href="#/p5/loop">loop()</a> will cause the code
* inside <a href="#/p5/draw">draw()</a> to resume executing continuously.
* <br><br>
* The number of times <a href="#/p5/draw">draw()</a> executes in each second may be controlled with
* the <a href="#/p5/frameRate">frameRate()</a> function.
* <br><br>
* There can only be one <a href="#/p5/draw">draw()</a> function for each sketch, and <a href="#/p5/draw">draw()</a> must
* exist if you want the code to run continuously, or to process events such
* as <a href="#/p5/mousePressed">mousePressed()</a>. Sometimes, you might have an empty call to <a href="#/p5/draw">draw()</a> in
* your program, as shown in the above example.
* <br><br>
* It is important to note that the drawing coordinate system will be reset
* at the beginning of each <a href="#/p5/draw">draw()</a> call. If any transformations are performed
* within <a href="#/p5/draw">draw()</a> (ex: scale, rotate, translate), their effects will be
* undone at the beginning of <a href="#/p5/draw">draw()</a>, so transformations will not accumulate
* over time. On the other hand, styling applied (ex: fill, stroke, etc) will
* remain in effect.
*
* @method draw
* @example
* <div><code>
* let yPos = 0;
* function setup() {
* // setup() runs once
* frameRate(30);
* }
* function draw() {
* // draw() loops forever, until stopped
* background(204);
* yPos = yPos - 1;
* if (yPos < 0) {
* yPos = height;
* }
* line(0, yPos, width, yPos);
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
//////////////////////////////////////////////
// PRIVATE p5 PROPERTIES AND METHODS
//////////////////////////////////////////////
this._setupDone = false;
// for handling hidpi
this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
this._userNode = node;
this._curElement = null;
this._elements = [];
this._glAttributes = null;
this._requestAnimId = 0;
this._preloadCount = 0;
this._isGlobal = false;
this._loop = true;
this._initializeInstanceVariables();
this._defaultCanvasSize = {
width: 100,
height: 100
};
this._events = {
// keep track of user-events for unregistering later
mousemove: null,
mousedown: null,
mouseup: null,
dragend: null,
dragover: null,
click: null,
dblclick: null,
mouseover: null,
mouseout: null,
keydown: null,
keyup: null,
keypress: null,
touchstart: null,
touchmove: null,
touchend: null,
resize: null,
blur: null
};
this._events.wheel = null;
this._loadingScreenId = 'p5_loading';
// Allows methods to be registered on an instance that
// are instance-specific.
this._registeredMethods = {};
var methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods);
for (var i = 0; i < methods.length; i++) {
var prop = methods[i];
this._registeredMethods[prop] = p5.prototype._registeredMethods[
prop
].slice();
}
if (window.DeviceOrientationEvent) {
this._events.deviceorientation = null;
}
if (window.DeviceMotionEvent && !window._isNodeWebkit) {
this._events.devicemotion = null;
}
this._start = function() {
// Find node if id given
if (this._userNode) {
if (typeof this._userNode === 'string') {
this._userNode = document.getElementById(this._userNode);
}
}
var context = this._isGlobal ? window : this;
var userPreload = context.preload;
if (userPreload) {
// Setup loading screen
// Set loading screen into dom if not present
// Otherwise displays and removes user provided loading screen
var loadingScreen = document.getElementById(this._loadingScreenId);
if (!loadingScreen) {
loadingScreen = document.createElement('div');
loadingScreen.innerHTML = 'Loading...';
loadingScreen.style.position = 'absolute';
loadingScreen.id = this._loadingScreenId;
var node = this._userNode || document.body;
node.appendChild(loadingScreen);
}
var methods = this._preloadMethods;
for (var method in methods) {
// default to p5 if no object defined
methods[method] = methods[method] || p5;
var obj = methods[method];
//it's p5, check if it's global or instance
if (obj === p5.prototype || obj === p5) {
if (this._isGlobal) {
window[method] = this._wrapPreload(this, method);
}
obj = this;
}
this._registeredPreloadMethods[method] = obj[method];
obj[method] = this._wrapPreload(obj, method);
}
userPreload();
this._runIfPreloadsAreDone();
} else {
this._setup();
this._draw();
}
}.bind(this);
this._runIfPreloadsAreDone = function() {
var context = this._isGlobal ? window : this;
if (context._preloadCount === 0) {
var loadingScreen = document.getElementById(context._loadingScreenId);
if (loadingScreen) {
loadingScreen.parentNode.removeChild(loadingScreen);
}
context._setup();
context._draw();
}
};
this._decrementPreload = function() {
var context = this._isGlobal ? window : this;
if (typeof context.preload === 'function') {
context._setProperty('_preloadCount', context._preloadCount - 1);
context._runIfPreloadsAreDone();
}
};
this._wrapPreload = function(obj, fnName) {
return function() {
//increment counter
this._incrementPreload();
//call original function
return this._registeredPreloadMethods[fnName].apply(obj, arguments);
}.bind(this);
};
this._incrementPreload = function() {
var context = this._isGlobal ? window : this;
context._setProperty('_preloadCount', context._preloadCount + 1);
};
this._setup = function() {
// Always create a default canvas.
// Later on if the user calls createCanvas, this default one
// will be replaced
this.createCanvas(
this._defaultCanvasSize.width,
this._defaultCanvasSize.height,
'p2d'
);
// return preload functions to their normal vals if switched by preload
var context = this._isGlobal ? window : this;
if (typeof context.preload === 'function') {
for (var f in this._preloadMethods) {
context[f] = this._preloadMethods[f][f];
if (context[f] && this) {
context[f] = context[f].bind(this);
}
}
}
// Short-circuit on this, in case someone used the library in "global"
// mode earlier
if (typeof context.setup === 'function') {
context.setup();
}
// unhide any hidden canvases that were created
var canvases = document.getElementsByTagName('canvas');
for (var i = 0; i < canvases.length; i++) {
var k = canvases[i];
if (k.dataset.hidden === 'true') {
k.style.visibility = '';
delete k.dataset.hidden;
}
}
this._setupDone = true;
}.bind(this);
this._draw = function() {
var now = window.performance.now();
var time_since_last = now - this._lastFrameTime;
var target_time_between_frames = 1000 / this._targetFrameRate;
// only draw if we really need to; don't overextend the browser.
// draw if we're within 5ms of when our next frame should paint
// (this will prevent us from giving up opportunities to draw
// again when it's really about time for us to do so). fixes an
// issue where the frameRate is too low if our refresh loop isn't
// in sync with the browser. note that we have to draw once even
// if looping is off, so we bypass the time delay if that
// is the case.
var epsilon = 5;
if (
!this._loop ||
time_since_last >= target_time_between_frames - epsilon
) {
//mandatory update values(matrixs and stack)
this.redraw();
this._frameRate = 1000.0 / (now - this._lastFrameTime);
this.deltaTime = now - this._lastFrameTime;
this._setProperty('deltaTime', this.deltaTime);
this._lastFrameTime = now;
// If the user is actually using mouse module, then update
// coordinates, otherwise skip. We can test this by simply
// checking if any of the mouse functions are available or not.
// NOTE : This reflects only in complete build or modular build.
if (typeof this._updateMouseCoords !== 'undefined') {
this._updateMouseCoords();
}
}
// get notified the next time the browser gives us
// an opportunity to draw.
if (this._loop) {
this._requestAnimId = window.requestAnimationFrame(this._draw);
}
}.bind(this);
this._setProperty = function(prop, value) {
this[prop] = value;
if (this._isGlobal) {
window[prop] = value;
}
}.bind(this);
/**
* Removes the entire p5 sketch. This will remove the canvas and any
* elements created by p5.js. It will also stop the draw loop and unbind
* any properties or methods from the window global scope. It will
* leave a variable p5 in case you wanted to create a new p5 sketch.
* If you like, you can set p5 = null to erase it. While all functions and
* variables and objects created by the p5 library will be removed, any
* other global variables created by your code will remain.
*
* @method remove
* @example
* <div class='norender'><code>
* function draw() {
* ellipse(50, 50, 10, 10);
* }
*
* function mousePressed() {
* remove(); // remove whole sketch on mouse press
* }
* </code></div>
*
* @alt
* nothing displayed
*
*/
this.remove = function() {
var loadingScreen = document.getElementById(this._loadingScreenId);
if (loadingScreen) {
loadingScreen.parentNode.removeChild(loadingScreen);
// Add 1 to preload counter to prevent the sketch ever executing setup()
this._incrementPreload();
}
if (this._curElement) {
// stop draw
this._loop = false;
if (this._requestAnimId) {
window.cancelAnimationFrame(this._requestAnimId);
}
// unregister events sketch-wide
for (var ev in this._events) {
window.removeEventListener(ev, this._events[ev]);
}
// remove DOM elements created by p5, and listeners
for (var i = 0; i < this._elements.length; i++) {
var e = this._elements[i];
if (e.elt.parentNode) {
e.elt.parentNode.removeChild(e.elt);
}
for (var elt_ev in e._events) {
e.elt.removeEventListener(elt_ev, e._events[elt_ev]);
}
}
// call any registered remove functions
var self = this;
this._registeredMethods.remove.forEach(function(f) {
if (typeof f !== 'undefined') {
f.call(self);
}
});
}
// remove window bound properties and methods
if (this._isGlobal) {
for (var p in p5.prototype) {
try {
delete window[p];
} catch (x) {
window[p] = undefined;
}
}
for (var p2 in this) {
if (this.hasOwnProperty(p2)) {
try {
delete window[p2];
} catch (x) {
window[p2] = undefined;
}
}
}
p5.instance = null;
}
}.bind(this);
// call any registered init functions
this._registeredMethods.init.forEach(function(f) {
if (typeof f !== 'undefined') {
f.call(this);
}
}, this);
var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder();
// If the user has created a global setup or draw function,
// assume "global" mode and make everything global (i.e. on the window)
if (!sketch) {
this._isGlobal = true;
p5.instance = this;
// Loop through methods on the prototype and attach them to the window
for (var p in p5.prototype) {
if (typeof p5.prototype[p] === 'function') {
var ev = p.substring(2);
if (!this._events.hasOwnProperty(ev)) {
if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) {
// Multiple p5 methods are just native Math functions. These can be
// called without any binding.
friendlyBindGlobal(p, p5.prototype[p]);
} else {
friendlyBindGlobal(p, p5.prototype[p].bind(this));
}
}
} else {
friendlyBindGlobal(p, p5.prototype[p]);
}
}
// Attach its properties to the window
for (var p2 in this) {
if (this.hasOwnProperty(p2)) {
friendlyBindGlobal(p2, this[p2]);
}
}
} else {
// Else, the user has passed in a sketch closure that may set
// user-provided 'setup', 'draw', etc. properties on this instance of p5
sketch(this);
}
// Bind events to window (not using container div bc key events don't work)
for (var e in this._events) {
var f = this['_on' + e];
if (f) {
var m = f.bind(this);
window.addEventListener(e, m, { passive: false });
this._events[e] = m;
}
}
var focusHandler = function() {
this._setProperty('focused', true);
}.bind(this);
var blurHandler = function() {
this._setProperty('focused', false);
}.bind(this);
window.addEventListener('focus', focusHandler);
window.addEventListener('blur', blurHandler);
this.registerMethod('remove', function() {
window.removeEventListener('focus', focusHandler);
window.removeEventListener('blur', blurHandler);
});
if (sync) {
this._start();
} else {
if (document.readyState === 'complete') {
this._start();
} else {
window.addEventListener('load', this._start.bind(this), false);
}
}
};
p5.prototype._initializeInstanceVariables = function() {
this._styles = [];
this._bezierDetail = 20;
this._curveDetail = 20;
this._colorMode = constants.RGB;
this._colorMaxes = {
rgb: [255, 255, 255, 255],
hsb: [360, 100, 100, 1],
hsl: [360, 100, 100, 1]
};
this._pixelsDirty = true;
this._downKeys = {}; //Holds the key codes of currently pressed keys
};
// This is a pointer to our global mode p5 instance, if we're in
// global mode.
p5.instance = null;
/**
* Allows for the friendly error system (FES) to be turned off when creating a sketch,
* which can give a significant boost to performance when needed.
* See <a href='https://github.com/processing/p5.js/wiki/Optimizing-p5.js-Code-for-Performance#disable-the-friendly-error-system-fes'>
* disabling the friendly error system</a>.
*
* @property {Boolean} disableFriendlyErrors
* @example
* <div class="norender notest"><code>
* p5.disableFriendlyErrors = true;
*
* function setup() {
* createCanvas(100, 50);
* }
* </code></div>
*/
p5.disableFriendlyErrors = false;
// attach constants to p5 prototype
for (var k in constants) {
p5.prototype[k] = constants[k];
}
// functions that cause preload to wait
// more can be added by using registerPreloadMethod(func)
p5.prototype._preloadMethods = {
loadJSON: p5.prototype,
loadImage: p5.prototype,
loadStrings: p5.prototype,
loadXML: p5.prototype,
loadBytes: p5.prototype,
loadTable: p5.prototype,
loadFont: p5.prototype,
loadModel: p5.prototype,
loadShader: p5.prototype
};
p5.prototype._registeredMethods = { init: [], pre: [], post: [], remove: [] };
p5.prototype._registeredPreloadMethods = {};
p5.prototype.registerPreloadMethod = function(fnString, obj) {
// obj = obj || p5.prototype;
if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) {
p5.prototype._preloadMethods[fnString] = obj;
}
};
p5.prototype.registerMethod = function(name, m) {
var target = this || p5.prototype;
if (!target._registeredMethods.hasOwnProperty(name)) {
target._registeredMethods[name] = [];
}
target._registeredMethods[name].push(m);
};
// create a function which provides a standardized process for binding
// globals; this is implemented as a factory primarily so that there's a
// way to redefine what "global" means for the binding function so it
// can be used in scenarios like unit testing where the window object
// might not exist
p5.prototype._createFriendlyGlobalFunctionBinder = function(options) {
options = options || {};
var globalObject = options.globalObject || window;
var log = options.log || console.log.bind(console);
var propsToForciblyOverwrite = {
// p5.print actually always overwrites an existing global function,
// albeit one that is very unlikely to be used:
//
// https://developer.mozilla.org/en-US/docs/Web/API/Window/print
print: true
};
return function(prop, value) {
if (
!p5.disableFriendlyErrors &&
typeof IS_MINIFIED === 'undefined' &&
typeof value === 'function' &&
!(prop in p5.prototype._preloadMethods)
) {
try {
// Because p5 has so many common function names, it's likely
// that users may accidentally overwrite global p5 functions with
// their own variables. Let's allow this but log a warning to
// help users who may be doing this unintentionally.
//
// For more information, see:
//
// https://github.com/processing/p5.js/issues/1317
if (prop in globalObject && !(prop in propsToForciblyOverwrite)) {
throw new Error('global "' + prop + '" already exists');
}
// It's possible that this might throw an error because there
// are a lot of edge-cases in which `Object.defineProperty` might
// not succeed; since this functionality is only intended to
// help beginners anyways, we'll just catch such an exception
// if it occurs, and fall back to legacy behavior.
Object.defineProperty(globalObject, prop, {
configurable: true,
enumerable: true,
get: function() {
return value;
},
set: function(newValue) {
Object.defineProperty(globalObject, prop, {
configurable: true,
enumerable: true,
value: newValue,
writable: true
});
log(
'You just changed the value of "' +
prop +
'", which was ' +
"a p5 function. This could cause problems later if you're " +
'not careful.'
);
}
});
} catch (e) {
log(
'p5 had problems creating the global function "' +
prop +
'", ' +
'possibly because your code is already using that name as ' +
'a variable. You may want to rename your variable to something ' +
'else.'
);
globalObject[prop] = value;
}
} else {
globalObject[prop] = value;
}
};
};
module.exports = p5;