/
flora.js
5315 lines (4474 loc) · 155 KB
/
flora.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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
FloraJS
Copyright (c) 2012 Vince Allen
Brooklyn, NY 11215, USA
email: vince@vinceallen.com
web: http://www.vinceallen.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Version: 0.0.7 */
/* Simplex noise by Sean McCullough banksean@gmail.com */
/* Build time: December 2, 2012 05:44:02 */
/** @namespace */
var Flora = {}, exports = Flora;
(function(exports) {
/*global window */
/**
* RequestAnimationFrame shim layer with setTimeout fallback
* @param {function} callback The function to call.
* @returns {function|Object} An animation frame or a timeout object.
*/
window.requestAnimFrame = (function(callback){
'use strict';
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
/*global exports */
var config = {
borderStyles: [
'none',
'solid',
'dotted',
'dashed',
'double',
'inset',
'outset',
'groove',
'ridge'
],
defaultColorList: [
{
name: 'heat',
startColor: [255, 132, 86],
endColor: [175, 47, 0]
},
{
name: 'cold',
startColor: [88, 129, 135],
endColor: [171, 244, 255]
},
{
name: 'food',
startColor: [186, 255, 130],
endColor: [84, 187, 0]
},
{
name: 'oxygen',
startColor: [109, 215, 255],
endColor: [0, 140, 192]
},
{
name: 'light',
startColor: [255, 227, 127],
endColor: [189, 148, 0]
}
],
keyMap: {
pause: 80,
reset: 82,
stats: 83,
thrustLeft: 37,
thrustUp: 38,
thrustRight: 39,
thrustDown: 40
},
touchMap: {
stats: 2,
pause: 3,
reset: 4
}
};
exports.config = config;
/*global exports */
/**
* Creates a new ElementList.
*
* @constructor
*/
function ElementList() {
'use strict';
/**
* Holds a list of elements.
* @private
*/
this._records = [];
}
ElementList.prototype.name = 'ElementList';
/**
* Returns the entire 'records' array.
*
* @returns {Array} An array of elements.
*/
ElementList.prototype.add = function(obj) {
'use strict';
this._records.push(obj);
return this._records;
};
/**
* Returns the entire 'records' array.
*
* @returns {Array} An array of elements.
*/
ElementList.prototype.all = function() {
'use strict';
return this._records;
};
/**
* Returns the total number of elements.
*
* @returns {number} Total number of elements.
*/
ElementList.prototype.count = function() {
'use strict';
return this._records.length;
};
/**
* Returns an array of elements created from the same constructor.
*
* @param {string} name The 'name' property.
* @returns {Array} An array of elements.
*/
ElementList.prototype.getAllByName = function(name) {
'use strict';
var i, max, arr = [];
for (i = 0, max = this._records.length; i < max; i++) {
if (this._records[i].name === name) {
arr[arr.length] = this._records[i];
}
}
return arr;
};
/**
* Returns an array of elements with an attribute that matches the
* passed 'attr'. If 'opt_val' is passed, 'attr' must equal 'val'.
*
* @param {string} attr The property to match.
* @param {*} [opt_val=] The 'attr' property must equal 'val'.
* @returns {Array} An array of elements.
*/
ElementList.prototype.getAllByAttribute = function(attr, opt_val) {
'use strict';
var i, max, arr = [], val = opt_val !== undefined ? opt_val : null;
for (i = 0, max = this._records.length; i < max; i++) {
if (this._records[i][attr] !== undefined) {
if (val !== null && this._records[i][attr] !== val) {
continue;
}
arr[arr.length] = this._records[i];
}
}
return arr;
};
/**
* Updates the properties of elements created from the same constructor.
*
* @param {string} name The constructor name.
* @param {Object} props A map of properties to update.
* @returns {Array} An array of elements.
* @example
* exports.elementList.updatePropsByName('point', {
* color: [0, 0, 0],
* scale: 2
* }); // all point will turn black and double in size
*/
ElementList.prototype.updatePropsByName = function(name, props) {
'use strict';
var i, max, p, arr = this.getAllByName(name);
for (i = 0, max = arr.length; i < max; i++) {
for (p in props) {
if (props.hasOwnProperty(p)) {
arr[i][p] = props[p];
}
}
}
return arr;
};
/**
* Finds an element by its 'id' and returns it.
*
* @param {string|number} id The element's id.
* @returns {Object} The element.
*/
ElementList.prototype.getElement = function (id) {
'use strict';
var i, max, records = this._records;
for (i = 0, max = records.length; i < max; i += 1) {
if (records[i].id === id) {
return records[i];
}
}
};
/**
* Finds an element by its 'id' and removes it from its
* world as well as the records array.
*
* @param {string|number} id The element's id.
*/
ElementList.prototype.destroyElement = function (id) {
'use strict';
var i, max, records = this._records;
for (i = 0, max = records.length; i < max; i += 1) {
if (records[i].id === id) {
records[i].world.el.removeChild(records[i].el);
records.splice(i, 1);
break;
}
}
};
/**
* Removes all elements from their world and resets
* the 'records' array.
*
* @param {string|number} id The element's id.
*/
ElementList.prototype.destroyAll = function () {
'use strict';
var i, records = this._records;
for (i = records.length - 1; i >= 0; i -= 1) {
if (records[i].world) {
records[i].world.el.removeChild(records[i].el);
}
}
this._records = [];
};
/**
* Removes all elements from their world and resets
* the 'records' array.
*
* @param {World} world The world.
*/
ElementList.prototype.destroyByWorld = function (world) {
'use strict';
var i, records = this._records;
for (i = records.length - 1; i >= 0; i -= 1) {
if (records[i].world && records[i].world === world) {
records[i].world.el.removeChild(records[i].el);
records.splice(i, 1);
}
}
};
exports.ElementList = ElementList;
/*global exports, window */
/**
* Creates a new System.
*
* @constructor
*/
function System() {
'use strict';
}
System.name = 'System';
/**
* A list of instructions to execute before the system starts.
*/
System.setup = null;
/**
* Starts the System.
* @param {function} func A list of instructions to execute before the system starts.
* @param {Object} opt_universe A map of options for the System's Universe.
* @param {Array} opt_worlds An array of DOM elements to use as Worlds.
*/
System.start = function (func, opt_universe, opt_worlds) {
'use strict';
var i, max,
defaultColorList = exports.config.defaultColorList;
this.universeOptions = opt_universe || null;
this.worlds = opt_worlds || null;
this._featureDetector = new exports.FeatureDetector();
this.supportedFeatures = {};
this.supportedFeatures.csstransforms = this._featureDetector.detect('csstransforms');
this.supportedFeatures.csstransforms3d = this._featureDetector.detect('csstransforms3d');
this.supportedFeatures.touch = this._featureDetector.detect('touch');
exports.liquids = [];
exports.repellers = [];
exports.attractors = [];
exports.heats = [];
exports.colds = [];
exports.lights = [];
exports.oxygen = [];
exports.food = [];
exports.predators = [];
exports.mouse = {
loc: new exports.Vector(),
locLast: new exports.Vector()
};
// create elementList before universe
exports.elementList = new exports.ElementList();
exports.universe = new exports.Universe(this.universeOptions);
if (exports.Interface.getDataType(this.worlds) === 'array') {
for (i = 0, max = this.worlds.length; i < max; i += 1) {
exports.universe.addWorld({
el: this.worlds[i]
});
}
} else {
exports.universe.addWorld();
}
exports.camera = new exports.Camera();
// add default colors
exports.defaultColors = new exports.ColorTable();
for (i = 0, max = defaultColorList.length; i < max; i++) {
exports.defaultColors.addColor({
name: defaultColorList[i].name,
startColor: defaultColorList[i].startColor,
endColor: defaultColorList[i].endColor
});
}
exports.animLoop = function () {
var i, universe = exports.universe,
elements = exports.elementList.all();
if (universe.isPlaying) {
window.requestAnimFrame(exports.animLoop);
if (universe.zSorted) {
elements = elements.sort(function(a,b){return (b.zIndex - a.zIndex);});
}
/*
* Using two loops here because it's faster and frame rate
* is more consistent if all properties are updated in one loop,
* and all DOM updates are done in a separate loop.
*/
// update elements' properties
for (i = elements.length - 1; i >= 0; i -= 1) {
elements[i].step();
}
// updated elements' DOM element
for (i = elements.length - 1; i >= 0; i -= 1) {
if (elements[i]) {
elements[i].draw();
}
}
exports.universe.updateClocks();
}
};
func = exports.Interface.getDataType(func) === "function" ? func : function () {};
System.setup = func;
func();
exports.animLoop();
};
/**
* Destroys a System.
*/
System.destroy = function () {
'use strict';
exports.elementList.destroyAll();
};
exports.System = System;
/*global exports, document, window, console */
/*jshint supernew:true */
/**
* @namespace
*/
var Utils = {};
/**
* Use to extend the properties and methods of a superClass
* onto a subClass.
*/
Utils.extend = function(subClass, superClass) {
'use strict';
function F() {}
F.prototype = superClass.prototype;
subClass.prototype = new F;
subClass.prototype.constructor = subClass;
};
/**
* Re-maps a number from one range to another.
*
* @param {number} value The value to be converted.
* @param {number} min1 Lower bound of the value's current range.
* @param {number} max1 Upper bound of the value's current range.
* @param {number} min2 Lower bound of the value's target range.
* @param {number} max2 Upper bound of the value's target range.
* @returns {number} A number.
*/
Utils.map = function(value, min1, max1, min2, max2) { // returns a new value relative to a new range
'use strict';
var unitratio = (value - min1) / (max1 - min1);
return (unitratio * (max2 - min2)) + min2;
};
/**
* Generates a psuedo-random number within a range.
*
* @param {number} low The low end of the range.
* @param {number} high The high end of the range.
* @param {boolean} [flt] Set to true to return a float.
* @returns {number} A number.
*/
Utils.getRandomNumber = function(low, high, flt) {
'use strict';
if (flt) {
return Math.random()*(high-(low-1)) + low;
}
return Math.floor(Math.random()*(high-(low-1))) + low;
};
/**
* Converts degrees to radians.
*
* @param {number} degrees The degrees value to be converted.
* @returns {number} A number in radians.
*/
Utils.degreesToRadians = function(degrees) {
'use strict';
if (typeof degrees !== 'undefined') {
return 2 * Math.PI * (degrees/360);
} else {
if (typeof console !== 'undefined') {
console.log('Error: Utils.degreesToRadians is missing degrees param.');
}
return false;
}
};
/**
* Converts radians to degrees.
*
* @param {number} radians The radians value to be converted.
* @returns {number} A number in degrees.
*/
Utils.radiansToDegrees = function(radians) {
'use strict';
if (typeof radians !== 'undefined') {
return radians * (180/Math.PI);
} else {
if (typeof console !== 'undefined') {
console.log('Error: Utils.radiansToDegrees is missing radians param.');
}
return false;
}
};
/**
* Constrain a value within a range.
*
* @param {number} val The value to constrain.
* @param {number} low The lower bound of the range.
* @param {number} high The upper bound of the range.
* @returns {number} A number.
*/
Utils.constrain = function(val, low, high) {
'use strict';
if (val > high) {
return high;
} else if (val < low) {
return low;
}
return val;
};
/**
* Returns a new object with all properties and methods of the
* old object copied to the new object's prototype.
*
* @param {Object} object The object to clone.
* @returns {Object} An object.
*/
Utils.clone = function(object) {
'use strict';
function F() {}
F.prototype = object;
return new F;
};
/**
* Add an event listener to a DOM element.
*
* @param {Object} target The element to receive the event listener.
* @param {string} eventType The event type.
* @param {function} The function to run when the event is triggered.
*/
Utils.addEvent = function(target, eventType, handler) {
'use strict';
if (target.addEventListener) { // W3C
this.addEventHandler = function(target, eventType, handler) {
target.addEventListener(eventType, handler, false);
};
} else if (target.attachEvent) { // IE
this.addEventHandler = function(target, eventType, handler) {
target.attachEvent("on" + eventType, handler);
};
}
this.addEventHandler(target, eventType, handler);
};
/**
* Logs a message to the browser console.
*
* @param {string} msg The message to log.
*/
Utils.log = function(msg) {
'use strict';
if (typeof console !== 'undefined' && typeof console.log !== 'undefined') {
this.log = function(msg) {
console.log(msg); // output error to console
};
this.log.call(this, msg);
} else {
this.log = function () {}; // noop
}
};
/**
* @returns {Object} The current window width and height.
* @example getWindowDim() returns {width: 1024, height: 768}
*/
Utils.getWindowSize = function() {
'use strict';
var d = {
'width' : false,
'height' : false
};
if (typeof(window.innerWidth) !== "undefined") {
d.width = window.innerWidth;
} else if (typeof(document.documentElement) !== "undefined" &&
typeof(document.documentElement.clientWidth) !== "undefined") {
d.width = document.documentElement.clientWidth;
} else if (typeof(document.body) !== "undefined") {
d.width = document.body.clientWidth;
}
if (typeof(window.innerHeight) !== "undefined") {
d.height = window.innerHeight;
} else if (typeof(document.documentElement) !== "undefined" &&
typeof(document.documentElement.clientHeight) !== "undefined") {
d.height = document.documentElement.clientHeight;
} else if (typeof(document.body) !== "undefined") {
d.height = document.body.clientHeight;
}
return d;
};
/**
* Concatenates several properties into a single list
* representing the style properties of an object.
*
* @param [Object] props A map of properties.
* @returns {string} A list of style properties.
*/
Utils.getCSSText = function(props) {
'use strict';
var positionStr = '',
width = typeof props.w === 'number' ? props.w + 'px' : props.w,
height = typeof props.h === 'number' ? props.h + 'px' : props.h;
if (!props.color) {
props.color = [];
props.background = null;
} else {
props.background = props.cm + '(' + props.color[0] + ', ' + props.color[1] + ', ' + props.color[2] + ')';
}
if (!props.borderColor) {
props.borderColor = [];
props.borderColorStr = '';
} else {
props.borderColorStr = props.cm + '(' + props.borderColor[0] + ', ' + props.borderColor[1] + ', ' + props.borderColor[2] + ')';
}
if (exports.System.supportedFeatures.csstransforms3d) {
positionStr = [
'-webkit-transform: translate3d(' + props.x + 'px, ' + props.y + 'px, 0) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-moz-transform: translate3d(' + props.x + 'px, ' + props.y + 'px, 0) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-o-transform: translate3d(' + props.x + 'px, ' + props.y + 'px, 0) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-ms-transform: translate3d(' + props.x + 'px, ' + props.y + 'px, 0) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')'
].join(';');
} else if (exports.System.supportedFeatures.csstransforms) {
positionStr = [
'-webkit-transform: translateX(' + props.x + 'px) translateY(' + props.y + 'px) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-moz-transform: translateX(' + props.x + 'px) translateY(' + props.y + 'px) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-o-transform: translateX(' + props.x + 'px) translateY(' + props.y + 'px) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')',
'-ms-transform: translateX(' + props.x + 'px) translateY(' + props.y + 'px) rotate(' + props.a + 'deg) scaleX(' + props.s + ') scaleY(' + props.s + ')'
].join(';');
} else {
positionStr = [
'position: absolute',
'left: ' + props.x + 'px',
'top: ' + props.y + 'px'
].join(';');
}
return [
positionStr,
'opacity: ' + props.o,
'width: ' + width,
'height: ' + height,
'background: ' + props.background,
'z-index: ' + props.z,
'border-width: ' + props.borderWidth + 'px',
'border-style: ' + props.borderStyle,
'border-color: ' + props.borderColorStr,
'border-radius: ' + props.borderRadius,
'box-shadow: ' + props.boxShadow
].join(';');
};
exports.Utils = Utils;
/*global exports */
/*jshint supernew:true */
/**
* Creates a new Vector.
*
* @param {number} [opt_x = 0] The x location.
* @param {number} [opt_y = 0] The y location.
* @constructor
*/
function Vector(opt_x, opt_y) {
'use strict';
this.x = opt_x || 0;
this.y = opt_y || 0;
}
/**
* Subtract two vectors.
*
* @param {number} v1 The first vector.
* @param {number} v2 The second vector.
* @returns {Object} A new Vector.
*/
Vector.VectorSub = function(v1, v2) {
'use strict';
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/**
* Add two vectors.
*
* @param {number} v1 The first vector.
* @param {number} v2 The second vector.
* @returns {Object} A new Vector.
*/
Vector.VectorAdd = function(v1, v2) {
'use strict';
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/**
* Multiply a vector by a scalar value.
*
* @param {number} v A vector.
* @param {number} n Vector will be multiplied by this number.
* @returns {Object} A new Vector.
*/
Vector.VectorMult = function(v, n) {
'use strict';
return new Vector(v.x * n, v.y * n);
};
/**
* Divide two vectors.
*
* @param {number} v A vector.
* @param {number} n Vector will be divided by this number.
* @returns {Object} A new Vector.
*/
Vector.VectorDiv = function(v, n) {
'use strict';
return new Vector(v.x / n, v.y / n);
};
/**
* Calculates the distance between two vectors.
*
* @param {number} v1 The first vector.
* @param {number} v2 The second vector.
* @returns {number} The distance between the two vectors.
*/
Vector.VectorDistance = function(v1, v2) {
'use strict';
return Math.sqrt(Math.pow(v2.x - v1.x, 2) + Math.pow(v2.y - v1.y, 2));
};
/**
* Get the midpoint between two vectors.
*
* @param {number} v1 The first vector.
* @param {number} v2 The second vector.
* @returns {Object} A new Vector.
*/
Vector.VectorMidPoint = function(v1, v2) {
'use strict';
return Vector.VectorAdd(v1, v2).div(2); // midpoint = (v1 + v2)/2
};
/**
* Get the angle between two vectors.
*
* @param {number} v1 The first vector.
* @param {number} v2 The second vector.
* @returns {number} An angle.
*/
Vector.VectorAngleBetween = function(v1, v2) {
'use strict';
var dot = v1.dot(v2),
theta = Math.acos(dot / (v1.mag() * v2.mag()));
return theta;
};
Vector.prototype.name = 'Vector';
/**
* Returns an new vector with all properties and methods of the
* old vector copied to the new vector's prototype.
*
* @returns {Object} A vector.
*/
Vector.prototype.clone = function() {
'use strict';
function F() {}
F.prototype = this;
return new F;
};
/**
* Adds a vector to this vector.
*
* @param {Object} vector The vector to add.
* @returns {Object} This vector.
*/
Vector.prototype.add = function(vector) {
'use strict';
this.x += vector.x;
this.y += vector.y;
return this;
};
/**
* Subtracts a vector from this vector.
*
* @param {Object} vector The vector to subtract.
* @returns {Object} This vector.
*/
Vector.prototype.sub = function(vector) {
'use strict';
this.x -= vector.x;
this.y -= vector.y;
return this;
};
/**
* Multiplies this vector by a passed value.
*
* @param {number} n Vector will be multiplied by this number.
* @returns {Object} This vector.
*/
Vector.prototype.mult = function(n) {
'use strict';
this.x *= n;
this.y *= n;
return this;
};
/**
* Divides this vector by a passed value.
*
* @param {number} n Vector will be divided by this number.
* @returns {Object} This vector.
*/
Vector.prototype.div = function(n) {
'use strict';
this.x /= n;
this.y /= n;
return this;
};
/**
* Calculates the magnitude of this vector.
*
* @returns {number} The vector's magnitude.
*/
Vector.prototype.mag = function() {
'use strict';
return Math.sqrt((this.x * this.x) + (this.y * this.y));
};
/**
* Limits the vector's magnitude.
*
* @param {number} high The upper bound of the vector's magnitude.
* @returns {Object} This vector.
*/
Vector.prototype.limit = function(high) {
'use strict';
if (this.mag() > high) {
this.normalize();
this.mult(high);
}
return this;
};
Vector.prototype.limitLow = function(low) {
'use strict';
if (this.mag() < low) {
this.normalize();
this.mult(low);
}
return this;
};
/**
* Divides a vector by its magnitude to reduce its magnitude to 1.
* Typically used to retrieve the direction of the vector for later manipulation.
*
* @returns {Object} This vector.
*/
Vector.prototype.normalize = function() {
'use strict';
var m = this.mag();
if (m !== 0) {
return this.div(m);
}
};
/**
* Calculates the distance between this vector and a passed vector.
*
* @param {Object} vector The target vector.
* @returns {Object} The distance between the two vectors.
*/
Vector.prototype.distance = function(vector) {
'use strict';
return Math.sqrt(Math.pow(vector.x - this.x, 2) + Math.pow(vector.y - this.y, 2));
};
/**
* Rotates a vector using a passed angle in radians.
*
* @param {number} radians The angle to rotate in radians.
* @returns {Object} This vector.
*/
Vector.prototype.rotate = function(radians) {
'use strict';
var cos = Math.cos(radians),
sin = Math.sin(radians),
x = this.x,
y = this.y;
this.x = x * cos - y * sin;
this.y = x * sin + y * cos;
return this;
};
/**
* Calculates the midpoint between this vector and a passed vector.
*
* @param {Object} v1 The first vector.
* @param {Object} v1 The second vector.
* @returns {Object} A vector representing the midpoint between the passed vectors.
*/
Vector.prototype.midpoint = function(vector) {
'use strict';
return Vector.VectorAdd(this, vector).div(2);
};
/**
* Calulates the dot product.
*
* @param {Object} vector The target vector.
* @returns {Object} A vector.
*/
Vector.prototype.dot = function(vector) {
'use strict';
if (this.z && vector.z) {
return this.x * vector.x + this.y * vector.y + this.z * vector.z;
}
return this.x * vector.x + this.y * vector.y;
};
exports.Vector = Vector;
/*global exports, document */
/**
* Creates a new ColorPalette object.
*
* Use this class to create a palette of colors randomly selected
* from a range created with initial start and end colors. You
* can also generate gradients that smoothly interpolate from
* start and end colors.
*