babylon.abstractMesh.ts 42 KB

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