babylon.mesh.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances = new Array<Array<InstancedMesh>>();
  5. public renderSelf = new Array<boolean>();
  6. }
  7. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  8. // Consts
  9. public static _FRONTSIDE: number = 0;
  10. public static _BACKSIDE: number = 1;
  11. public static _DOUBLESIDE: number = 2;
  12. public static _DEFAULTSIDE: number = 0;
  13. public static get FRONTSIDE(): number {
  14. return Mesh._FRONTSIDE;
  15. }
  16. public static get BACKSIDE(): number {
  17. return Mesh._BACKSIDE;
  18. }
  19. public static get DOUBLESIDE(): number {
  20. return Mesh._DOUBLESIDE;
  21. }
  22. public static get DEFAULTSIDE(): number {
  23. return Mesh._DEFAULTSIDE;
  24. }
  25. // Members
  26. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  27. public instances = new Array<InstancedMesh>();
  28. public delayLoadingFile: string;
  29. public _binaryInfo: any;
  30. private _LODLevels = new Array<Internals.MeshLODLevel>();
  31. // Private
  32. public _geometry: Geometry;
  33. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  34. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  35. public _delayInfo; //ANY
  36. public _delayLoadingFunction: (any, Mesh) => void;
  37. public _visibleInstances: any = {};
  38. private _renderIdForInstances = new Array<number>();
  39. private _batchCache = new _InstancesBatch();
  40. private _worldMatricesInstancesBuffer: WebGLBuffer;
  41. private _worldMatricesInstancesArray: Float32Array;
  42. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  43. public _shouldGenerateFlatShading: boolean;
  44. private _preActivateId: number;
  45. /**
  46. * @constructor
  47. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  48. * @param {Scene} scene - The scene to add this mesh to.
  49. * @param {Node} parent - The parent of this mesh, if it has one
  50. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  51. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  52. * When false, achieved by calling a clone(), also passing False.
  53. * This will make creation of children, recursive.
  54. */
  55. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  56. super(name, scene);
  57. if (source) {
  58. // Geometry
  59. if (source._geometry) {
  60. source._geometry.applyToMesh(this);
  61. }
  62. // Deep copy
  63. Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  64. // Material
  65. this.material = source.material;
  66. if (!doNotCloneChildren) {
  67. // Children
  68. for (var index = 0; index < scene.meshes.length; index++) {
  69. var mesh = scene.meshes[index];
  70. if (mesh.parent === source) {
  71. // doNotCloneChildren is always going to be False
  72. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  73. }
  74. }
  75. }
  76. // Particles
  77. for (index = 0; index < scene.particleSystems.length; index++) {
  78. var system = scene.particleSystems[index];
  79. if (system.emitter === source) {
  80. system.clone(system.name, this);
  81. }
  82. }
  83. this.computeWorldMatrix(true);
  84. }
  85. // Parent
  86. if (parent !== null) {
  87. this.parent = parent;
  88. }
  89. }
  90. // Methods
  91. public get hasLODLevels(): boolean {
  92. return this._LODLevels.length > 0;
  93. }
  94. private _sortLODLevels(): void {
  95. this._LODLevels.sort((a, b) => {
  96. if (a.distance < b.distance) {
  97. return 1;
  98. }
  99. if (a.distance > b.distance) {
  100. return -1;
  101. }
  102. return 0;
  103. });
  104. }
  105. /**
  106. * Add a mesh as LOD level triggered at the given distance.
  107. * @param {number} distance - the distance from the center of the object to show this level
  108. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  109. * @return {BABYLON.Mesh} this mesh (for chaining)
  110. */
  111. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  112. if (mesh && mesh._masterMesh) {
  113. Tools.Warn("You cannot use a mesh as LOD level twice");
  114. return this;
  115. }
  116. var level = new Internals.MeshLODLevel(distance, mesh);
  117. this._LODLevels.push(level);
  118. if (mesh) {
  119. mesh._masterMesh = this;
  120. }
  121. this._sortLODLevels();
  122. return this;
  123. }
  124. /**
  125. * Remove a mesh from the LOD array
  126. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  127. * @return {BABYLON.Mesh} this mesh (for chaining)
  128. */
  129. public removeLODLevel(mesh: Mesh): Mesh {
  130. for (var index = 0; index < this._LODLevels.length; index++) {
  131. if (this._LODLevels[index].mesh === mesh) {
  132. this._LODLevels.splice(index, 1);
  133. if (mesh) {
  134. mesh._masterMesh = null;
  135. }
  136. }
  137. }
  138. this._sortLODLevels();
  139. return this;
  140. }
  141. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  142. if (!this._LODLevels || this._LODLevels.length === 0) {
  143. return this;
  144. }
  145. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  146. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  147. return this;
  148. }
  149. for (var index = 0; index < this._LODLevels.length; index++) {
  150. var level = this._LODLevels[index];
  151. if (level.distance < distanceToCamera) {
  152. if (level.mesh) {
  153. level.mesh._preActivate();
  154. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  155. }
  156. return level.mesh;
  157. }
  158. }
  159. return this;
  160. }
  161. public get geometry(): Geometry {
  162. return this._geometry;
  163. }
  164. public getTotalVertices(): number {
  165. if (!this._geometry) {
  166. return 0;
  167. }
  168. return this._geometry.getTotalVertices();
  169. }
  170. public getVerticesData(kind: string): number[] {
  171. if (!this._geometry) {
  172. return null;
  173. }
  174. return this._geometry.getVerticesData(kind);
  175. }
  176. public getVertexBuffer(kind): VertexBuffer {
  177. if (!this._geometry) {
  178. return undefined;
  179. }
  180. return this._geometry.getVertexBuffer(kind);
  181. }
  182. public isVerticesDataPresent(kind: string): boolean {
  183. if (!this._geometry) {
  184. if (this._delayInfo) {
  185. return this._delayInfo.indexOf(kind) !== -1;
  186. }
  187. return false;
  188. }
  189. return this._geometry.isVerticesDataPresent(kind);
  190. }
  191. public getVerticesDataKinds(): string[] {
  192. if (!this._geometry) {
  193. var result = [];
  194. if (this._delayInfo) {
  195. for (var kind in this._delayInfo) {
  196. result.push(kind);
  197. }
  198. }
  199. return result;
  200. }
  201. return this._geometry.getVerticesDataKinds();
  202. }
  203. public getTotalIndices(): number {
  204. if (!this._geometry) {
  205. return 0;
  206. }
  207. return this._geometry.getTotalIndices();
  208. }
  209. public getIndices(): number[] {
  210. if (!this._geometry) {
  211. return [];
  212. }
  213. return this._geometry.getIndices();
  214. }
  215. public get isBlocked(): boolean {
  216. return this._masterMesh !== null && this._masterMesh !== undefined;
  217. }
  218. public isReady(): boolean {
  219. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  220. return false;
  221. }
  222. return super.isReady();
  223. }
  224. public isDisposed(): boolean {
  225. return this._isDisposed;
  226. }
  227. // Methods
  228. public _preActivate(): void {
  229. var sceneRenderId = this.getScene().getRenderId();
  230. if (this._preActivateId === sceneRenderId) {
  231. return;
  232. }
  233. this._preActivateId = sceneRenderId;
  234. this._visibleInstances = null;
  235. }
  236. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  237. if (!this._visibleInstances) {
  238. this._visibleInstances = {};
  239. this._visibleInstances.defaultRenderId = renderId;
  240. this._visibleInstances.selfDefaultRenderId = this._renderId;
  241. }
  242. if (!this._visibleInstances[renderId]) {
  243. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  244. }
  245. this._visibleInstances[renderId].push(instance);
  246. }
  247. public refreshBoundingInfo(): void {
  248. var data = this.getVerticesData(VertexBuffer.PositionKind);
  249. if (data) {
  250. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  251. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  252. }
  253. if (this.subMeshes) {
  254. for (var index = 0; index < this.subMeshes.length; index++) {
  255. this.subMeshes[index].refreshBoundingInfo();
  256. }
  257. }
  258. this._updateBoundingInfo();
  259. }
  260. public _createGlobalSubMesh(): SubMesh {
  261. var totalVertices = this.getTotalVertices();
  262. if (!totalVertices || !this.getIndices()) {
  263. return null;
  264. }
  265. this.releaseSubMeshes();
  266. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  267. }
  268. public subdivide(count: number): void {
  269. if (count < 1) {
  270. return;
  271. }
  272. var totalIndices = this.getTotalIndices();
  273. var subdivisionSize = (totalIndices / count) | 0;
  274. var offset = 0;
  275. // Ensure that subdivisionSize is a multiple of 3
  276. while (subdivisionSize % 3 !== 0) {
  277. subdivisionSize++;
  278. }
  279. this.releaseSubMeshes();
  280. for (var index = 0; index < count; index++) {
  281. if (offset >= totalIndices) {
  282. break;
  283. }
  284. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  285. offset += subdivisionSize;
  286. }
  287. this.synchronizeInstances();
  288. }
  289. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  290. if (kind instanceof Array) {
  291. var temp = data;
  292. data = kind;
  293. kind = temp;
  294. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  295. }
  296. if (!this._geometry) {
  297. var vertexData = new VertexData();
  298. vertexData.set(data, kind);
  299. var scene = this.getScene();
  300. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  301. }
  302. else {
  303. this._geometry.setVerticesData(kind, data, updatable, stride);
  304. }
  305. }
  306. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  307. if (!this._geometry) {
  308. return;
  309. }
  310. if (!makeItUnique) {
  311. this._geometry.updateVerticesData(kind, data, updateExtends);
  312. }
  313. else {
  314. this.makeGeometryUnique();
  315. this.updateVerticesData(kind, data, updateExtends, false);
  316. }
  317. }
  318. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  319. if (!this._geometry) {
  320. return;
  321. }
  322. if (!makeItUnique) {
  323. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  324. }
  325. else {
  326. this.makeGeometryUnique();
  327. this.updateVerticesDataDirectly(kind, data, offset, false);
  328. }
  329. }
  330. public makeGeometryUnique() {
  331. if (!this._geometry) {
  332. return;
  333. }
  334. var geometry = this._geometry.copy(Geometry.RandomId());
  335. geometry.applyToMesh(this);
  336. }
  337. public setIndices(indices: number[], totalVertices?: number): void {
  338. if (!this._geometry) {
  339. var vertexData = new VertexData();
  340. vertexData.indices = indices;
  341. var scene = this.getScene();
  342. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  343. }
  344. else {
  345. this._geometry.setIndices(indices, totalVertices);
  346. }
  347. }
  348. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  349. var engine = this.getScene().getEngine();
  350. // Wireframe
  351. var indexToBind;
  352. switch (fillMode) {
  353. case Material.PointFillMode:
  354. indexToBind = null;
  355. break;
  356. case Material.WireFrameFillMode:
  357. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  358. break;
  359. default:
  360. case Material.TriangleFillMode:
  361. indexToBind = this._geometry.getIndexBuffer();
  362. break;
  363. }
  364. // VBOs
  365. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  366. }
  367. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  368. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  369. return;
  370. }
  371. var engine = this.getScene().getEngine();
  372. // Draw order
  373. switch (fillMode) {
  374. case Material.PointFillMode:
  375. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  376. break;
  377. case Material.WireFrameFillMode:
  378. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  379. break;
  380. default:
  381. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  382. }
  383. }
  384. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  385. this._onBeforeRenderCallbacks.push(func);
  386. }
  387. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  388. var index = this._onBeforeRenderCallbacks.indexOf(func);
  389. if (index > -1) {
  390. this._onBeforeRenderCallbacks.splice(index, 1);
  391. }
  392. }
  393. public registerAfterRender(func: () => void): void {
  394. this._onAfterRenderCallbacks.push(func);
  395. }
  396. public unregisterAfterRender(func: () => void): void {
  397. var index = this._onAfterRenderCallbacks.indexOf(func);
  398. if (index > -1) {
  399. this._onAfterRenderCallbacks.splice(index, 1);
  400. }
  401. }
  402. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  403. var scene = this.getScene();
  404. this._batchCache.mustReturn = false;
  405. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  406. this._batchCache.visibleInstances[subMeshId] = null;
  407. if (this._visibleInstances) {
  408. var currentRenderId = scene.getRenderId();
  409. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  410. var selfRenderId = this._renderId;
  411. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  412. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  413. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  414. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  415. }
  416. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  417. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  418. this._batchCache.mustReturn = true;
  419. return this._batchCache;
  420. }
  421. if (currentRenderId !== selfRenderId) {
  422. this._batchCache.renderSelf[subMeshId] = false;
  423. }
  424. }
  425. this._renderIdForInstances[subMeshId] = currentRenderId;
  426. }
  427. return this._batchCache;
  428. }
  429. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  430. var visibleInstances = batch.visibleInstances[subMesh._id];
  431. var matricesCount = visibleInstances.length + 1;
  432. var bufferSize = matricesCount * 16 * 4;
  433. while (this._instancesBufferSize < bufferSize) {
  434. this._instancesBufferSize *= 2;
  435. }
  436. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  437. if (this._worldMatricesInstancesBuffer) {
  438. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  439. }
  440. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  441. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  442. }
  443. var offset = 0;
  444. var instancesCount = 0;
  445. var world = this.getWorldMatrix();
  446. if (batch.renderSelf[subMesh._id]) {
  447. world.copyToArray(this._worldMatricesInstancesArray, offset);
  448. offset += 16;
  449. instancesCount++;
  450. }
  451. if (visibleInstances) {
  452. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  453. var instance = visibleInstances[instanceIndex];
  454. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  455. offset += 16;
  456. instancesCount++;
  457. }
  458. }
  459. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  460. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  461. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  462. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  463. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  464. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  465. this._draw(subMesh, fillMode, instancesCount);
  466. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  467. }
  468. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  469. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  470. var scene = this.getScene();
  471. var engine = scene.getEngine();
  472. if (hardwareInstancedRendering) {
  473. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  474. } else {
  475. if (batch.renderSelf[subMesh._id]) {
  476. // Draw
  477. if (onBeforeDraw) {
  478. onBeforeDraw(false, this.getWorldMatrix());
  479. }
  480. this._draw(subMesh, fillMode);
  481. }
  482. if (batch.visibleInstances[subMesh._id]) {
  483. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  484. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  485. // World
  486. var world = instance.getWorldMatrix();
  487. if (onBeforeDraw) {
  488. onBeforeDraw(true, world);
  489. }
  490. // Draw
  491. this._draw(subMesh, fillMode);
  492. }
  493. }
  494. }
  495. }
  496. public render(subMesh: SubMesh): void {
  497. var scene = this.getScene();
  498. // Managing instances
  499. var batch = this._getInstancesRenderList(subMesh._id);
  500. if (batch.mustReturn) {
  501. return;
  502. }
  503. // Checking geometry state
  504. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  505. return;
  506. }
  507. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  508. this._onBeforeRenderCallbacks[callbackIndex](this);
  509. }
  510. var engine = scene.getEngine();
  511. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  512. // Material
  513. var effectiveMaterial = subMesh.getMaterial();
  514. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  515. return;
  516. }
  517. // Outline - step 1
  518. var savedDepthWrite = engine.getDepthWrite();
  519. if (this.renderOutline) {
  520. engine.setDepthWrite(false);
  521. scene.getOutlineRenderer().render(subMesh, batch);
  522. engine.setDepthWrite(savedDepthWrite);
  523. }
  524. effectiveMaterial._preBind();
  525. var effect = effectiveMaterial.getEffect();
  526. // Bind
  527. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  528. this._bind(subMesh, effect, fillMode);
  529. var world = this.getWorldMatrix();
  530. effectiveMaterial.bind(world, this);
  531. // Draw
  532. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  533. (isInstance, world) => {
  534. if (isInstance) {
  535. effectiveMaterial.bindOnlyWorldMatrix(world);
  536. }
  537. });
  538. // Unbind
  539. effectiveMaterial.unbind();
  540. // Outline - step 2
  541. if (this.renderOutline && savedDepthWrite) {
  542. engine.setDepthWrite(true);
  543. engine.setColorWrite(false);
  544. scene.getOutlineRenderer().render(subMesh, batch);
  545. engine.setColorWrite(true);
  546. }
  547. // Overlay
  548. if (this.renderOverlay) {
  549. var currentMode = engine.getAlphaMode();
  550. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  551. scene.getOutlineRenderer().render(subMesh, batch, true);
  552. engine.setAlphaMode(currentMode);
  553. }
  554. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  555. this._onAfterRenderCallbacks[callbackIndex](this);
  556. }
  557. }
  558. public getEmittedParticleSystems(): ParticleSystem[] {
  559. var results = new Array<ParticleSystem>();
  560. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  561. var particleSystem = this.getScene().particleSystems[index];
  562. if (particleSystem.emitter === this) {
  563. results.push(particleSystem);
  564. }
  565. }
  566. return results;
  567. }
  568. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  569. var results = new Array<ParticleSystem>();
  570. var descendants = this.getDescendants();
  571. descendants.push(this);
  572. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  573. var particleSystem = this.getScene().particleSystems[index];
  574. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  575. results.push(particleSystem);
  576. }
  577. }
  578. return results;
  579. }
  580. public getChildren(): Node[] {
  581. var results = [];
  582. for (var index = 0; index < this.getScene().meshes.length; index++) {
  583. var mesh = this.getScene().meshes[index];
  584. if (mesh.parent === this) {
  585. results.push(mesh);
  586. }
  587. }
  588. return results;
  589. }
  590. public _checkDelayState(): void {
  591. var that = this;
  592. var scene = this.getScene();
  593. if (this._geometry) {
  594. this._geometry.load(scene);
  595. }
  596. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  597. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  598. scene._addPendingData(that);
  599. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  600. Tools.LoadFile(this.delayLoadingFile, data => {
  601. if (data instanceof ArrayBuffer) {
  602. this._delayLoadingFunction(data, this);
  603. }
  604. else {
  605. this._delayLoadingFunction(JSON.parse(data), this);
  606. }
  607. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  608. scene._removePendingData(this);
  609. }, () => { }, scene.database, getBinaryData);
  610. }
  611. }
  612. public isInFrustum(frustumPlanes: Plane[]): boolean {
  613. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  614. return false;
  615. }
  616. if (!super.isInFrustum(frustumPlanes)) {
  617. return false;
  618. }
  619. this._checkDelayState();
  620. return true;
  621. }
  622. public setMaterialByID(id: string): void {
  623. var materials = this.getScene().materials;
  624. for (var index = 0; index < materials.length; index++) {
  625. if (materials[index].id === id) {
  626. this.material = materials[index];
  627. return;
  628. }
  629. }
  630. // Multi
  631. var multiMaterials = this.getScene().multiMaterials;
  632. for (index = 0; index < multiMaterials.length; index++) {
  633. if (multiMaterials[index].id === id) {
  634. this.material = multiMaterials[index];
  635. return;
  636. }
  637. }
  638. }
  639. public getAnimatables(): IAnimatable[] {
  640. var results = [];
  641. if (this.material) {
  642. results.push(this.material);
  643. }
  644. if (this.skeleton) {
  645. results.push(this.skeleton);
  646. }
  647. return results;
  648. }
  649. // Geometry
  650. public bakeTransformIntoVertices(transform: Matrix): void {
  651. // Position
  652. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  653. return;
  654. }
  655. this._resetPointsArrayCache();
  656. var data = this.getVerticesData(VertexBuffer.PositionKind);
  657. var temp = [];
  658. for (var index = 0; index < data.length; index += 3) {
  659. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  660. }
  661. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  662. // Normals
  663. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  664. return;
  665. }
  666. data = this.getVerticesData(VertexBuffer.NormalKind);
  667. for (index = 0; index < data.length; index += 3) {
  668. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  669. }
  670. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  671. }
  672. // Cache
  673. public _resetPointsArrayCache(): void {
  674. this._positions = null;
  675. }
  676. public _generatePointsArray(): boolean {
  677. if (this._positions)
  678. return true;
  679. this._positions = [];
  680. var data = this.getVerticesData(VertexBuffer.PositionKind);
  681. if (!data) {
  682. return false;
  683. }
  684. for (var index = 0; index < data.length; index += 3) {
  685. this._positions.push(Vector3.FromArray(data, index));
  686. }
  687. return true;
  688. }
  689. // Clone
  690. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  691. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  692. }
  693. // Dispose
  694. public dispose(doNotRecurse?: boolean): void {
  695. if (this._geometry) {
  696. this._geometry.releaseForMesh(this, true);
  697. }
  698. // Instances
  699. if (this._worldMatricesInstancesBuffer) {
  700. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  701. this._worldMatricesInstancesBuffer = null;
  702. }
  703. while (this.instances.length) {
  704. this.instances[0].dispose();
  705. }
  706. super.dispose(doNotRecurse);
  707. }
  708. // Geometric tools
  709. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  710. var scene = this.getScene();
  711. var onload = img => {
  712. // Getting height map data
  713. var canvas = document.createElement("canvas");
  714. var context = canvas.getContext("2d");
  715. var heightMapWidth = img.width;
  716. var heightMapHeight = img.height;
  717. canvas.width = heightMapWidth;
  718. canvas.height = heightMapHeight;
  719. context.drawImage(img, 0, 0);
  720. // Create VertexData from map data
  721. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  722. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  723. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  724. //execute success callback, if set
  725. if (onSuccess) {
  726. onSuccess(this);
  727. }
  728. };
  729. Tools.LoadImage(url, onload, () => { }, scene.database);
  730. }
  731. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  732. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  733. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  734. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  735. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  736. return;
  737. }
  738. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  739. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  740. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  741. var position = Vector3.Zero();
  742. var normal = Vector3.Zero();
  743. var uv = Vector2.Zero();
  744. for (var index = 0; index < positions.length; index += 3) {
  745. Vector3.FromArrayToRef(positions, index, position);
  746. Vector3.FromArrayToRef(normals, index, normal);
  747. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  748. // Compute height
  749. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  750. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  751. var pos = (u + v * heightMapWidth) * 4;
  752. var r = buffer[pos] / 255.0;
  753. var g = buffer[pos + 1] / 255.0;
  754. var b = buffer[pos + 2] / 255.0;
  755. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  756. normal.normalize();
  757. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  758. position = position.add(normal);
  759. position.toArray(positions, index);
  760. }
  761. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  762. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  763. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  764. }
  765. public convertToFlatShadedMesh(): void {
  766. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  767. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  768. var kinds = this.getVerticesDataKinds();
  769. var vbs = [];
  770. var data = [];
  771. var newdata = [];
  772. var updatableNormals = false;
  773. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  774. var kind = kinds[kindIndex];
  775. var vertexBuffer = this.getVertexBuffer(kind);
  776. if (kind === VertexBuffer.NormalKind) {
  777. updatableNormals = vertexBuffer.isUpdatable();
  778. kinds.splice(kindIndex, 1);
  779. kindIndex--;
  780. continue;
  781. }
  782. vbs[kind] = vertexBuffer;
  783. data[kind] = vbs[kind].getData();
  784. newdata[kind] = [];
  785. }
  786. // Save previous submeshes
  787. var previousSubmeshes = this.subMeshes.slice(0);
  788. var indices = this.getIndices();
  789. var totalIndices = this.getTotalIndices();
  790. // Generating unique vertices per face
  791. for (var index = 0; index < totalIndices; index++) {
  792. var vertexIndex = indices[index];
  793. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  794. kind = kinds[kindIndex];
  795. var stride = vbs[kind].getStrideSize();
  796. for (var offset = 0; offset < stride; offset++) {
  797. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  798. }
  799. }
  800. }
  801. // Updating faces & normal
  802. var normals = [];
  803. var positions = newdata[VertexBuffer.PositionKind];
  804. for (index = 0; index < totalIndices; index += 3) {
  805. indices[index] = index;
  806. indices[index + 1] = index + 1;
  807. indices[index + 2] = index + 2;
  808. var p1 = Vector3.FromArray(positions, index * 3);
  809. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  810. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  811. var p1p2 = p1.subtract(p2);
  812. var p3p2 = p3.subtract(p2);
  813. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  814. // Store same normals for every vertex
  815. for (var localIndex = 0; localIndex < 3; localIndex++) {
  816. normals.push(normal.x);
  817. normals.push(normal.y);
  818. normals.push(normal.z);
  819. }
  820. }
  821. this.setIndices(indices);
  822. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  823. // Updating vertex buffers
  824. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  825. kind = kinds[kindIndex];
  826. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  827. }
  828. // Updating submeshes
  829. this.releaseSubMeshes();
  830. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  831. var previousOne = previousSubmeshes[submeshIndex];
  832. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  833. }
  834. this.synchronizeInstances();
  835. }
  836. // Instances
  837. public createInstance(name: string): InstancedMesh {
  838. return new InstancedMesh(name, this);
  839. }
  840. public synchronizeInstances(): void {
  841. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  842. var instance = this.instances[instanceIndex];
  843. instance._syncSubMeshes();
  844. }
  845. }
  846. /**
  847. * Simplify the mesh according to the given array of settings.
  848. * Function will return immediately and will simplify async.
  849. * @param settings a collection of simplification settings.
  850. * @param parallelProcessing should all levels calculate parallel or one after the other.
  851. * @param type the type of simplification to run.
  852. * successCallback optional success callback to be called after the simplification finished processing all settings.
  853. */
  854. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, type: SimplificationType = SimplificationType.QUADRATIC, successCallback?: () => void) {
  855. var getSimplifier = (): ISimplifier => {
  856. switch (type) {
  857. case SimplificationType.QUADRATIC:
  858. default:
  859. return new QuadraticErrorSimplification(this);
  860. }
  861. }
  862. if (parallelProcessing) {
  863. //parallel simplifier
  864. settings.forEach((setting) => {
  865. var simplifier = getSimplifier();
  866. simplifier.simplify(setting, (newMesh) => {
  867. this.addLODLevel(setting.distance, newMesh);
  868. //check if it is the last
  869. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  870. //all done, run the success callback.
  871. successCallback();
  872. }
  873. });
  874. });
  875. } else {
  876. //single simplifier.
  877. var simplifier = getSimplifier();
  878. var runDecimation = (setting: ISimplificationSettings, callback: () => void) => {
  879. simplifier.simplify(setting, (newMesh) => {
  880. this.addLODLevel(setting.distance, newMesh);
  881. //run the next quality level
  882. callback();
  883. });
  884. }
  885. AsyncLoop.Run(settings.length, (loop: AsyncLoop) => {
  886. runDecimation(settings[loop.index], () => {
  887. loop.executeNext();
  888. });
  889. }, () => {
  890. //execution ended, run the success callback.
  891. if (successCallback) {
  892. successCallback();
  893. }
  894. });
  895. }
  896. }
  897. // Statics
  898. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  899. var ribbon = new Mesh(name, scene);
  900. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  901. vertexData.applyToMesh(ribbon, updatable);
  902. return ribbon;
  903. }
  904. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  905. var box = new Mesh(name, scene);
  906. var vertexData = VertexData.CreateBox(size, sideOrientation);
  907. vertexData.applyToMesh(box, updatable);
  908. return box;
  909. }
  910. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  911. var sphere = new Mesh(name, scene);
  912. var vertexData = VertexData.CreateSphere(segments, diameter, sideOrientation);
  913. vertexData.applyToMesh(sphere, updatable);
  914. return sphere;
  915. }
  916. // Cylinder and cone (Code inspired by SharpDX.org)
  917. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  918. // subdivisions is a new parameter, we need to support old signature
  919. if (scene === undefined || !(scene instanceof Scene)) {
  920. if (scene !== undefined) {
  921. updatable = scene;
  922. }
  923. scene = <Scene>subdivisions;
  924. subdivisions = 1;
  925. }
  926. var cylinder = new Mesh(name, scene);
  927. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  928. vertexData.applyToMesh(cylinder, updatable);
  929. return cylinder;
  930. }
  931. // Torus (Code from SharpDX.org)
  932. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  933. var torus = new Mesh(name, scene);
  934. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  935. vertexData.applyToMesh(torus, updatable);
  936. return torus;
  937. }
  938. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  939. var torusKnot = new Mesh(name, scene);
  940. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  941. vertexData.applyToMesh(torusKnot, updatable);
  942. return torusKnot;
  943. }
  944. // Lines
  945. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  946. var lines = new LinesMesh(name, scene, updatable);
  947. var vertexData = VertexData.CreateLines(points);
  948. vertexData.applyToMesh(lines, updatable);
  949. return lines;
  950. }
  951. // Plane & ground
  952. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  953. var plane = new Mesh(name, scene);
  954. var vertexData = VertexData.CreatePlane(size, sideOrientation);
  955. vertexData.applyToMesh(plane, updatable);
  956. return plane;
  957. }
  958. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  959. var ground = new GroundMesh(name, scene);
  960. ground._setReady(false);
  961. ground._subdivisions = subdivisions;
  962. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  963. vertexData.applyToMesh(ground, updatable);
  964. ground._setReady(true);
  965. return ground;
  966. }
  967. public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
  968. var tiledGround = new Mesh(name, scene);
  969. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  970. vertexData.applyToMesh(tiledGround, updatable);
  971. return tiledGround;
  972. }
  973. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh {
  974. var ground = new GroundMesh(name, scene);
  975. ground._subdivisions = subdivisions;
  976. ground._setReady(false);
  977. var onload = img => {
  978. // Getting height map data
  979. var canvas = document.createElement("canvas");
  980. var context = canvas.getContext("2d");
  981. var heightMapWidth = img.width;
  982. var heightMapHeight = img.height;
  983. canvas.width = heightMapWidth;
  984. canvas.height = heightMapHeight;
  985. context.drawImage(img, 0, 0);
  986. // Create VertexData from map data
  987. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  988. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  989. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  990. vertexData.applyToMesh(ground, updatable);
  991. ground._setReady(true);
  992. //execute ready callback, if set
  993. if (onReady) {
  994. onReady(ground);
  995. }
  996. };
  997. Tools.LoadImage(url, onload, () => { }, scene.database);
  998. return ground;
  999. }
  1000. public static CreateTube(name: string, path: Vector3[], radius: number, tesselation: number, radiusFunction: { (i: number, distance: number): number; }, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1001. var path3D: Path3D = new Path3D(path);
  1002. var tangents: Vector3[] = path3D.getTangents();
  1003. var normals: Vector3[] = path3D.getNormals();
  1004. var distances: number[] = path3D.getDistances();
  1005. var pi2: number = Math.PI * 2;
  1006. var step: number = pi2 / tesselation;
  1007. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1008. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1009. var circlePaths: Vector3[][] = [];
  1010. var circlePath: Vector3[];
  1011. var rad: number;
  1012. var normal: Vector3;
  1013. var rotated: Vector3;
  1014. var rotationMatrix: Matrix;
  1015. for (var i: number = 0; i < path.length; i++) {
  1016. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1017. circlePath = []; // current circle array
  1018. normal = normals[i]; // current normal
  1019. for (var ang: number = 0; ang < pi2; ang += step) {
  1020. rotationMatrix = Matrix.RotationAxis(tangents[i], ang);
  1021. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1022. circlePath.push(rotated);
  1023. }
  1024. circlePaths.push(circlePath);
  1025. }
  1026. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  1027. return tube;
  1028. }
  1029. // Tools
  1030. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1031. var minVector: Vector3 = null;
  1032. var maxVector: Vector3 = null;
  1033. for (var i in meshes) {
  1034. var mesh = meshes[i];
  1035. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1036. if (!minVector) {
  1037. minVector = boundingBox.minimumWorld;
  1038. maxVector = boundingBox.maximumWorld;
  1039. continue;
  1040. }
  1041. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1042. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1043. }
  1044. return {
  1045. min: minVector,
  1046. max: maxVector
  1047. };
  1048. }
  1049. public static Center(meshesOrMinMaxVector): Vector3 {
  1050. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1051. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1052. }
  1053. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean): Mesh {
  1054. var source = meshes[0];
  1055. var material = source.material;
  1056. var scene = source.getScene();
  1057. if (!allow32BitsIndices) {
  1058. var totalVertices = 0;
  1059. // Counting vertices
  1060. for (var index = 0; index < meshes.length; index++) {
  1061. totalVertices += meshes[index].getTotalVertices();
  1062. if (totalVertices > 65536) {
  1063. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1064. return null;
  1065. }
  1066. }
  1067. }
  1068. // Merge
  1069. var vertexData = VertexData.ExtractFromMesh(source);
  1070. vertexData.transform(source.getWorldMatrix());
  1071. for (index = 1; index < meshes.length; index++) {
  1072. var otherVertexData = VertexData.ExtractFromMesh(meshes[index]);
  1073. otherVertexData.transform(meshes[index].getWorldMatrix());
  1074. vertexData.merge(otherVertexData);
  1075. }
  1076. var newMesh = new Mesh(source.name + "_merged", scene);
  1077. vertexData.applyToMesh(newMesh);
  1078. // Setting properties
  1079. newMesh.material = material;
  1080. newMesh.checkCollisions = source.checkCollisions;
  1081. // Cleaning
  1082. if (disposeSource) {
  1083. for (index = 0; index < meshes.length; index++) {
  1084. meshes[index].dispose();
  1085. }
  1086. }
  1087. return newMesh;
  1088. }
  1089. }
  1090. }