babylon.mesh.ts 46 KB

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