babylon.mesh.ts 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. module BABYLON {
  2. export class Mesh extends Node {
  3. // Statics
  4. public static BILLBOARDMODE_NONE = 0;
  5. public static BILLBOARDMODE_X = 1;
  6. public static BILLBOARDMODE_Y = 2;
  7. public static BILLBOARDMODE_Z = 4;
  8. public static BILLBOARDMODE_ALL = 7;
  9. // Members
  10. public position = new BABYLON.Vector3(0, 0, 0);
  11. public rotation = new BABYLON.Vector3(0, 0, 0);
  12. public rotationQuaternion = null;
  13. public scaling = new BABYLON.Vector3(1, 1, 1);
  14. public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE
  15. public material = null;
  16. public isVisible = true;
  17. public isPickable = true;
  18. public visibility = 1.0;
  19. public billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  20. public checkCollisions = false;
  21. public receiveShadows = false;
  22. public _isDisposed = false;
  23. public onDispose = null;
  24. public skeleton = null;
  25. public renderingGroupId = 0;
  26. public infiniteDistance = false;
  27. public showBoundingBox = false;
  28. public subMeshes: SubMesh[];
  29. public delayLoadingFile: string;
  30. // Cache
  31. private _positions = null;
  32. private _localScaling = BABYLON.Matrix.Zero();
  33. private _localRotation = BABYLON.Matrix.Zero();
  34. private _localTranslation = BABYLON.Matrix.Zero();
  35. private _localBillboard = BABYLON.Matrix.Zero();
  36. private _localPivotScaling = BABYLON.Matrix.Zero();
  37. private _localPivotScalingRotation = BABYLON.Matrix.Zero();
  38. private _localWorld = BABYLON.Matrix.Zero();
  39. private _worldMatrix = BABYLON.Matrix.Zero();
  40. private _rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  41. private _collisionsTransformMatrix = BABYLON.Matrix.Zero();
  42. private _collisionsScalingMatrix = BABYLON.Matrix.Zero();
  43. private _absolutePosition = BABYLON.Vector3.Zero();
  44. // Physics
  45. private _physicImpostor = PhysicsEngine.NoImpostor;
  46. private _physicsMass: number;
  47. private _physicsFriction: number;
  48. private _physicRestitution: number;
  49. // Private
  50. private _boundingInfo: BoundingInfo;
  51. private _totalVertices = 0;
  52. private _pivotMatrix = BABYLON.Matrix.Identity();
  53. private _indices = [];
  54. private _renderId = 0;
  55. private _onBeforeRenderCallbacks = [];
  56. private _delayInfo; //ANY
  57. private _vertexStrideSize = 0;
  58. private _animationStarted = false;
  59. private _vertexBuffers;
  60. private _indexBuffer;
  61. private _delayLoadingFunction: (any, Mesh) => void;
  62. constructor(name: string, scene: Scene) {
  63. super(name, scene);
  64. scene.meshes.push(this);
  65. }
  66. public getBoundingInfo(): BoundingInfo {
  67. return this._boundingInfo;
  68. }
  69. public getWorldMatrix(): Matrix {
  70. if (this._currentRenderId !== this.getScene().getRenderId()) {
  71. this.computeWorldMatrix();
  72. }
  73. return this._worldMatrix;
  74. }
  75. public rotate(axis: Vector3, amount: number, space: Space): void {
  76. if (!this.rotationQuaternion) {
  77. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  78. this.rotation = BABYLON.Vector3.Zero();
  79. }
  80. if (!space || space == BABYLON.Space.LOCAL) {
  81. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  82. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  83. }
  84. else {
  85. if (this.parent) {
  86. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  87. invertParentWorldMatrix.invert();
  88. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  89. }
  90. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  91. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  92. }
  93. }
  94. public translate(axis: Vector3, distance: number, space: Space): void {
  95. var displacementVector = axis.scale(distance);
  96. if (!space || space == BABYLON.Space.LOCAL) {
  97. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  98. this.setPositionWithLocalVector(tempV3);
  99. }
  100. else {
  101. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  102. }
  103. }
  104. public getAbsolutePosition(): Vector3 {
  105. this.computeWorldMatrix();
  106. return this._absolutePosition;
  107. }
  108. public setAbsolutePosition(absolutePosition: Vector3): void {
  109. if (!absolutePosition) {
  110. return;
  111. }
  112. var absolutePositionX;
  113. var absolutePositionY;
  114. var absolutePositionZ;
  115. if (absolutePosition.x === undefined) {
  116. if (arguments.length < 3) {
  117. return;
  118. }
  119. absolutePositionX = arguments[0];
  120. absolutePositionY = arguments[1];
  121. absolutePositionZ = arguments[2];
  122. }
  123. else {
  124. absolutePositionX = absolutePosition.x;
  125. absolutePositionY = absolutePosition.y;
  126. absolutePositionZ = absolutePosition.z;
  127. }
  128. if (this.parent) {
  129. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  130. invertParentWorldMatrix.invert();
  131. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  132. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  133. } else {
  134. this.position.x = absolutePositionX;
  135. this.position.y = absolutePositionY;
  136. this.position.z = absolutePositionZ;
  137. }
  138. }
  139. public getTotalVertices(): number {
  140. return this._totalVertices;
  141. }
  142. public getVerticesData(kind): number[] {
  143. return this._vertexBuffers[kind].getData();
  144. }
  145. public getVertexBuffer(kind): VertexBuffer {
  146. return this._vertexBuffers[kind];
  147. }
  148. public isVerticesDataPresent(kind: string): boolean {
  149. if (!this._vertexBuffers) {
  150. if (this._delayInfo) {
  151. return this._delayInfo.indexOf(kind) !== -1;
  152. }
  153. return false;
  154. }
  155. return this._vertexBuffers[kind] !== undefined;
  156. }
  157. public getVerticesDataKinds(): string[] {
  158. var result = [];
  159. if (!this._vertexBuffers && this._delayInfo) {
  160. for (var kind in this._delayInfo) {
  161. result.push(kind);
  162. }
  163. } else {
  164. for (kind in this._vertexBuffers) {
  165. result.push(kind);
  166. }
  167. }
  168. return result;
  169. }
  170. public getTotalIndices(): number {
  171. return this._indices.length;
  172. }
  173. public getIndices(): number[] {
  174. return this._indices;
  175. }
  176. public getVertexStrideSize(): number {
  177. return this._vertexStrideSize;
  178. }
  179. public setPivotMatrix(matrix: Matrix): void {
  180. this._pivotMatrix = matrix;
  181. this._cache.pivotMatrixUpdated = true;
  182. }
  183. public getPivotMatrix(): Matrix {
  184. return this._pivotMatrix;
  185. }
  186. public _isSynchronized(): boolean {
  187. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE)
  188. return false;
  189. if (this._cache.pivotMatrixUpdated) {
  190. return false;
  191. }
  192. if (this.infiniteDistance) {
  193. return false;
  194. }
  195. if (!this._cache.position.equals(this.position))
  196. return false;
  197. if (this.rotationQuaternion) {
  198. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  199. return false;
  200. } else {
  201. if (!this._cache.rotation.equals(this.rotation))
  202. return false;
  203. }
  204. if (!this._cache.scaling.equals(this.scaling))
  205. return false;
  206. return true;
  207. }
  208. public isReady(): boolean {
  209. return this._isReady;
  210. }
  211. public isAnimated(): boolean {
  212. return this._animationStarted;
  213. }
  214. public isDisposed(): boolean {
  215. return this._isDisposed;
  216. }
  217. // Methods
  218. public _initCache() {
  219. super._initCache();
  220. this._cache.localMatrixUpdated = false;
  221. this._cache.position = BABYLON.Vector3.Zero();
  222. this._cache.scaling = BABYLON.Vector3.Zero();
  223. this._cache.rotation = BABYLON.Vector3.Zero();
  224. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  225. }
  226. public markAsDirty(property: string): void {
  227. if (property === "rotation") {
  228. this.rotationQuaternion = null;
  229. }
  230. this._currentRenderId = -1;
  231. }
  232. public refreshBoundingInfo(): void {
  233. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  234. if (!data) {
  235. return;
  236. }
  237. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  238. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  239. for (var index = 0; index < this.subMeshes.length; index++) {
  240. this.subMeshes[index].refreshBoundingInfo();
  241. }
  242. this._updateBoundingInfo();
  243. }
  244. public _updateBoundingInfo(): void {
  245. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
  246. this._boundingInfo._update(this._worldMatrix);
  247. if (!this.subMeshes) {
  248. return;
  249. }
  250. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  251. var subMesh = this.subMeshes[subIndex];
  252. subMesh.updateBoundingInfo(this._worldMatrix);
  253. }
  254. }
  255. public computeWorldMatrix(force?: boolean): Matrix {
  256. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  257. return this._worldMatrix;
  258. }
  259. this._cache.position.copyFrom(this.position);
  260. this._cache.scaling.copyFrom(this.scaling);
  261. this._cache.pivotMatrixUpdated = false;
  262. this._currentRenderId = this.getScene().getRenderId();
  263. // Scaling
  264. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  265. // Rotation
  266. if (this.rotationQuaternion) {
  267. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  268. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  269. } else {
  270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  271. this._cache.rotation.copyFrom(this.rotation);
  272. }
  273. // Translation
  274. if (this.infiniteDistance && !this.parent) {
  275. var camera = this.getScene().activeCamera;
  276. var cameraWorldMatrix = camera.getWorldMatrix();
  277. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  278. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  279. } else {
  280. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  281. }
  282. // Composing transformations
  283. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  284. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  285. // Billboarding
  286. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE) {
  287. var localPosition = this.position.clone();
  288. var zero = this.getScene().activeCamera.position.clone();
  289. if (this.parent && (<any>this.parent).position) {
  290. localPosition.addInPlace((<any>this.parent).position);
  291. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  292. }
  293. if ((this.billboardMode & Mesh.BILLBOARDMODE_ALL) === Mesh.BILLBOARDMODE_ALL) {
  294. zero = this.getScene().activeCamera.position;
  295. } else {
  296. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  297. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  298. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  299. zero.y = localPosition.y + 0.001;
  300. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  301. zero.z = localPosition.z + 0.001;
  302. }
  303. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  304. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  305. this._localBillboard.invert();
  306. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  307. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  308. }
  309. // Local world
  310. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  311. // Parent
  312. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  313. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  314. } else {
  315. this._worldMatrix.copyFrom(this._localWorld);
  316. }
  317. // Bounding info
  318. this._updateBoundingInfo();
  319. // Absolute position
  320. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  321. return this._worldMatrix;
  322. }
  323. public _createGlobalSubMesh(): SubMesh {
  324. if (!this._totalVertices || !this._indices) {
  325. return null;
  326. }
  327. this.subMeshes = [];
  328. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  329. }
  330. public subdivide(count: number): void {
  331. if (count < 1) {
  332. return;
  333. }
  334. var subdivisionSize = this._indices.length / count;
  335. var offset = 0;
  336. this.subMeshes = [];
  337. for (var index = 0; index < count; index++) {
  338. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  339. offset += subdivisionSize;
  340. }
  341. }
  342. public setVerticesData(data: number[], kind: string, updatable?: boolean): void {
  343. if (!this._vertexBuffers) {
  344. this._vertexBuffers = {};
  345. }
  346. if (this._vertexBuffers[kind]) {
  347. this._vertexBuffers[kind].dispose();
  348. }
  349. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  350. if (kind === BABYLON.VertexBuffer.PositionKind) {
  351. this._resetPointsArrayCache();
  352. var stride = this._vertexBuffers[kind].getStrideSize();
  353. this._totalVertices = data.length / stride;
  354. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  355. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  356. this._createGlobalSubMesh();
  357. }
  358. }
  359. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean): void {
  360. if (this._vertexBuffers[kind]) {
  361. this._vertexBuffers[kind].update(data);
  362. if (kind === BABYLON.VertexBuffer.PositionKind) {
  363. this._resetPointsArrayCache();
  364. if (updateExtends) {
  365. var stride = this._vertexBuffers[kind].getStrideSize();
  366. this._totalVertices = data.length / stride;
  367. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  368. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  369. }
  370. }
  371. }
  372. }
  373. public setIndices(indices: number[]): void {
  374. if (this._indexBuffer) {
  375. this.getScene().getEngine()._releaseBuffer(this._indexBuffer);
  376. }
  377. this._indexBuffer = this.getScene().getEngine().createIndexBuffer(indices);
  378. this._indices = indices;
  379. this._createGlobalSubMesh();
  380. }
  381. // ANY
  382. public bindAndDraw(subMesh: SubMesh, effect, wireframe?: boolean): void {
  383. var engine = this.getScene().getEngine();
  384. // Wireframe
  385. var indexToBind = this._indexBuffer;
  386. var useTriangles = true;
  387. if (wireframe) {
  388. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  389. useTriangles = false;
  390. }
  391. // VBOs
  392. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  393. // Draw order
  394. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  395. }
  396. public registerBeforeRender(func: () => void): void {
  397. this._onBeforeRenderCallbacks.push(func);
  398. }
  399. public unregisterBeforeRender(func: () => void): void {
  400. var index = this._onBeforeRenderCallbacks.indexOf(func);
  401. if (index > -1) {
  402. this._onBeforeRenderCallbacks.splice(index, 1);
  403. }
  404. }
  405. public render(subMesh: SubMesh): void {
  406. if (!this._vertexBuffers || !this._indexBuffer) {
  407. return;
  408. }
  409. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  410. this._onBeforeRenderCallbacks[callbackIndex]();
  411. }
  412. // World
  413. var world = this.getWorldMatrix();
  414. // Material
  415. var effectiveMaterial = subMesh.getMaterial();
  416. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  417. return;
  418. }
  419. effectiveMaterial._preBind();
  420. effectiveMaterial.bind(world, this);
  421. // Bind and draw
  422. var engine = this.getScene().getEngine();
  423. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  424. // Unbind
  425. effectiveMaterial.unbind();
  426. }
  427. public getEmittedParticleSystems(): ParticleSystem[] {
  428. var results = new Array<ParticleSystem>();
  429. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  430. var particleSystem = this.getScene().particleSystems[index];
  431. if (particleSystem.emitter === this) {
  432. results.push(particleSystem);
  433. }
  434. }
  435. return results;
  436. }
  437. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  438. var results = new Array<ParticleSystem>();
  439. var descendants = this.getDescendants();
  440. descendants.push(this);
  441. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  442. var particleSystem = this.getScene().particleSystems[index];
  443. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  444. results.push(particleSystem);
  445. }
  446. }
  447. return results;
  448. }
  449. public getChildren(): Node[] {
  450. var results = [];
  451. for (var index = 0; index < this.getScene().meshes.length; index++) {
  452. var mesh = this.getScene().meshes[index];
  453. if (mesh.parent == this) {
  454. results.push(mesh);
  455. }
  456. }
  457. return results;
  458. }
  459. public isInFrustum(frustumPlanes: Plane[]): boolean {
  460. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  461. return false;
  462. }
  463. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  464. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  466. this.getScene()._addPendingData(this);
  467. Tools.LoadFile(this.delayLoadingFile, data => {
  468. this._delayLoadingFunction(JSON.parse(data), this);
  469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  470. this.getScene()._removePendingData(this);
  471. }, () => { }, this.getScene().database);
  472. }
  473. return result;
  474. }
  475. public setMaterialByID(id: string): void {
  476. var materials = this.getScene().materials;
  477. for (var index = 0; index < materials.length; index++) {
  478. if (materials[index].id == id) {
  479. this.material = materials[index];
  480. return;
  481. }
  482. }
  483. // Multi
  484. var multiMaterials = this.getScene().multiMaterials;
  485. for (index = 0; index < multiMaterials.length; index++) {
  486. if (multiMaterials[index].id == id) {
  487. this.material = multiMaterials[index];
  488. return;
  489. }
  490. }
  491. }
  492. public getAnimatables(): IAnimatable[] {
  493. var results = [];
  494. if (this.material) {
  495. results.push(this.material);
  496. }
  497. return results;
  498. }
  499. // Geometry
  500. public setPositionWithLocalVector(vector3: Vector3): void {
  501. this.computeWorldMatrix();
  502. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  503. }
  504. public getPositionExpressedInLocalSpace(): Vector3 {
  505. this.computeWorldMatrix();
  506. var invLocalWorldMatrix = this._localWorld.clone();
  507. invLocalWorldMatrix.invert();
  508. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  509. }
  510. public locallyTranslate(vector3: Vector3): void {
  511. this.computeWorldMatrix();
  512. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  513. }
  514. public bakeTransformIntoVertices(transform: Matrix): void {
  515. // Position
  516. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  517. return;
  518. }
  519. this._resetPointsArrayCache();
  520. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  521. var temp = [];
  522. for (var index = 0; index < data.length; index += 3) {
  523. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  524. }
  525. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  526. // Normals
  527. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  528. return;
  529. }
  530. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  531. for (index = 0; index < data.length; index += 3) {
  532. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  533. }
  534. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  535. }
  536. public lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void {
  537. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  538. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  539. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  540. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  541. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  542. /// <returns>Mesh oriented towards targetMesh</returns>
  543. yawCor = yawCor || 0; // default to zero if undefined
  544. pitchCor = pitchCor || 0;
  545. rollCor = rollCor || 0;
  546. var dv = targetPoint.subtract(this.position);
  547. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  548. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  549. var pitch = Math.atan2(dv.y, len);
  550. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  551. }
  552. // Cache
  553. public _resetPointsArrayCache(): void {
  554. this._positions = null;
  555. }
  556. public _generatePointsArray(): void {
  557. if (this._positions)
  558. return;
  559. this._positions = [];
  560. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  561. for (var index = 0; index < data.length; index += 3) {
  562. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  563. }
  564. }
  565. // Collisions
  566. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void {
  567. this._generatePointsArray();
  568. // Transformation
  569. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  570. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  571. subMesh._lastColliderWorldVertices = [];
  572. subMesh._trianglePlanes = [];
  573. var start = subMesh.verticesStart;
  574. var end = (subMesh.verticesStart + subMesh.verticesCount);
  575. for (var i = start; i < end; i++) {
  576. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  577. }
  578. }
  579. // Collide
  580. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  581. }
  582. public _processCollisionsForSubModels(collider: Collider, transformMatrix: Matrix): void {
  583. for (var index = 0; index < this.subMeshes.length; index++) {
  584. var subMesh = this.subMeshes[index];
  585. // Bounding test
  586. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  587. continue;
  588. this._collideForSubMesh(subMesh, transformMatrix, collider);
  589. }
  590. }
  591. public _checkCollision(collider: Collider): void {
  592. // Bounding box test
  593. if (!this._boundingInfo._checkCollision(collider))
  594. return;
  595. // Transformation matrix
  596. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  597. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  598. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  599. }
  600. public intersectsMesh(mesh: Mesh, precise?: boolean): boolean {
  601. if (!this._boundingInfo || !mesh._boundingInfo) {
  602. return false;
  603. }
  604. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  605. }
  606. public intersectsPoint(point: Vector3): boolean {
  607. if (!this._boundingInfo) {
  608. return false;
  609. }
  610. return this._boundingInfo.intersectsPoint(point);
  611. }
  612. // Picking
  613. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  614. var pickingInfo = new BABYLON.PickingInfo();
  615. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  616. return pickingInfo;
  617. }
  618. this._generatePointsArray();
  619. var intersectInfo: IntersectionInfo = null;
  620. for (var index = 0; index < this.subMeshes.length; index++) {
  621. var subMesh = this.subMeshes[index];
  622. // Bounding test
  623. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  624. continue;
  625. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  626. if (currentIntersectInfo) {
  627. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  628. intersectInfo = currentIntersectInfo;
  629. if (fastCheck) {
  630. break;
  631. }
  632. }
  633. }
  634. }
  635. if (intersectInfo) {
  636. // Get picked point
  637. var world = this.getWorldMatrix();
  638. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  639. var direction = ray.direction.clone();
  640. direction.normalize();
  641. direction = direction.scale(intersectInfo.distance);
  642. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  643. var pickedPoint = worldOrigin.add(worldDirection);
  644. // Return result
  645. pickingInfo.hit = true;
  646. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  647. pickingInfo.pickedPoint = pickedPoint;
  648. pickingInfo.pickedMesh = this;
  649. pickingInfo.bu = intersectInfo.bu;
  650. pickingInfo.bv = intersectInfo.bv;
  651. pickingInfo.faceId = intersectInfo.faceId;
  652. return pickingInfo;
  653. }
  654. return pickingInfo;
  655. }
  656. // Clone
  657. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  658. var result = new BABYLON.Mesh(name, this.getScene());
  659. // Buffers
  660. result._vertexBuffers = this._vertexBuffers;
  661. for (var kind in result._vertexBuffers) {
  662. result._vertexBuffers[kind]._buffer.references++;
  663. }
  664. result._indexBuffer = this._indexBuffer;
  665. this._indexBuffer.references++;
  666. // Deep copy
  667. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  668. // Bounding info
  669. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  670. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  671. // Material
  672. result.material = this.material;
  673. // Parent
  674. if (newParent) {
  675. result.parent = newParent;
  676. }
  677. if (!doNotCloneChildren) {
  678. // Children
  679. for (var index = 0; index < this.getScene().meshes.length; index++) {
  680. var mesh = this.getScene().meshes[index];
  681. if (mesh.parent == this) {
  682. mesh.clone(mesh.name, result);
  683. }
  684. }
  685. }
  686. // Particles
  687. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  688. var system = this.getScene().particleSystems[index];
  689. if (system.emitter == this) {
  690. system.clone(system.name, result);
  691. }
  692. }
  693. result.computeWorldMatrix(true);
  694. return result;
  695. }
  696. // Dispose
  697. public dispose(doNotRecurse?: boolean): void {
  698. if (this._vertexBuffers) {
  699. for (var vbKind in this._vertexBuffers) {
  700. this._vertexBuffers[vbKind].dispose();
  701. }
  702. this._vertexBuffers = null;
  703. }
  704. if (this._indexBuffer) {
  705. this.getScene().getEngine()._releaseBuffer(this._indexBuffer);
  706. this._indexBuffer = null;
  707. }
  708. // Physics
  709. if (this.getPhysicsImpostor() != PhysicsEngine.NoImpostor) {
  710. this.setPhysicsState({ impostor: PhysicsEngine.NoImpostor });
  711. }
  712. // Remove from scene
  713. var index = this.getScene().meshes.indexOf(this);
  714. this.getScene().meshes.splice(index, 1);
  715. if (!doNotRecurse) {
  716. // Particles
  717. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  718. if (this.getScene().particleSystems[index].emitter == this) {
  719. this.getScene().particleSystems[index].dispose();
  720. index--;
  721. }
  722. }
  723. // Children
  724. var objects = this.getScene().meshes.slice(0);
  725. for (index = 0; index < objects.length; index++) {
  726. if (objects[index].parent == this) {
  727. objects[index].dispose();
  728. }
  729. }
  730. } else {
  731. for (index = 0; index < this.getScene().meshes.length; index++) {
  732. var obj = this.getScene().meshes[index];
  733. if (obj.parent === this) {
  734. obj.parent = null;
  735. obj.computeWorldMatrix(true);
  736. }
  737. }
  738. }
  739. this._isDisposed = true;
  740. // Callback
  741. if (this.onDispose) {
  742. this.onDispose();
  743. }
  744. }
  745. // Physics
  746. public setPhysicsState(options): void {
  747. var physicsEngine = this.getScene().getPhysicsEngine();
  748. if (!physicsEngine) {
  749. return;
  750. }
  751. options.impostor = options.impostor || PhysicsEngine.NoImpostor;
  752. options.mass = options.mass || 0;
  753. options.friction = options.friction || 0.2;
  754. options.restitution = options.restitution || 0.9;
  755. this._physicImpostor = options.impostor;
  756. this._physicsMass = options.mass;
  757. this._physicsFriction = options.friction;
  758. this._physicRestitution = options.restitution;
  759. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  760. physicsEngine._unregisterMesh(this);
  761. return;
  762. }
  763. physicsEngine._registerMesh(this, options);
  764. }
  765. public getPhysicsImpostor(): number {
  766. if (!this._physicImpostor) {
  767. return BABYLON.PhysicsEngine.NoImpostor;
  768. }
  769. return this._physicImpostor;
  770. }
  771. public getPhysicsMass(): number {
  772. if (!this._physicsMass) {
  773. return 0;
  774. }
  775. return this._physicsMass;
  776. }
  777. public getPhysicsFriction(): number {
  778. if (!this._physicsFriction) {
  779. return 0;
  780. }
  781. return this._physicsFriction;
  782. }
  783. public getPhysicsRestitution(): number {
  784. if (!this._physicRestitution) {
  785. return 0;
  786. }
  787. return this._physicRestitution;
  788. }
  789. public applyImpulse(force: Vector3, contactPoint: Vector3): void {
  790. if (!this._physicImpostor) {
  791. return;
  792. }
  793. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  794. }
  795. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3): void {
  796. if (!this._physicImpostor) {
  797. return;
  798. }
  799. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
  800. }
  801. // Geometric tools
  802. public convertToFlatShadedMesh(): void {
  803. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  804. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  805. var kinds = this.getVerticesDataKinds();
  806. var vbs = [];
  807. var data = [];
  808. var newdata = [];
  809. var updatableNormals = false;
  810. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  811. var kind = kinds[kindIndex];
  812. if (kind === BABYLON.VertexBuffer.NormalKind) {
  813. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  814. kinds.splice(kindIndex, 1);
  815. kindIndex--;
  816. continue;
  817. }
  818. vbs[kind] = this.getVertexBuffer(kind);
  819. data[kind] = vbs[kind].getData();
  820. newdata[kind] = [];
  821. }
  822. // Save previous submeshes
  823. var previousSubmeshes = this.subMeshes.slice(0);
  824. var indices = this.getIndices();
  825. // Generating unique vertices per face
  826. for (index = 0; index < indices.length; index++) {
  827. var vertexIndex = indices[index];
  828. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  829. kind = kinds[kindIndex];
  830. var stride = vbs[kind].getStrideSize();
  831. for (var offset = 0; offset < stride; offset++) {
  832. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  833. }
  834. }
  835. }
  836. // Updating faces & normal
  837. var normals = [];
  838. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  839. for (var index = 0; index < indices.length; index += 3) {
  840. indices[index] = index;
  841. indices[index + 1] = index + 1;
  842. indices[index + 2] = index + 2;
  843. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  844. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  845. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  846. var p1p2 = p1.subtract(p2);
  847. var p3p2 = p3.subtract(p2);
  848. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  849. // Store same normals for every vertex
  850. for (var localIndex = 0; localIndex < 3; localIndex++) {
  851. normals.push(normal.x);
  852. normals.push(normal.y);
  853. normals.push(normal.z);
  854. }
  855. }
  856. this.setIndices(indices);
  857. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  858. // Updating vertex buffers
  859. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  860. kind = kinds[kindIndex];
  861. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  862. }
  863. // Updating submeshes
  864. this.subMeshes = [];
  865. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  866. var previousOne = previousSubmeshes[submeshIndex];
  867. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  868. }
  869. }
  870. // Statics
  871. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  872. var box = new BABYLON.Mesh(name, scene);
  873. var vertexData = BABYLON.VertexData.CreateBox(size);
  874. vertexData.applyToMesh(box, updatable);
  875. return box;
  876. }
  877. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  878. var sphere = new BABYLON.Mesh(name, scene);
  879. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  880. vertexData.applyToMesh(sphere, updatable);
  881. return sphere;
  882. }
  883. // Cylinder and cone (Code inspired by SharpDX.org)
  884. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  885. var cylinder = new BABYLON.Mesh(name, scene);
  886. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  887. vertexData.applyToMesh(cylinder, updatable);
  888. return cylinder;
  889. }
  890. // Torus (Code from SharpDX.org)
  891. public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  892. var torus = new BABYLON.Mesh(name, scene);
  893. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  894. vertexData.applyToMesh(torus, updatable);
  895. return torus;
  896. }
  897. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  898. var torusKnot = new BABYLON.Mesh(name, scene);
  899. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  900. vertexData.applyToMesh(torusKnot, updatable);
  901. return torusKnot;
  902. }
  903. // Plane & ground
  904. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  905. var plane = new BABYLON.Mesh(name, scene);
  906. var vertexData = BABYLON.VertexData.CreatePlane(size);
  907. vertexData.applyToMesh(plane, updatable);
  908. return plane;
  909. }
  910. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  911. var ground = new BABYLON.Mesh(name, scene);
  912. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  913. vertexData.applyToMesh(ground, updatable);
  914. return ground;
  915. }
  916. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): Mesh {
  917. var ground = new BABYLON.Mesh(name, scene);
  918. var onload = img => {
  919. // Getting height map data
  920. var canvas = document.createElement("canvas");
  921. var context = canvas.getContext("2d");
  922. var heightMapWidth = img.width;
  923. var heightMapHeight = img.height;
  924. canvas.width = heightMapWidth;
  925. canvas.height = heightMapHeight;
  926. context.drawImage(img, 0, 0);
  927. // Create VertexData from map data
  928. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  929. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  930. vertexData.applyToMesh(ground, updatable);
  931. ground._isReady = true;
  932. };
  933. Tools.LoadImage(url, onload, () => {}, scene.database);
  934. ground._isReady = false;
  935. return ground;
  936. }
  937. // Tools
  938. public static MinMax(meshes: Mesh[]): {min: Vector3; max: Vector3} {
  939. var minVector;
  940. var maxVector;
  941. for (var i in meshes) {
  942. var mesh = meshes[i];
  943. var boundingBox = mesh.getBoundingInfo().boundingBox;
  944. if (!minVector) {
  945. minVector = boundingBox.minimumWorld;
  946. maxVector = boundingBox.maximumWorld;
  947. continue;
  948. }
  949. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  950. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  951. }
  952. return {
  953. min: minVector,
  954. max: maxVector
  955. };
  956. }
  957. public static Center(meshesOrMinMaxVector): Vector3 {
  958. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  959. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  960. }
  961. }
  962. }