babylon.abstractMesh.js 44 KB

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