babylon.abstractMesh.ts 37 KB

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