babylon.abstractMesh.ts 35 KB

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