babylon.abstractMesh.ts 32 KB

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