babylon.abstractMesh.ts 36 KB

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