babylon.mesh.ts 45 KB

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