babylon.mesh.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances: InstancedMesh[];
  5. public renderSelf = true;
  6. }
  7. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  8. // Members
  9. public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10. public instances = new Array<InstancedMesh>();
  11. public delayLoadingFile: string;
  12. // Private
  13. public _geometry: Geometry;
  14. private _onBeforeRenderCallbacks = [];
  15. private _delayInfo; //ANY
  16. private _delayLoadingFunction: (any, Mesh) => void;
  17. public _visibleInstances: any = {};
  18. private _renderIdForInstances = -1;
  19. private _batchCache = new _InstancesBatch();
  20. private _worldMatricesInstancesBuffer: WebGLBuffer;
  21. private _worldMatricesInstancesArray: Float32Array;
  22. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23. constructor(name: string, scene: Scene) {
  24. super(name, scene);
  25. }
  26. public getTotalVertices(): number {
  27. if (!this._geometry) {
  28. return 0;
  29. }
  30. return this._geometry.getTotalVertices();
  31. }
  32. public getVerticesData(kind: string): number[] {
  33. if (!this._geometry) {
  34. return null;
  35. }
  36. return this._geometry.getVerticesData(kind);
  37. }
  38. public getVertexBuffer(kind): VertexBuffer {
  39. if (!this._geometry) {
  40. return undefined;
  41. }
  42. return this._geometry.getVertexBuffer(kind);
  43. }
  44. public isVerticesDataPresent(kind: string): boolean {
  45. if (!this._geometry) {
  46. if (this._delayInfo) {
  47. return this._delayInfo.indexOf(kind) !== -1;
  48. }
  49. return false;
  50. }
  51. return this._geometry.isVerticesDataPresent(kind);
  52. }
  53. public getVerticesDataKinds(): string[] {
  54. if (!this._geometry) {
  55. var result = [];
  56. if (this._delayInfo) {
  57. for (var kind in this._delayInfo) {
  58. result.push(kind);
  59. }
  60. }
  61. return result;
  62. }
  63. return this._geometry.getVerticesDataKinds();
  64. }
  65. public getTotalIndices(): number {
  66. if (!this._geometry) {
  67. return 0;
  68. }
  69. return this._geometry.getTotalIndices();
  70. }
  71. public getIndices(): number[] {
  72. if (!this._geometry) {
  73. return [];
  74. }
  75. return this._geometry.getIndices();
  76. }
  77. public isReady(): boolean {
  78. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  79. return false;
  80. }
  81. return super.isReady();
  82. }
  83. public isDisposed(): boolean {
  84. return this._isDisposed;
  85. }
  86. // Methods
  87. public _preActivate(): void {
  88. this._visibleInstances = null;
  89. }
  90. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  91. if (!this._visibleInstances) {
  92. this._visibleInstances = {};
  93. this._visibleInstances.defaultRenderId = renderId;
  94. this._visibleInstances.selfDefaultRenderId = this._renderId;
  95. }
  96. if (!this._visibleInstances[renderId]) {
  97. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  98. }
  99. this._visibleInstances[renderId].push(instance);
  100. }
  101. public refreshBoundingInfo(): void {
  102. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103. if (data) {
  104. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  105. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  106. }
  107. if (this.subMeshes) {
  108. for (var index = 0; index < this.subMeshes.length; index++) {
  109. this.subMeshes[index].refreshBoundingInfo();
  110. }
  111. }
  112. this._updateBoundingInfo();
  113. }
  114. public _createGlobalSubMesh(): SubMesh {
  115. var totalVertices = this.getTotalVertices();
  116. if (!totalVertices || !this.getIndices()) {
  117. return null;
  118. }
  119. this.releaseSubMeshes();
  120. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  121. }
  122. public subdivide(count: number): void {
  123. if (count < 1) {
  124. return;
  125. }
  126. var totalIndices = this.getTotalIndices();
  127. var subdivisionSize = (totalIndices / count) | 0;
  128. var offset = 0;
  129. // Ensure that subdivisionSize is a multiple of 3
  130. while (subdivisionSize % 3 != 0) {
  131. subdivisionSize++;
  132. }
  133. this.releaseSubMeshes();
  134. for (var index = 0; index < count; index++) {
  135. if (offset >= totalIndices) {
  136. break;
  137. }
  138. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  139. offset += subdivisionSize;
  140. }
  141. this.synchronizeInstances();
  142. }
  143. public setVerticesData(kind: any, data: any, updatable?: boolean): void {
  144. if (kind instanceof Array) {
  145. var temp = data;
  146. data = kind;
  147. kind = temp;
  148. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  149. }
  150. if (!this._geometry) {
  151. var vertexData = new BABYLON.VertexData();
  152. vertexData.set(data, kind);
  153. var scene = this.getScene();
  154. new BABYLON.Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  155. }
  156. else {
  157. this._geometry.setVerticesData(kind, data, updatable);
  158. }
  159. }
  160. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  161. if (!this._geometry) {
  162. return;
  163. }
  164. if (!makeItUnique) {
  165. this._geometry.updateVerticesData(kind, data, updateExtends);
  166. }
  167. else {
  168. this.makeGeometryUnique();
  169. this.updateVerticesData(kind, data, updateExtends, false);
  170. }
  171. }
  172. public makeGeometryUnique() {
  173. if (!this._geometry) {
  174. return;
  175. }
  176. var geometry = this._geometry.copy(Geometry.RandomId());
  177. geometry.applyToMesh(this);
  178. }
  179. public setIndices(indices: number[]): void {
  180. if (!this._geometry) {
  181. var vertexData = new BABYLON.VertexData();
  182. vertexData.indices = indices;
  183. var scene = this.getScene();
  184. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  185. }
  186. else {
  187. this._geometry.setIndices(indices);
  188. }
  189. }
  190. public _bind(subMesh: SubMesh, effect: Effect, wireframe?: boolean): void {
  191. var engine = this.getScene().getEngine();
  192. // Wireframe
  193. var indexToBind = this._geometry.getIndexBuffer();
  194. if (wireframe) {
  195. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  196. }
  197. // VBOs
  198. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  199. }
  200. public _draw(subMesh: SubMesh, useTriangles: boolean, instancesCount?: number): void {
  201. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  202. return;
  203. }
  204. var engine = this.getScene().getEngine();
  205. // Draw order
  206. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  207. }
  208. public registerBeforeRender(func: () => void): void {
  209. this._onBeforeRenderCallbacks.push(func);
  210. }
  211. public unregisterBeforeRender(func: () => void): void {
  212. var index = this._onBeforeRenderCallbacks.indexOf(func);
  213. if (index > -1) {
  214. this._onBeforeRenderCallbacks.splice(index, 1);
  215. }
  216. }
  217. public _getInstancesRenderList(): _InstancesBatch {
  218. var scene = this.getScene();
  219. this._batchCache.mustReturn = false;
  220. this._batchCache.renderSelf = true;
  221. this._batchCache.visibleInstances = null;
  222. if (this._visibleInstances) {
  223. var currentRenderId = scene.getRenderId();
  224. this._batchCache.visibleInstances = this._visibleInstances[currentRenderId];
  225. var selfRenderId = this._renderId;
  226. if (!this._batchCache.visibleInstances && this._visibleInstances.defaultRenderId) {
  227. this._batchCache.visibleInstances = this._visibleInstances[this._visibleInstances.defaultRenderId];
  228. currentRenderId = this._visibleInstances.defaultRenderId;
  229. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  230. }
  231. if (this._batchCache.visibleInstances && this._batchCache.visibleInstances.length) {
  232. if (this._renderIdForInstances === currentRenderId) {
  233. this._batchCache.mustReturn = true;
  234. return this._batchCache;
  235. }
  236. if (currentRenderId !== selfRenderId) {
  237. this._batchCache.renderSelf = false;
  238. }
  239. }
  240. this._renderIdForInstances = currentRenderId;
  241. }
  242. return this._batchCache;
  243. }
  244. public _renderWithInstances(subMesh: SubMesh, wireFrame: boolean, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  245. var matricesCount = this.instances.length + 1;
  246. var bufferSize = matricesCount * 16 * 4;
  247. while (this._instancesBufferSize < bufferSize) {
  248. this._instancesBufferSize *= 2;
  249. }
  250. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  251. if (this._worldMatricesInstancesBuffer) {
  252. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  253. }
  254. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  255. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  256. }
  257. var offset = 0;
  258. var instancesCount = 0;
  259. var world = this.getWorldMatrix();
  260. if (batch.renderSelf) {
  261. world.copyToArray(this._worldMatricesInstancesArray, offset);
  262. offset += 16;
  263. instancesCount++;
  264. }
  265. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances.length; instanceIndex++) {
  266. var instance = batch.visibleInstances[instanceIndex];
  267. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  268. offset += 16;
  269. instancesCount++;
  270. }
  271. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  272. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  273. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  274. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  275. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  276. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  277. this._draw(subMesh, !wireFrame, instancesCount);
  278. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  279. }
  280. public render(subMesh: SubMesh): void {
  281. var scene = this.getScene();
  282. // Managing instances
  283. var batch = this._getInstancesRenderList();
  284. if (batch.mustReturn) {
  285. return;
  286. }
  287. // Checking geometry state
  288. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  289. return;
  290. }
  291. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  292. this._onBeforeRenderCallbacks[callbackIndex]();
  293. }
  294. var engine = scene.getEngine();
  295. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  296. // Material
  297. var effectiveMaterial = subMesh.getMaterial();
  298. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  299. return;
  300. }
  301. effectiveMaterial._preBind();
  302. var effect = effectiveMaterial.getEffect();
  303. // Bind
  304. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  305. this._bind(subMesh, effect, wireFrame);
  306. var world = this.getWorldMatrix();
  307. effectiveMaterial.bind(world, this);
  308. // Instances rendering
  309. if (hardwareInstancedRendering) {
  310. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  311. } else {
  312. if (batch.renderSelf) {
  313. // Draw
  314. this._draw(subMesh, !wireFrame);
  315. }
  316. if (batch.visibleInstances) {
  317. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances.length; instanceIndex++) {
  318. var instance = batch.visibleInstances[instanceIndex];
  319. // World
  320. world = instance.getWorldMatrix();
  321. effectiveMaterial.bindOnlyWorldMatrix(world);
  322. // Draw
  323. this._draw(subMesh, !wireFrame);
  324. }
  325. }
  326. }
  327. // Unbind
  328. effectiveMaterial.unbind();
  329. }
  330. public getEmittedParticleSystems(): ParticleSystem[] {
  331. var results = new Array<ParticleSystem>();
  332. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  333. var particleSystem = this.getScene().particleSystems[index];
  334. if (particleSystem.emitter === this) {
  335. results.push(particleSystem);
  336. }
  337. }
  338. return results;
  339. }
  340. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  341. var results = new Array<ParticleSystem>();
  342. var descendants = this.getDescendants();
  343. descendants.push(this);
  344. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  345. var particleSystem = this.getScene().particleSystems[index];
  346. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  347. results.push(particleSystem);
  348. }
  349. }
  350. return results;
  351. }
  352. public getChildren(): Node[] {
  353. var results = [];
  354. for (var index = 0; index < this.getScene().meshes.length; index++) {
  355. var mesh = this.getScene().meshes[index];
  356. if (mesh.parent == this) {
  357. results.push(mesh);
  358. }
  359. }
  360. return results;
  361. }
  362. public _checkDelayState(): void {
  363. var that = this;
  364. var scene = this.getScene();
  365. if (this._geometry) {
  366. this._geometry.load(scene);
  367. }
  368. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  369. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  370. scene._addPendingData(that);
  371. BABYLON.Tools.LoadFile(this.delayLoadingFile, data => {
  372. this._delayLoadingFunction(JSON.parse(data), this);
  373. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  374. scene._removePendingData(this);
  375. }, () => { }, scene.database);
  376. }
  377. }
  378. public isInFrustum(frustumPlanes: Plane[]): boolean {
  379. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  380. return false;
  381. }
  382. if (!super.isInFrustum(frustumPlanes)) {
  383. return false;
  384. }
  385. this._checkDelayState();
  386. return true;
  387. }
  388. public setMaterialByID(id: string): void {
  389. var materials = this.getScene().materials;
  390. for (var index = 0; index < materials.length; index++) {
  391. if (materials[index].id == id) {
  392. this.material = materials[index];
  393. return;
  394. }
  395. }
  396. // Multi
  397. var multiMaterials = this.getScene().multiMaterials;
  398. for (index = 0; index < multiMaterials.length; index++) {
  399. if (multiMaterials[index].id == id) {
  400. this.material = multiMaterials[index];
  401. return;
  402. }
  403. }
  404. }
  405. public getAnimatables(): IAnimatable[] {
  406. var results = [];
  407. if (this.material) {
  408. results.push(this.material);
  409. }
  410. return results;
  411. }
  412. // Geometry
  413. public bakeTransformIntoVertices(transform: Matrix): void {
  414. // Position
  415. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  416. return;
  417. }
  418. this._resetPointsArrayCache();
  419. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  420. var temp = [];
  421. for (var index = 0; index < data.length; index += 3) {
  422. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  423. }
  424. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  425. // Normals
  426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  427. return;
  428. }
  429. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  430. for (index = 0; index < data.length; index += 3) {
  431. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  432. }
  433. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  434. }
  435. // Cache
  436. public _resetPointsArrayCache(): void {
  437. this._positions = null;
  438. }
  439. public _generatePointsArray(): boolean {
  440. if (this._positions)
  441. return true;
  442. this._positions = [];
  443. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  444. if (!data) {
  445. return false;
  446. }
  447. for (var index = 0; index < data.length; index += 3) {
  448. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  449. }
  450. return true;
  451. }
  452. // Clone
  453. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  454. var result = new BABYLON.Mesh(name, this.getScene());
  455. // Geometry
  456. this._geometry.applyToMesh(result);
  457. // Deep copy
  458. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  459. // Material
  460. result.material = this.material;
  461. // Parent
  462. if (newParent) {
  463. result.parent = newParent;
  464. }
  465. if (!doNotCloneChildren) {
  466. // Children
  467. for (var index = 0; index < this.getScene().meshes.length; index++) {
  468. var mesh = this.getScene().meshes[index];
  469. if (mesh.parent == this) {
  470. mesh.clone(mesh.name, result);
  471. }
  472. }
  473. }
  474. // Particles
  475. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  476. var system = this.getScene().particleSystems[index];
  477. if (system.emitter == this) {
  478. system.clone(system.name, result);
  479. }
  480. }
  481. result.computeWorldMatrix(true);
  482. return result;
  483. }
  484. // Dispose
  485. public dispose(doNotRecurse?: boolean): void {
  486. if (this._geometry) {
  487. this._geometry.releaseForMesh(this, true);
  488. }
  489. // Instances
  490. if (this._worldMatricesInstancesBuffer) {
  491. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  492. this._worldMatricesInstancesBuffer = null;
  493. }
  494. while (this.instances.length) {
  495. this.instances[0].dispose();
  496. }
  497. super.dispose(doNotRecurse);
  498. }
  499. // Geometric tools
  500. public convertToFlatShadedMesh(): void {
  501. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  502. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  503. var kinds = this.getVerticesDataKinds();
  504. var vbs = [];
  505. var data = [];
  506. var newdata = [];
  507. var updatableNormals = false;
  508. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  509. var kind = kinds[kindIndex];
  510. var vertexBuffer = this.getVertexBuffer(kind);
  511. if (kind === BABYLON.VertexBuffer.NormalKind) {
  512. updatableNormals = vertexBuffer.isUpdatable();
  513. kinds.splice(kindIndex, 1);
  514. kindIndex--;
  515. continue;
  516. }
  517. vbs[kind] = vertexBuffer;
  518. data[kind] = vbs[kind].getData();
  519. newdata[kind] = [];
  520. }
  521. // Save previous submeshes
  522. var previousSubmeshes = this.subMeshes.slice(0);
  523. var indices = this.getIndices();
  524. var totalIndices = this.getTotalIndices();
  525. // Generating unique vertices per face
  526. for (index = 0; index < totalIndices; index++) {
  527. var vertexIndex = indices[index];
  528. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  529. kind = kinds[kindIndex];
  530. var stride = vbs[kind].getStrideSize();
  531. for (var offset = 0; offset < stride; offset++) {
  532. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  533. }
  534. }
  535. }
  536. // Updating faces & normal
  537. var normals = [];
  538. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  539. for (var index = 0; index < totalIndices; index += 3) {
  540. indices[index] = index;
  541. indices[index + 1] = index + 1;
  542. indices[index + 2] = index + 2;
  543. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  544. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  545. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  546. var p1p2 = p1.subtract(p2);
  547. var p3p2 = p3.subtract(p2);
  548. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  549. // Store same normals for every vertex
  550. for (var localIndex = 0; localIndex < 3; localIndex++) {
  551. normals.push(normal.x);
  552. normals.push(normal.y);
  553. normals.push(normal.z);
  554. }
  555. }
  556. this.setIndices(indices);
  557. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  558. // Updating vertex buffers
  559. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  560. kind = kinds[kindIndex];
  561. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  562. }
  563. // Updating submeshes
  564. this.releaseSubMeshes();
  565. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  566. var previousOne = previousSubmeshes[submeshIndex];
  567. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  568. }
  569. this.synchronizeInstances();
  570. }
  571. // Instances
  572. public createInstance(name: string): InstancedMesh {
  573. return new InstancedMesh(name, this);
  574. }
  575. public synchronizeInstances(): void {
  576. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  577. var instance = this.instances[instanceIndex];
  578. instance._syncSubMeshes();
  579. }
  580. }
  581. // Statics
  582. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  583. var box = new BABYLON.Mesh(name, scene);
  584. var vertexData = BABYLON.VertexData.CreateBox(size);
  585. vertexData.applyToMesh(box, updatable);
  586. return box;
  587. }
  588. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  589. var sphere = new BABYLON.Mesh(name, scene);
  590. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  591. vertexData.applyToMesh(sphere, updatable);
  592. return sphere;
  593. }
  594. // Cylinder and cone (Code inspired by SharpDX.org)
  595. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  596. var cylinder = new BABYLON.Mesh(name, scene);
  597. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  598. vertexData.applyToMesh(cylinder, updatable);
  599. return cylinder;
  600. }
  601. // Torus (Code from SharpDX.org)
  602. public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  603. var torus = new BABYLON.Mesh(name, scene);
  604. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  605. vertexData.applyToMesh(torus, updatable);
  606. return torus;
  607. }
  608. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  609. var torusKnot = new BABYLON.Mesh(name, scene);
  610. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  611. vertexData.applyToMesh(torusKnot, updatable);
  612. return torusKnot;
  613. }
  614. // Plane & ground
  615. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  616. var plane = new BABYLON.Mesh(name, scene);
  617. var vertexData = BABYLON.VertexData.CreatePlane(size);
  618. vertexData.applyToMesh(plane, updatable);
  619. return plane;
  620. }
  621. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  622. var ground = new BABYLON.GroundMesh(name, scene);
  623. ground._setReady(false);
  624. ground._subdivisions = subdivisions;
  625. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  626. vertexData.applyToMesh(ground, updatable);
  627. ground._setReady(true);
  628. return ground;
  629. }
  630. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): Mesh {
  631. var ground = new BABYLON.GroundMesh(name, scene);
  632. ground._subdivisions = subdivisions;
  633. ground._setReady(false);
  634. var onload = img => {
  635. // Getting height map data
  636. var canvas = document.createElement("canvas");
  637. var context = canvas.getContext("2d");
  638. var heightMapWidth = img.width;
  639. var heightMapHeight = img.height;
  640. canvas.width = heightMapWidth;
  641. canvas.height = heightMapHeight;
  642. context.drawImage(img, 0, 0);
  643. // Create VertexData from map data
  644. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  645. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  646. vertexData.applyToMesh(ground, updatable);
  647. ground._setReady(true);
  648. };
  649. Tools.LoadImage(url, onload, () => { }, scene.database);
  650. return ground;
  651. }
  652. // Tools
  653. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  654. var minVector = null;
  655. var maxVector = null;
  656. for (var i in meshes) {
  657. var mesh = meshes[i];
  658. var boundingBox = mesh.getBoundingInfo().boundingBox;
  659. if (!minVector) {
  660. minVector = boundingBox.minimumWorld;
  661. maxVector = boundingBox.maximumWorld;
  662. continue;
  663. }
  664. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  665. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  666. }
  667. return {
  668. min: minVector,
  669. max: maxVector
  670. };
  671. }
  672. public static Center(meshesOrMinMaxVector): Vector3 {
  673. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  674. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  675. }
  676. }
  677. }