-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaframe-physics-components.js
More file actions
15176 lines (12916 loc) · 446 KB
/
aframe-physics-components.js
File metadata and controls
15176 lines (12916 loc) · 446 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
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
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
// Browser distribution of the A-Frame component.
(function () {
if (typeof AFRAME === 'undefined') {
console.error('Component attempted to register before AFRAME was available.');
return;
}
// Register all components here.
var components = __webpack_require__(1).components;
Object.keys(components).forEach(function (name) {
if (AFRAME.aframeCore) {
AFRAME.aframeCore.registerComponent(name, components[name]);
} else {
AFRAME.registerComponent(name, components[name]);
}
});
})();
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var CANNON = __webpack_require__(2);
var coordinates = AFRAME.utils.coordinates;
var diff = AFRAME.utils.diff;
var rad = THREE.Math.degToRad;
var deg = THREE.Math.radToDeg;
// CANNON.World component.
var WorldComponent = {
schema: {
gravity: { type: 'vec3', default: { x: 0, y: -9.82, z: 0 } }
},
init: function () {
var el = this.el;
var world = this.world = new CANNON.World();
this.fixedTimeStep = 1.0 / 60.0;
this.maxSubSteps = 3;
// Artificially bubble physics-world events to entity.
['beginContact', 'endContact'].forEach(function (eventName) {
world.addEventListener(eventName, function (event) {
el.emit('physics-' + eventName, {
bodyA: event.bodyA.el,
bodyB: event.bodyB.el,
target: event.target,
bubbles: false
});
});
});
},
update: function (oldData) {
var gravity = this.data.gravity;
var world = this.world;
world.broadphase = new CANNON.NaiveBroadphase();
world.gravity.set(gravity.x, gravity.y, gravity.z);
},
tick: function (time) {
// Simulation loop.
var fixedTimeStep = this.fixedTimeStep;
var maxSubSteps = this.maxSubsteps;
var world = this.world;
if (this.lastTime !== undefined){
var timeChange = (time - this.lastTime) / 1000;
world.step(fixedTimeStep, timeChange, maxSubSteps);
world.bodies.forEach(function (body) {
if (body.tickWorld) { body.tickWorld(); }
});
}
this.lastTime = time;
}
};
// CANNON.Body component.
var BodyComponent = {
dependencies: ['position'],
schema: {
angularVelocity: { type: 'vec3' },
angularDamping: { default: 0.01 },
boundingBox: { type: 'vec3' },
linearDamping: { default: 0.01 },
mass: { default: 1 },
velocity: { type: 'vec3' }
},
/**
* TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
*/
init: function () {
var self = this;
var sceneEl = this.el.sceneEl;
this.tickWorldBound = this.tickWorld.bind(this);
// Wait for scene to load to initialize physics world.
sceneEl.addEventListener('loaded', function () {
if (!('physics-world' in sceneEl.components)) {
console.warn('physics-world must be specified on scene for physics to work.');
}
var world = self.world = sceneEl.components['physics-world'].world;
var body = self.body = self.getBody(self.el, self.data);
world.add(body);
});
},
update: function (oldData) {
if (!this.world) { return; }
var diffData = diff(this.data, oldData);
if ('velocity' in diffData) {
this.body.velocity.x = diffData.velocity.x;
this.body.velocity.y = diffData.velocity.y;
this.body.velocity.z = diffData.velocity.z;
}
},
applyImpulse: function (forceVec3, pointVec3) {
pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
this.body.applyImpulse(
new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
);
},
getBody: function (el, data) {
var boundingBox = data.boundingBox;
var position = el.getAttribute('position');
var angularVelocity = data.angularVelocity;
var velocity = data.velocity;
var bodyProperties = {
angularDamping: data.angularDamping,
angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
rad(angularVelocity.z)),
linearDamping: data.linearDamping,
mass: data.mass,
position: new CANNON.Vec3(position.x, position.y, position.z),
shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
boundingBox.z / 2)),
velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
};
body = new CANNON.Body(bodyProperties);
// Attach A-Frame stuff.
body.el = el;
body.tickWorld = this.tickWorldBound;
// Artificially bubble physics-body event to entity.
body.addEventListener('collide', function (event) {
el.emit('physics-collide', {
body: event.body,
contact: event.contact,
target: event.target,
bubbles: false
});
});
return body;
},
/**
* Copy CANNON rigid body properties to THREE object3D.
*/
tickWorld: function () {
var body = this.body;
var el = this.el;
el.setAttribute('position', body.position);
// Don't rotate camera around.
if (this.el.components.camera) { return; }
el.setAttribute('rotation', {
x: deg(body.quaternion.x),
y: deg(body.quaternion.y),
z: deg(body.quaternion.z)
});
}
};
// CANNON.Material component.
var materialComponent = {
dependencies: ['physics-body'],
schema: {
angularVelocity: { type: 'vec3' },
angularDamping: { default: 0.01 },
boundingBox: { type: 'vec3' },
linearDamping: { default: 0.01 },
mass: { default: 1 },
velocity: { type: 'vec3' }
},
/**
* TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
*/
init: function () {
var self = this;
var sceneEl = this.el.sceneEl;
this.tickWorldBound = this.tickWorld.bind(this);
// Wait for scene to load to initialize physics world.
sceneEl.addEventListener('loaded', function () {
if (!('physics-world' in sceneEl.components)) {
console.warn('physics-world must be specified on scene for physics to work.');
}
var world = self.world = sceneEl.components['physics-world'].world;
var body = self.body = self.getBody(self.el, self.data);
world.add(body);
});
},
update: function () {
if (!this.world) { return; }
},
applyImpulse: function (forceVec3, pointVec3) {
pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
this.body.applyImpulse(
new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
);
},
getBody: function (el, data) {
var boundingBox = data.boundingBox;
var position = el.getAttribute('position');
var angularVelocity = data.angularVelocity;
var velocity = data.velocity;
var bodyProperties = {
angularDamping: data.angularDamping,
angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
rad(angularVelocity.z)),
linearDamping: data.linearDamping,
mass: data.mass,
position: new CANNON.Vec3(position.x, position.y, position.z),
shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
boundingBox.z / 2)),
velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
};
body = new CANNON.Body(bodyProperties);
// Attach A-Frame stuff.
body.el = el;
body.tick = this.tickWorldBound;
// Artificially bubble physics-body event to entity.
body.addEventListener('collide', function (event) {
el.emit('physics-collide', {
body: event.body,
contact: event.contact,
target: event.target,
bubbles: false
});
});
return body;
},
/**
* Copy CANNON rigid body properties to THREE object3D.
*/
tickWorld: function () {
var body = this.body;
var el = this.el;
el.setAttribute('position', body.position);
el.setAttribute('rotation', {
x: deg(body.quaternion.x),
y: deg(body.quaternion.y),
z: deg(body.quaternion.z)
});
}
};
module.exports.components = {
'physics-body': BodyComponent,
'physics-world': WorldComponent,
'wasd-physics-controls': __webpack_require__(59)
};
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// Export classes
module.exports = {
version : __webpack_require__(3).version,
AABB : __webpack_require__(4),
ArrayCollisionMatrix : __webpack_require__(8),
Body : __webpack_require__(9),
Box : __webpack_require__(14),
Broadphase : __webpack_require__(17),
Constraint : __webpack_require__(19),
ContactEquation : __webpack_require__(20),
Narrowphase : __webpack_require__(23),
ConeTwistConstraint : __webpack_require__(30),
ContactMaterial : __webpack_require__(34),
ConvexPolyhedron : __webpack_require__(15),
Cylinder : __webpack_require__(35),
DistanceConstraint : __webpack_require__(36),
Equation : __webpack_require__(21),
EventTarget : __webpack_require__(10),
FrictionEquation : __webpack_require__(29),
GSSolver : __webpack_require__(37),
GridBroadphase : __webpack_require__(38),
Heightfield : __webpack_require__(39),
HingeConstraint : __webpack_require__(40),
LockConstraint : __webpack_require__(42),
Mat3 : __webpack_require__(6),
Material : __webpack_require__(13),
NaiveBroadphase : __webpack_require__(43),
ObjectCollisionMatrix : __webpack_require__(44),
Pool : __webpack_require__(28),
Particle : __webpack_require__(45),
Plane : __webpack_require__(18),
PointToPointConstraint : __webpack_require__(31),
Quaternion : __webpack_require__(12),
Ray : __webpack_require__(24),
RaycastVehicle : __webpack_require__(46),
RaycastResult : __webpack_require__(25),
RigidVehicle : __webpack_require__(48),
RotationalEquation : __webpack_require__(33),
RotationalMotorEquation : __webpack_require__(41),
SAPBroadphase : __webpack_require__(50),
SPHSystem : __webpack_require__(51),
Shape : __webpack_require__(11),
Solver : __webpack_require__(26),
Sphere : __webpack_require__(49),
SplitSolver : __webpack_require__(52),
Spring : __webpack_require__(53),
Transform : __webpack_require__(16),
Trimesh : __webpack_require__(54),
Vec3 : __webpack_require__(5),
Vec3Pool : __webpack_require__(27),
World : __webpack_require__(56),
};
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = {
"name": "cannon",
"version": "0.6.2",
"description": "A lightweight 3D physics engine written in JavaScript.",
"homepage": "https://github.com/schteppe/cannon.js",
"author": {
"name": "Stefan Hedman",
"email": "schteppe@gmail.com",
"url": "http://steffe.se"
},
"keywords": [
"cannon.js",
"cannon",
"physics",
"engine",
"3d"
],
"main": "./src/Cannon.js",
"engines": {
"node": "*"
},
"repository": {
"type": "git",
"url": "git+https://github.com/schteppe/cannon.js.git"
},
"bugs": {
"url": "https://github.com/schteppe/cannon.js/issues"
},
"licenses": [
{
"type": "MIT"
}
],
"devDependencies": {
"jshint": "latest",
"uglify-js": "latest",
"nodeunit": "^0.9.0",
"grunt": "~0.4.0",
"grunt-contrib-jshint": "~0.1.1",
"grunt-contrib-nodeunit": "^0.4.1",
"grunt-contrib-concat": "~0.1.3",
"grunt-contrib-uglify": "^0.5.1",
"grunt-browserify": "^2.1.4",
"grunt-contrib-yuidoc": "^0.5.2",
"browserify": "*"
},
"dependencies": {},
"gitHead": "022e8ba53fa83abf0ad8a0e4fd08623123838a17",
"readme": "# cannon.js\n\n### Lightweight 3D physics for the web\nInspired by [three.js](https://github.com/mrdoob/three.js) and [ammo.js](https://github.com/kripken/ammo.js), and driven by the fact that the web lacks a physics engine, here comes cannon.js.\nThe rigid body physics engine includes simple collision detection, various body shapes, contacts, friction and constraints.\n\n[Demos](http://schteppe.github.com/cannon.js) - [Documentation](http://schteppe.github.com/cannon.js/docs) - [Rendering hints](https://github.com/schteppe/cannon.js/tree/master/examples) - [NPM package](https://npmjs.org/package/cannon) - [CDN](https://cdnjs.com/libraries/cannon.js)\n\n### Browser install\n\nJust include [cannon.js](https://github.com/schteppe/cannon.js/releases/download/v0.6.2/cannon.js) or [cannon.min.js](https://github.com/schteppe/cannon.js/releases/download/v0.6.2/cannon.min.js) in your html and you're done:\n\n```html\n<script src=\"cannon.min.js\"></script>\n```\n\n### Node.js install\n\nInstall the cannon package via NPM:\n\n```bash\nnpm install --save cannon\n```\n\nAlternatively, point to the Github repo directly to get the very latest version:\n\n```bash\nnpm install --save schteppe/cannon.js\n```\n\n### Example\n\nThe sample code below creates a sphere on a plane, steps the simulation, and prints the sphere simulation to the console. Note that Cannon.js uses [SI units](http://en.wikipedia.org/wiki/International_System_of_Units) (metre, kilogram, second, etc.).\n\n```javascript\n// Setup our world\nvar world = new CANNON.World();\nworld.gravity.set(0, 0, -9.82); // m/s²\n\n// Create a sphere\nvar radius = 1; // m\nvar sphereBody = new CANNON.Body({\n mass: 5, // kg\n position: new CANNON.Vec3(0, 0, 10), // m\n shape: new CANNON.Sphere(radius)\n});\nworld.addBody(sphereBody);\n\n// Create a plane\nvar groundBody = new CANNON.Body({\n mass: 0 // mass == 0 makes the body static\n});\nvar groundShape = new CANNON.Plane();\ngroundBody.addShape(groundShape);\nworld.addBody(groundBody);\n\nvar fixedTimeStep = 1.0 / 60.0; // seconds\nvar maxSubSteps = 3;\n\n// Start the simulation loop\nvar lastTime;\n(function simloop(time){\n requestAnimationFrame(simloop);\n if(lastTime !== undefined){\n var dt = (time - lastTime) / 1000;\n world.step(fixedTimeStep, dt, maxSubSteps);\n }\n console.log(\"Sphere z position: \" + sphereBody.position.z);\n lastTime = time;\n})();\n```\n\nIf you want to know how to use cannon.js with a rendering engine, for example Three.js, see the [Examples](examples).\n\n### Features\n* Rigid body dynamics\n* Discrete collision detection\n* Contacts, friction and restitution\n* Constraints\n * PointToPoint (a.k.a. ball/socket joint)\n * Distance\n * Hinge (with optional motor)\n * Lock\n * ConeTwist\n* Gauss-Seidel constraint solver and an island split algorithm\n* Collision filters\n* Body sleeping\n* Experimental SPH / fluid support\n* Various shapes and collision algorithms (see table below)\n\n| | [Sphere](http://schteppe.github.io/cannon.js/docs/classes/Sphere.html) | [Plane](http://schteppe.github.io/cannon.js/docs/classes/Plane.html) | [Box](http://schteppe.github.io/cannon.js/docs/classes/Box.html) | [Convex](http://schteppe.github.io/cannon.js/docs/classes/ConvexPolyhedron.html) | [Particle](http://schteppe.github.io/cannon.js/docs/classes/Particle.html) | [Heightfield](http://schteppe.github.io/cannon.js/docs/classes/Heightfield.html) | [Trimesh](http://schteppe.github.io/cannon.js/docs/classes/Trimesh.html) |\n| :-----------|:------:|:-----:|:---:|:------:|:--------:|:-----------:|:-------:|\n| Sphere | Yes | Yes | Yes | Yes | Yes | Yes | Yes |\n| Plane | - | - | Yes | Yes | Yes | - | Yes |\n| Box | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Cylinder | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Convex | - | - | - | Yes | Yes | Yes | (todo) |\n| Particle | - | - | - | - | - | (todo) | (todo) |\n| Heightfield | - | - | - | - | - | - | (todo) |\n| Trimesh | - | - | - | - | - | - | - |\n\n### Todo\nThe simpler todos are marked with ```@todo``` in the code. Github Issues can and should also be used for todos.\n\n### Help\nCreate an [issue](https://github.com/schteppe/cannon.js/issues) if you need help.\n",
"readmeFilename": "README.markdown",
"_id": "cannon@0.6.2",
"_shasum": "1dd279639eb713fa5b8d6c0d02a7ca79177f881f",
"_from": "schteppe/cannon.js#022e8ba53fa83abf0ad8a0e4fd08623123838a17",
"_resolved": "git://github.com/schteppe/cannon.js.git#022e8ba53fa83abf0ad8a0e4fd08623123838a17"
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var Vec3 = __webpack_require__(5);
var Utils = __webpack_require__(7);
module.exports = AABB;
/**
* Axis aligned bounding box class.
* @class AABB
* @constructor
* @param {Object} [options]
* @param {Vec3} [options.upperBound]
* @param {Vec3} [options.lowerBound]
*/
function AABB(options){
options = options || {};
/**
* The lower bound of the bounding box.
* @property lowerBound
* @type {Vec3}
*/
this.lowerBound = new Vec3();
if(options.lowerBound){
this.lowerBound.copy(options.lowerBound);
}
/**
* The upper bound of the bounding box.
* @property upperBound
* @type {Vec3}
*/
this.upperBound = new Vec3();
if(options.upperBound){
this.upperBound.copy(options.upperBound);
}
}
var tmp = new Vec3();
/**
* Set the AABB bounds from a set of points.
* @method setFromPoints
* @param {Array} points An array of Vec3's.
* @param {Vec3} position
* @param {Quaternion} quaternion
* @param {number} skinSize
* @return {AABB} The self object
*/
AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
var l = this.lowerBound,
u = this.upperBound,
q = quaternion;
// Set to the first point
l.copy(points[0]);
if(q){
q.vmult(l, l);
}
u.copy(l);
for(var i = 1; i<points.length; i++){
var p = points[i];
if(q){
q.vmult(p, tmp);
p = tmp;
}
if(p.x > u.x){ u.x = p.x; }
if(p.x < l.x){ l.x = p.x; }
if(p.y > u.y){ u.y = p.y; }
if(p.y < l.y){ l.y = p.y; }
if(p.z > u.z){ u.z = p.z; }
if(p.z < l.z){ l.z = p.z; }
}
// Add offset
if (position) {
position.vadd(l, l);
position.vadd(u, u);
}
if(skinSize){
l.x -= skinSize;
l.y -= skinSize;
l.z -= skinSize;
u.x += skinSize;
u.y += skinSize;
u.z += skinSize;
}
return this;
};
/**
* Copy bounds from an AABB to this AABB
* @method copy
* @param {AABB} aabb Source to copy from
* @return {AABB} The this object, for chainability
*/
AABB.prototype.copy = function(aabb){
this.lowerBound.copy(aabb.lowerBound);
this.upperBound.copy(aabb.upperBound);
return this;
};
/**
* Clone an AABB
* @method clone
*/
AABB.prototype.clone = function(){
return new AABB().copy(this);
};
/**
* Extend this AABB so that it covers the given AABB too.
* @method extend
* @param {AABB} aabb
*/
AABB.prototype.extend = function(aabb){
this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
};
/**
* Returns true if the given AABB overlaps this AABB.
* @method overlaps
* @param {AABB} aabb
* @return {Boolean}
*/
AABB.prototype.overlaps = function(aabb){
var l1 = this.lowerBound,
u1 = this.upperBound,
l2 = aabb.lowerBound,
u2 = aabb.upperBound;
// l2 u2
// |---------|
// |--------|
// l1 u1
var overlapsX = ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x));
var overlapsY = ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y));
var overlapsZ = ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
return overlapsX && overlapsY && overlapsZ;
};
// Mostly for debugging
AABB.prototype.volume = function(){
var l = this.lowerBound,
u = this.upperBound;
return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
};
/**
* Returns true if the given AABB is fully contained in this AABB.
* @method contains
* @param {AABB} aabb
* @return {Boolean}
*/
AABB.prototype.contains = function(aabb){
var l1 = this.lowerBound,
u1 = this.upperBound,
l2 = aabb.lowerBound,
u2 = aabb.upperBound;
// l2 u2
// |---------|
// |---------------|
// l1 u1
return (
(l1.x <= l2.x && u1.x >= u2.x) &&
(l1.y <= l2.y && u1.y >= u2.y) &&
(l1.z <= l2.z && u1.z >= u2.z)
);
};
/**
* @method getCorners
* @param {Vec3} a
* @param {Vec3} b
* @param {Vec3} c
* @param {Vec3} d
* @param {Vec3} e
* @param {Vec3} f
* @param {Vec3} g
* @param {Vec3} h
*/
AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
var l = this.lowerBound,
u = this.upperBound;
a.copy(l);
b.set( u.x, l.y, l.z );
c.set( u.x, u.y, l.z );
d.set( l.x, u.y, u.z );
e.set( u.x, l.y, l.z );
f.set( l.x, u.y, l.z );
g.set( l.x, l.y, u.z );
h.copy(u);
};
var transformIntoFrame_corners = [
new Vec3(),
new Vec3(),
new Vec3(),
new Vec3(),
new Vec3(),
new Vec3(),
new Vec3(),
new Vec3()
];
/**
* Get the representation of an AABB in another frame.
* @method toLocalFrame
* @param {Transform} frame
* @param {AABB} target
* @return {AABB} The "target" AABB object.
*/
AABB.prototype.toLocalFrame = function(frame, target){
var corners = transformIntoFrame_corners;
var a = corners[0];
var b = corners[1];
var c = corners[2];
var d = corners[3];
var e = corners[4];
var f = corners[5];
var g = corners[6];
var h = corners[7];
// Get corners in current frame
this.getCorners(a, b, c, d, e, f, g, h);
// Transform them to new local frame
for(var i=0; i !== 8; i++){
var corner = corners[i];
frame.pointToLocal(corner, corner);
}
return target.setFromPoints(corners);
};
/**
* Get the representation of an AABB in the global frame.
* @method toWorldFrame
* @param {Transform} frame
* @param {AABB} target
* @return {AABB} The "target" AABB object.
*/
AABB.prototype.toWorldFrame = function(frame, target){
var corners = transformIntoFrame_corners;
var a = corners[0];
var b = corners[1];
var c = corners[2];
var d = corners[3];
var e = corners[4];
var f = corners[5];
var g = corners[6];
var h = corners[7];
// Get corners in current frame
this.getCorners(a, b, c, d, e, f, g, h);
// Transform them to new local frame
for(var i=0; i !== 8; i++){
var corner = corners[i];
frame.pointToWorld(corner, corner);
}
return target.setFromPoints(corners);
};
/**
* Check if the AABB is hit by a ray.
* @param {Ray} ray
* @return {number}
*/
AABB.prototype.overlapsRay = function(ray){
var t = 0;
// ray.direction is unit direction vector of ray
var dirFracX = 1 / ray._direction.x;
var dirFracY = 1 / ray._direction.y;
var dirFracZ = 1 / ray._direction.z;
// this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
var t1 = (this.lowerBound.x - ray.from.x) * dirFracX;
var t2 = (this.upperBound.x - ray.from.x) * dirFracX;
var t3 = (this.lowerBound.y - ray.from.y) * dirFracY;
var t4 = (this.upperBound.y - ray.from.y) * dirFracY;
var t5 = (this.lowerBound.z - ray.from.z) * dirFracZ;
var t6 = (this.upperBound.z - ray.from.z) * dirFracZ;
// var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
// var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
// if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
if (tmax < 0){
//t = tmax;
return false;
}
// if tmin > tmax, ray doesn't intersect AABB
if (tmin > tmax){
//t = tmax;
return false;
}
return true;
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
module.exports = Vec3;
var Mat3 = __webpack_require__(6);
/**
* 3-dimensional vector
* @class Vec3
* @constructor
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @author schteppe
* @example
* var v = new Vec3(1, 2, 3);
* console.log('x=' + v.x); // x=1
*/
function Vec3(x,y,z){
/**
* @property x
* @type {Number}
*/
this.x = x||0.0;
/**
* @property y
* @type {Number}
*/
this.y = y||0.0;
/**
* @property z
* @type {Number}
*/
this.z = z||0.0;
}
/**
* @static
* @property {Vec3} ZERO
*/
Vec3.ZERO = new Vec3(0, 0, 0);
/**
* @static
* @property {Vec3} UNIT_X
*/
Vec3.UNIT_X = new Vec3(1, 0, 0);
/**
* @static
* @property {Vec3} UNIT_Y
*/
Vec3.UNIT_Y = new Vec3(0, 1, 0);
/**
* @static
* @property {Vec3} UNIT_Z
*/
Vec3.UNIT_Z = new Vec3(0, 0, 1);
/**
* Vector cross product
* @method cross
* @param {Vec3} v
* @param {Vec3} target Optional. Target to save in.
* @return {Vec3}
*/
Vec3.prototype.cross = function(v,target){
var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
target = target || new Vec3();
target.x = (y * vz) - (z * vy);
target.y = (z * vx) - (x * vz);
target.z = (x * vy) - (y * vx);
return target;
};
/**
* Set the vectors' 3 elements
* @method set
* @param {Number} x
* @param {Number} y
* @param {Number} z
* @return Vec3
*/
Vec3.prototype.set = function(x,y,z){
this.x = x;
this.y = y;
this.z = z;
return this;
};
/**
* Set all components of the vector to zero.
* @method setZero
*/
Vec3.prototype.setZero = function(){
this.x = this.y = this.z = 0;
};
/**
* Vector addition
* @method vadd
* @param {Vec3} v
* @param {Vec3} target Optional.
* @return {Vec3}
*/
Vec3.prototype.vadd = function(v,target){
if(target){
target.x = v.x + this.x;
target.y = v.y + this.y;
target.z = v.z + this.z;
} else {
return new Vec3(this.x + v.x,
this.y + v.y,
this.z + v.z);
}
};
/**
* Vector subtraction
* @method vsub
* @param {Vec3} v
* @param {Vec3} target Optional. Target to save in.
* @return {Vec3}
*/
Vec3.prototype.vsub = function(v,target){
if(target){
target.x = this.x - v.x;
target.y = this.y - v.y;
target.z = this.z - v.z;
} else {
return new Vec3(this.x-v.x,
this.y-v.y,
this.z-v.z);
}
};
/**
* Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
* @method crossmat
* @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
* @return {Mat3}
*/
Vec3.prototype.crossmat = function(){
return new Mat3([ 0, -this.z, this.y,
this.z, 0, -this.x,
-this.y, this.x, 0]);
};
/**
* Normalize the vector. Note that this changes the values in the vector.
* @method normalize
* @return {Number} Returns the norm of the vector
*/
Vec3.prototype.normalize = function(){
var x=this.x, y=this.y, z=this.z;
var n = Math.sqrt(x*x + y*y + z*z);
if(n>0.0){
var invN = 1/n;
this.x *= invN;
this.y *= invN;
this.z *= invN;
} else {
// Make something up
this.x = 0;
this.y = 0;
this.z = 0;
}
return n;
};
/**
* Get the version of this vector that is of length 1.
* @method unit
* @param {Vec3} target Optional target to save in
* @return {Vec3} Returns the unit vector
*/
Vec3.prototype.unit = function(target){
target = target || new Vec3();
var x=this.x, y=this.y, z=this.z;
var ninv = Math.sqrt(x*x + y*y + z*z);
if(ninv>0.0){
ninv = 1.0/ninv;
target.x = x * ninv;
target.y = y * ninv;
target.z = z * ninv;
} else {
target.x = 1;
target.y = 0;
target.z = 0;
}
return target;
};
/**
* Get the length of the vector
* @method norm
* @return {Number}
* @deprecated Use .length() instead
*/
Vec3.prototype.norm = function(){
var x=this.x, y=this.y, z=this.z;
return Math.sqrt(x*x + y*y + z*z);
};
/**
* Get the length of the vector
* @method length
* @return {Number}