babylon.abstractMesh.ts 39 KB

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