babylon.abstractMesh.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var BABYLON;
  7. (function (BABYLON) {
  8. var AbstractMesh = (function (_super) {
  9. __extends(AbstractMesh, _super);
  10. function AbstractMesh(name, scene) {
  11. var _this = this;
  12. _super.call(this, name, scene);
  13. // Properties
  14. this.definedFacingForward = true; // orientation for POV movement & rotation
  15. this.position = new BABYLON.Vector3(0, 0, 0);
  16. this.rotation = new BABYLON.Vector3(0, 0, 0);
  17. this.scaling = new BABYLON.Vector3(1, 1, 1);
  18. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  19. this.visibility = 1.0;
  20. this.alphaIndex = Number.MAX_VALUE;
  21. this.infiniteDistance = false;
  22. this.isVisible = true;
  23. this.isPickable = true;
  24. this.showBoundingBox = false;
  25. this.showSubMeshesBoundingBox = false;
  26. this.onDispose = null;
  27. this.isBlocker = false;
  28. this.renderingGroupId = 0;
  29. this.receiveShadows = false;
  30. this.renderOutline = false;
  31. this.outlineColor = BABYLON.Color3.Red();
  32. this.outlineWidth = 0.02;
  33. this.renderOverlay = false;
  34. this.overlayColor = BABYLON.Color3.Red();
  35. this.overlayAlpha = 0.5;
  36. this.hasVertexAlpha = false;
  37. this.useVertexColors = true;
  38. this.applyFog = true;
  39. this.computeBonesUsingShaders = true;
  40. this.scalingDeterminant = 1;
  41. this.numBoneInfluencers = 4;
  42. this.useOctreeForRenderingSelection = true;
  43. this.useOctreeForPicking = true;
  44. this.useOctreeForCollisions = true;
  45. this.layerMask = 0x0FFFFFFF;
  46. this.alwaysSelectAsActiveMesh = false;
  47. // Physics
  48. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  49. // Collisions
  50. this._checkCollisions = false;
  51. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  52. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  53. this._collider = new BABYLON.Collider();
  54. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  55. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  56. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  57. // Edges
  58. this.edgesWidth = 1;
  59. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  60. // Cache
  61. this._localScaling = BABYLON.Matrix.Zero();
  62. this._localRotation = BABYLON.Matrix.Zero();
  63. this._localTranslation = BABYLON.Matrix.Zero();
  64. this._localBillboard = BABYLON.Matrix.Zero();
  65. this._localPivotScaling = BABYLON.Matrix.Zero();
  66. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  67. this._localWorld = BABYLON.Matrix.Zero();
  68. this._worldMatrix = BABYLON.Matrix.Zero();
  69. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  70. this._absolutePosition = BABYLON.Vector3.Zero();
  71. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  72. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  73. this._isDirty = false;
  74. this._pivotMatrix = BABYLON.Matrix.Identity();
  75. this._isDisposed = false;
  76. this._renderId = 0;
  77. this._intersectionsInProgress = new Array();
  78. this._onAfterWorldMatrixUpdate = new Array();
  79. this._isWorldMatrixFrozen = false;
  80. this._unIndexed = false;
  81. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  82. if (collidedMesh === void 0) { collidedMesh = null; }
  83. //TODO move this to the collision coordinator!
  84. if (_this.getScene().workerCollisions)
  85. newPosition.multiplyInPlace(_this._collider.radius);
  86. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  87. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  88. _this.position.addInPlace(_this._diffPositionForCollisions);
  89. }
  90. if (_this.onCollide && collidedMesh) {
  91. _this.onCollide(collidedMesh);
  92. }
  93. if (_this.onCollisionPositionChange) {
  94. _this.onCollisionPositionChange(_this.position);
  95. }
  96. };
  97. scene.addMesh(this);
  98. }
  99. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  100. get: function () {
  101. return AbstractMesh._BILLBOARDMODE_NONE;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  107. get: function () {
  108. return AbstractMesh._BILLBOARDMODE_X;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  114. get: function () {
  115. return AbstractMesh._BILLBOARDMODE_Y;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  121. get: function () {
  122. return AbstractMesh._BILLBOARDMODE_Z;
  123. },
  124. enumerable: true,
  125. configurable: true
  126. });
  127. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  128. get: function () {
  129. return AbstractMesh._BILLBOARDMODE_ALL;
  130. },
  131. enumerable: true,
  132. configurable: true
  133. });
  134. // Methods
  135. AbstractMesh.prototype.disableEdgesRendering = function () {
  136. if (this._edgesRenderer !== undefined) {
  137. this._edgesRenderer.dispose();
  138. this._edgesRenderer = undefined;
  139. }
  140. };
  141. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  142. if (epsilon === void 0) { epsilon = 0.95; }
  143. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  144. this.disableEdgesRendering();
  145. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  146. };
  147. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  148. get: function () {
  149. return false;
  150. },
  151. enumerable: true,
  152. configurable: true
  153. });
  154. AbstractMesh.prototype.getLOD = function (camera) {
  155. return this;
  156. };
  157. AbstractMesh.prototype.getTotalVertices = function () {
  158. return 0;
  159. };
  160. AbstractMesh.prototype.getIndices = function () {
  161. return null;
  162. };
  163. AbstractMesh.prototype.getVerticesData = function (kind) {
  164. return null;
  165. };
  166. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  167. return false;
  168. };
  169. AbstractMesh.prototype.getBoundingInfo = function () {
  170. if (this._masterMesh) {
  171. return this._masterMesh.getBoundingInfo();
  172. }
  173. if (!this._boundingInfo) {
  174. this._updateBoundingInfo();
  175. }
  176. return this._boundingInfo;
  177. };
  178. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  179. get: function () {
  180. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  181. },
  182. enumerable: true,
  183. configurable: true
  184. });
  185. AbstractMesh.prototype._preActivate = function () {
  186. };
  187. AbstractMesh.prototype._activate = function (renderId) {
  188. this._renderId = renderId;
  189. };
  190. AbstractMesh.prototype.getWorldMatrix = function () {
  191. if (this._masterMesh) {
  192. return this._masterMesh.getWorldMatrix();
  193. }
  194. if (this._currentRenderId !== this.getScene().getRenderId()) {
  195. this.computeWorldMatrix();
  196. }
  197. return this._worldMatrix;
  198. };
  199. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  200. get: function () {
  201. return this._worldMatrix;
  202. },
  203. enumerable: true,
  204. configurable: true
  205. });
  206. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  207. get: function () {
  208. return this._absolutePosition;
  209. },
  210. enumerable: true,
  211. configurable: true
  212. });
  213. AbstractMesh.prototype.freezeWorldMatrix = function () {
  214. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  215. this.computeWorldMatrix(true);
  216. this._isWorldMatrixFrozen = true;
  217. };
  218. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  219. this._isWorldMatrixFrozen = false;
  220. this.computeWorldMatrix(true);
  221. };
  222. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  223. get: function () {
  224. return this._isWorldMatrixFrozen;
  225. },
  226. enumerable: true,
  227. configurable: true
  228. });
  229. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  230. axis.normalize();
  231. if (!this.rotationQuaternion) {
  232. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  233. this.rotation = BABYLON.Vector3.Zero();
  234. }
  235. var rotationQuaternion;
  236. if (!space || space === BABYLON.Space.LOCAL) {
  237. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  238. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  239. }
  240. else {
  241. if (this.parent) {
  242. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  243. invertParentWorldMatrix.invert();
  244. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  245. }
  246. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  247. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  248. }
  249. };
  250. AbstractMesh.prototype.translate = function (axis, distance, space) {
  251. var displacementVector = axis.scale(distance);
  252. if (!space || space === BABYLON.Space.LOCAL) {
  253. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  254. this.setPositionWithLocalVector(tempV3);
  255. }
  256. else {
  257. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  258. }
  259. };
  260. AbstractMesh.prototype.getAbsolutePosition = function () {
  261. this.computeWorldMatrix();
  262. return this._absolutePosition;
  263. };
  264. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  265. if (!absolutePosition) {
  266. return;
  267. }
  268. var absolutePositionX;
  269. var absolutePositionY;
  270. var absolutePositionZ;
  271. if (absolutePosition.x === undefined) {
  272. if (arguments.length < 3) {
  273. return;
  274. }
  275. absolutePositionX = arguments[0];
  276. absolutePositionY = arguments[1];
  277. absolutePositionZ = arguments[2];
  278. }
  279. else {
  280. absolutePositionX = absolutePosition.x;
  281. absolutePositionY = absolutePosition.y;
  282. absolutePositionZ = absolutePosition.z;
  283. }
  284. if (this.parent) {
  285. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  286. invertParentWorldMatrix.invert();
  287. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  288. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  289. }
  290. else {
  291. this.position.x = absolutePositionX;
  292. this.position.y = absolutePositionY;
  293. this.position.z = absolutePositionZ;
  294. }
  295. };
  296. // ================================== Point of View Movement =================================
  297. /**
  298. * Perform relative position change from the point of view of behind the front of the mesh.
  299. * This is performed taking into account the meshes current rotation, so you do not have to care.
  300. * Supports definition of mesh facing forward or backward.
  301. * @param {number} amountRight
  302. * @param {number} amountUp
  303. * @param {number} amountForward
  304. */
  305. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  306. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  307. };
  308. /**
  309. * Calculate relative position change from the point of view of behind the front of the mesh.
  310. * This is performed taking into account the meshes current rotation, so you do not have to care.
  311. * Supports definition of mesh facing forward or backward.
  312. * @param {number} amountRight
  313. * @param {number} amountUp
  314. * @param {number} amountForward
  315. */
  316. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  317. var rotMatrix = new BABYLON.Matrix();
  318. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  319. rotQuaternion.toRotationMatrix(rotMatrix);
  320. var translationDelta = BABYLON.Vector3.Zero();
  321. var defForwardMult = this.definedFacingForward ? -1 : 1;
  322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  323. return translationDelta;
  324. };
  325. // ================================== Point of View Rotation =================================
  326. /**
  327. * Perform relative rotation change from the point of view of behind the front of the mesh.
  328. * Supports definition of mesh facing forward or backward.
  329. * @param {number} flipBack
  330. * @param {number} twirlClockwise
  331. * @param {number} tiltRight
  332. */
  333. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  334. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  335. };
  336. /**
  337. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  338. * Supports definition of mesh facing forward or backward.
  339. * @param {number} flipBack
  340. * @param {number} twirlClockwise
  341. * @param {number} tiltRight
  342. */
  343. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  344. var defForwardMult = this.definedFacingForward ? 1 : -1;
  345. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  346. };
  347. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  348. this._pivotMatrix = matrix;
  349. this._cache.pivotMatrixUpdated = true;
  350. };
  351. AbstractMesh.prototype.getPivotMatrix = function () {
  352. return this._pivotMatrix;
  353. };
  354. AbstractMesh.prototype._isSynchronized = function () {
  355. if (this._isDirty) {
  356. return false;
  357. }
  358. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  359. return false;
  360. if (this._cache.pivotMatrixUpdated) {
  361. return false;
  362. }
  363. if (this.infiniteDistance) {
  364. return false;
  365. }
  366. if (!this._cache.position.equals(this.position))
  367. return false;
  368. if (this.rotationQuaternion) {
  369. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  370. return false;
  371. }
  372. else {
  373. if (!this._cache.rotation.equals(this.rotation))
  374. return false;
  375. }
  376. if (!this._cache.scaling.equals(this.scaling))
  377. return false;
  378. return true;
  379. };
  380. AbstractMesh.prototype._initCache = function () {
  381. _super.prototype._initCache.call(this);
  382. this._cache.localMatrixUpdated = false;
  383. this._cache.position = BABYLON.Vector3.Zero();
  384. this._cache.scaling = BABYLON.Vector3.Zero();
  385. this._cache.rotation = BABYLON.Vector3.Zero();
  386. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  387. this._cache.billboardMode = -1;
  388. };
  389. AbstractMesh.prototype.markAsDirty = function (property) {
  390. if (property === "rotation") {
  391. this.rotationQuaternion = null;
  392. }
  393. this._currentRenderId = Number.MAX_VALUE;
  394. this._isDirty = true;
  395. };
  396. AbstractMesh.prototype._updateBoundingInfo = function () {
  397. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  398. this._boundingInfo._update(this.worldMatrixFromCache);
  399. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  400. };
  401. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  402. if (!this.subMeshes) {
  403. return;
  404. }
  405. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  406. var subMesh = this.subMeshes[subIndex];
  407. if (!subMesh.IsGlobal) {
  408. subMesh.updateBoundingInfo(matrix);
  409. }
  410. }
  411. };
  412. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  413. if (this._isWorldMatrixFrozen) {
  414. return this._worldMatrix;
  415. }
  416. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  417. return this._worldMatrix;
  418. }
  419. this._cache.position.copyFrom(this.position);
  420. this._cache.scaling.copyFrom(this.scaling);
  421. this._cache.pivotMatrixUpdated = false;
  422. this._cache.billboardMode = this.billboardMode;
  423. this._currentRenderId = this.getScene().getRenderId();
  424. this._isDirty = false;
  425. // Scaling
  426. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  427. // Rotation
  428. if (this.rotationQuaternion) {
  429. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  430. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  431. }
  432. else {
  433. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  434. this._cache.rotation.copyFrom(this.rotation);
  435. }
  436. // Translation
  437. if (this.infiniteDistance && !this.parent) {
  438. var camera = this.getScene().activeCamera;
  439. if (camera) {
  440. var cameraWorldMatrix = camera.getWorldMatrix();
  441. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  442. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  443. }
  444. }
  445. else {
  446. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  447. }
  448. // Composing transformations
  449. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  450. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  451. // Billboarding
  452. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  453. var localPosition = this.position.clone();
  454. var zero = this.getScene().activeCamera.globalPosition.clone();
  455. if (this.parent && this.parent.position) {
  456. localPosition.addInPlace(this.parent.position);
  457. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  458. }
  459. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  460. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  461. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  462. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  463. zero.y = localPosition.y + 0.001;
  464. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  465. zero.z = localPosition.z + 0.001;
  466. }
  467. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  468. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  469. this._localBillboard.invert();
  470. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  471. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  472. }
  473. // Local world
  474. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  475. // Parent
  476. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  477. this._markSyncedWithParent();
  478. if (this._meshToBoneReferal) {
  479. if (!this._localMeshReferalTransform) {
  480. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  481. }
  482. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  483. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  484. }
  485. else {
  486. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  487. }
  488. }
  489. else {
  490. this._worldMatrix.copyFrom(this._localWorld);
  491. }
  492. // Bounding info
  493. this._updateBoundingInfo();
  494. // Absolute position
  495. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  496. // Callbacks
  497. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  498. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  499. }
  500. return this._worldMatrix;
  501. };
  502. /**
  503. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  504. * @param func: callback function to add
  505. */
  506. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  507. this._onAfterWorldMatrixUpdate.push(func);
  508. };
  509. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  510. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  511. if (index > -1) {
  512. this._onAfterWorldMatrixUpdate.splice(index, 1);
  513. }
  514. };
  515. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  516. this.computeWorldMatrix();
  517. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  518. };
  519. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  520. this.computeWorldMatrix();
  521. var invLocalWorldMatrix = this._localWorld.clone();
  522. invLocalWorldMatrix.invert();
  523. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  524. };
  525. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  526. this.computeWorldMatrix(true);
  527. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  528. };
  529. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  530. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  531. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  532. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  533. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  534. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  535. /// <returns>Mesh oriented towards targetMesh</returns>
  536. yawCor = yawCor || 0; // default to zero if undefined
  537. pitchCor = pitchCor || 0;
  538. rollCor = rollCor || 0;
  539. var dv = targetPoint.subtract(this.position);
  540. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  541. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  542. var pitch = Math.atan2(dv.y, len);
  543. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  544. };
  545. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  546. this._meshToBoneReferal = affectedMesh;
  547. this.parent = bone;
  548. if (bone.getWorldMatrix().determinant() < 0) {
  549. this.scalingDeterminant *= -1;
  550. }
  551. };
  552. AbstractMesh.prototype.detachFromBone = function () {
  553. if (this.parent.getWorldMatrix().determinant() < 0) {
  554. this.scalingDeterminant *= -1;
  555. }
  556. this._meshToBoneReferal = null;
  557. this.parent = null;
  558. };
  559. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  560. return this._boundingInfo.isInFrustum(frustumPlanes);
  561. };
  562. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  563. if (!camera) {
  564. camera = this.getScene().activeCamera;
  565. }
  566. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  567. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  568. return false;
  569. }
  570. return true;
  571. };
  572. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  573. if (!this._boundingInfo || !mesh._boundingInfo) {
  574. return false;
  575. }
  576. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  577. };
  578. AbstractMesh.prototype.intersectsPoint = function (point) {
  579. if (!this._boundingInfo) {
  580. return false;
  581. }
  582. return this._boundingInfo.intersectsPoint(point);
  583. };
  584. // Physics
  585. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  586. var physicsEngine = this.getScene().getPhysicsEngine();
  587. if (!physicsEngine) {
  588. return null;
  589. }
  590. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  591. if (impostor.impostor) {
  592. // Old API
  593. options = impostor;
  594. impostor = impostor.impostor;
  595. }
  596. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  597. physicsEngine._unregisterMesh(this);
  598. return null;
  599. }
  600. if (!options) {
  601. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  602. }
  603. else {
  604. if (!options.mass && options.mass !== 0)
  605. options.mass = 0;
  606. if (!options.friction && options.friction !== 0)
  607. options.friction = 0.2;
  608. if (!options.restitution && options.restitution !== 0)
  609. options.restitution = 0.2;
  610. }
  611. this._physicImpostor = impostor;
  612. this._physicsMass = options.mass;
  613. this._physicsFriction = options.friction;
  614. this._physicRestitution = options.restitution;
  615. return physicsEngine._registerMesh(this, impostor, options);
  616. };
  617. AbstractMesh.prototype.getPhysicsImpostor = function () {
  618. if (!this._physicImpostor) {
  619. return BABYLON.PhysicsEngine.NoImpostor;
  620. }
  621. return this._physicImpostor;
  622. };
  623. AbstractMesh.prototype.getPhysicsMass = function () {
  624. if (!this._physicsMass) {
  625. return 0;
  626. }
  627. return this._physicsMass;
  628. };
  629. AbstractMesh.prototype.getPhysicsFriction = function () {
  630. if (!this._physicsFriction) {
  631. return 0;
  632. }
  633. return this._physicsFriction;
  634. };
  635. AbstractMesh.prototype.getPhysicsRestitution = function () {
  636. if (!this._physicRestitution) {
  637. return 0;
  638. }
  639. return this._physicRestitution;
  640. };
  641. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  642. if (!camera) {
  643. camera = this.getScene().activeCamera;
  644. }
  645. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  646. };
  647. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  648. if (!camera) {
  649. camera = this.getScene().activeCamera;
  650. }
  651. return this.absolutePosition.subtract(camera.position).length();
  652. };
  653. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  654. if (!this._physicImpostor) {
  655. return;
  656. }
  657. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  658. };
  659. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  660. if (!this._physicImpostor) {
  661. return;
  662. }
  663. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  664. };
  665. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  666. if (!this._physicImpostor) {
  667. return;
  668. }
  669. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  670. };
  671. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  672. // Collisions
  673. get: function () {
  674. return this._checkCollisions;
  675. },
  676. set: function (collisionEnabled) {
  677. this._checkCollisions = collisionEnabled;
  678. if (this.getScene().workerCollisions) {
  679. this.getScene().collisionCoordinator.onMeshUpdated(this);
  680. }
  681. },
  682. enumerable: true,
  683. configurable: true
  684. });
  685. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  686. var globalPosition = this.getAbsolutePosition();
  687. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  688. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  689. this._collider.radius = this.ellipsoid;
  690. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  691. };
  692. // Submeshes octree
  693. /**
  694. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  695. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  696. */
  697. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  698. if (maxCapacity === void 0) { maxCapacity = 64; }
  699. if (maxDepth === void 0) { maxDepth = 2; }
  700. if (!this._submeshesOctree) {
  701. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  702. }
  703. this.computeWorldMatrix(true);
  704. // Update octree
  705. var bbox = this.getBoundingInfo().boundingBox;
  706. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  707. return this._submeshesOctree;
  708. };
  709. // Collisions
  710. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  711. this._generatePointsArray();
  712. // Transformation
  713. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  714. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  715. subMesh._lastColliderWorldVertices = [];
  716. subMesh._trianglePlanes = [];
  717. var start = subMesh.verticesStart;
  718. var end = (subMesh.verticesStart + subMesh.verticesCount);
  719. for (var i = start; i < end; i++) {
  720. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  721. }
  722. }
  723. // Collide
  724. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  725. if (collider.collisionFound) {
  726. collider.collidedMesh = this;
  727. }
  728. };
  729. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  730. var subMeshes;
  731. var len;
  732. // Octrees
  733. if (this._submeshesOctree && this.useOctreeForCollisions) {
  734. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  735. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  736. len = intersections.length;
  737. subMeshes = intersections.data;
  738. }
  739. else {
  740. subMeshes = this.subMeshes;
  741. len = subMeshes.length;
  742. }
  743. for (var index = 0; index < len; index++) {
  744. var subMesh = subMeshes[index];
  745. // Bounding test
  746. if (len > 1 && !subMesh._checkCollision(collider))
  747. continue;
  748. this._collideForSubMesh(subMesh, transformMatrix, collider);
  749. }
  750. };
  751. AbstractMesh.prototype._checkCollision = function (collider) {
  752. // Bounding box test
  753. if (!this._boundingInfo._checkCollision(collider))
  754. return;
  755. // Transformation matrix
  756. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  757. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  758. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  759. };
  760. // Picking
  761. AbstractMesh.prototype._generatePointsArray = function () {
  762. return false;
  763. };
  764. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  765. var pickingInfo = new BABYLON.PickingInfo();
  766. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  767. return pickingInfo;
  768. }
  769. if (!this._generatePointsArray()) {
  770. return pickingInfo;
  771. }
  772. var intersectInfo = null;
  773. // Octrees
  774. var subMeshes;
  775. var len;
  776. if (this._submeshesOctree && this.useOctreeForPicking) {
  777. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  778. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  779. len = intersections.length;
  780. subMeshes = intersections.data;
  781. }
  782. else {
  783. subMeshes = this.subMeshes;
  784. len = subMeshes.length;
  785. }
  786. for (var index = 0; index < len; index++) {
  787. var subMesh = subMeshes[index];
  788. // Bounding test
  789. if (len > 1 && !subMesh.canIntersects(ray))
  790. continue;
  791. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  792. if (currentIntersectInfo) {
  793. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  794. intersectInfo = currentIntersectInfo;
  795. intersectInfo.subMeshId = index;
  796. if (fastCheck) {
  797. break;
  798. }
  799. }
  800. }
  801. }
  802. if (intersectInfo) {
  803. // Get picked point
  804. var world = this.getWorldMatrix();
  805. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  806. var direction = ray.direction.clone();
  807. direction = direction.scale(intersectInfo.distance);
  808. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  809. var pickedPoint = worldOrigin.add(worldDirection);
  810. // Return result
  811. pickingInfo.hit = true;
  812. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  813. pickingInfo.pickedPoint = pickedPoint;
  814. pickingInfo.pickedMesh = this;
  815. pickingInfo.bu = intersectInfo.bu;
  816. pickingInfo.bv = intersectInfo.bv;
  817. pickingInfo.faceId = intersectInfo.faceId;
  818. pickingInfo.subMeshId = intersectInfo.subMeshId;
  819. return pickingInfo;
  820. }
  821. return pickingInfo;
  822. };
  823. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  824. return null;
  825. };
  826. AbstractMesh.prototype.releaseSubMeshes = function () {
  827. if (this.subMeshes) {
  828. while (this.subMeshes.length) {
  829. this.subMeshes[0].dispose();
  830. }
  831. }
  832. else {
  833. this.subMeshes = new Array();
  834. }
  835. };
  836. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  837. var index;
  838. // Animations
  839. this.getScene().stopAnimation(this);
  840. // Physics
  841. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  842. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  843. }
  844. // Intersections in progress
  845. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  846. var other = this._intersectionsInProgress[index];
  847. var pos = other._intersectionsInProgress.indexOf(this);
  848. other._intersectionsInProgress.splice(pos, 1);
  849. }
  850. this._intersectionsInProgress = [];
  851. // Edges
  852. if (this._edgesRenderer) {
  853. this._edgesRenderer.dispose();
  854. this._edgesRenderer = null;
  855. }
  856. // SubMeshes
  857. this.releaseSubMeshes();
  858. // Remove from scene
  859. this.getScene().removeMesh(this);
  860. if (!doNotRecurse) {
  861. // Particles
  862. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  863. if (this.getScene().particleSystems[index].emitter === this) {
  864. this.getScene().particleSystems[index].dispose();
  865. index--;
  866. }
  867. }
  868. // Children
  869. var objects = this.getScene().meshes.slice(0);
  870. for (index = 0; index < objects.length; index++) {
  871. if (objects[index].parent === this) {
  872. objects[index].dispose();
  873. }
  874. }
  875. }
  876. else {
  877. for (index = 0; index < this.getScene().meshes.length; index++) {
  878. var obj = this.getScene().meshes[index];
  879. if (obj.parent === this) {
  880. obj.parent = null;
  881. obj.computeWorldMatrix(true);
  882. }
  883. }
  884. }
  885. this._onAfterWorldMatrixUpdate = [];
  886. this._isDisposed = true;
  887. // Callback
  888. if (this.onDispose) {
  889. this.onDispose();
  890. }
  891. };
  892. // Statics
  893. AbstractMesh._BILLBOARDMODE_NONE = 0;
  894. AbstractMesh._BILLBOARDMODE_X = 1;
  895. AbstractMesh._BILLBOARDMODE_Y = 2;
  896. AbstractMesh._BILLBOARDMODE_Z = 4;
  897. AbstractMesh._BILLBOARDMODE_ALL = 7;
  898. return AbstractMesh;
  899. })(BABYLON.Node);
  900. BABYLON.AbstractMesh = AbstractMesh;
  901. })(BABYLON || (BABYLON = {}));