babylon.mesh.ts 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  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. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  32. // Private
  33. public _geometry: Geometry;
  34. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  35. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  36. public _delayInfo; //ANY
  37. public _delayLoadingFunction: (any, Mesh) => void;
  38. public _visibleInstances: any = {};
  39. private _renderIdForInstances = new Array<number>();
  40. private _batchCache = new _InstancesBatch();
  41. private _worldMatricesInstancesBuffer: WebGLBuffer;
  42. private _worldMatricesInstancesArray: Float32Array;
  43. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  44. public _shouldGenerateFlatShading: boolean;
  45. private _preActivateId: number;
  46. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  47. /**
  48. * @constructor
  49. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  50. * @param {Scene} scene - The scene to add this mesh to.
  51. * @param {Node} parent - The parent of this mesh, if it has one
  52. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  53. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  54. * When false, achieved by calling a clone(), also passing False.
  55. * This will make creation of children, recursive.
  56. */
  57. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  58. super(name, scene);
  59. if (source) {
  60. // Geometry
  61. if (source._geometry) {
  62. source._geometry.applyToMesh(this);
  63. }
  64. // Deep copy
  65. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  66. // Material
  67. this.material = source.material;
  68. if (!doNotCloneChildren) {
  69. // Children
  70. for (var index = 0; index < scene.meshes.length; index++) {
  71. var mesh = scene.meshes[index];
  72. if (mesh.parent === source) {
  73. // doNotCloneChildren is always going to be False
  74. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  75. }
  76. }
  77. }
  78. // Particles
  79. for (index = 0; index < scene.particleSystems.length; index++) {
  80. var system = scene.particleSystems[index];
  81. if (system.emitter === source) {
  82. system.clone(system.name, this);
  83. }
  84. }
  85. this.computeWorldMatrix(true);
  86. }
  87. // Parent
  88. if (parent !== null) {
  89. this.parent = parent;
  90. }
  91. }
  92. // Methods
  93. public get hasLODLevels(): boolean {
  94. return this._LODLevels.length > 0;
  95. }
  96. private _sortLODLevels(): void {
  97. this._LODLevels.sort((a, b) => {
  98. if (a.distance < b.distance) {
  99. return 1;
  100. }
  101. if (a.distance > b.distance) {
  102. return -1;
  103. }
  104. return 0;
  105. });
  106. }
  107. /**
  108. * Add a mesh as LOD level triggered at the given distance.
  109. * @param {number} distance - the distance from the center of the object to show this level
  110. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  111. * @return {BABYLON.Mesh} this mesh (for chaining)
  112. */
  113. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  114. if (mesh && mesh._masterMesh) {
  115. Tools.Warn("You cannot use a mesh as LOD level twice");
  116. return this;
  117. }
  118. var level = new Internals.MeshLODLevel(distance, mesh);
  119. this._LODLevels.push(level);
  120. if (mesh) {
  121. mesh._masterMesh = this;
  122. }
  123. this._sortLODLevels();
  124. return this;
  125. }
  126. public getLODLevelAtDistance(distance: number): Mesh {
  127. for (var index = 0; index < this._LODLevels.length; index++) {
  128. var level = this._LODLevels[index];
  129. if (level.distance === distance) {
  130. return level.mesh;
  131. }
  132. }
  133. return null;
  134. }
  135. /**
  136. * Remove a mesh from the LOD array
  137. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  138. * @return {BABYLON.Mesh} this mesh (for chaining)
  139. */
  140. public removeLODLevel(mesh: Mesh): Mesh {
  141. for (var index = 0; index < this._LODLevels.length; index++) {
  142. if (this._LODLevels[index].mesh === mesh) {
  143. this._LODLevels.splice(index, 1);
  144. if (mesh) {
  145. mesh._masterMesh = null;
  146. }
  147. }
  148. }
  149. this._sortLODLevels();
  150. return this;
  151. }
  152. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  153. if (!this._LODLevels || this._LODLevels.length === 0) {
  154. return this;
  155. }
  156. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  157. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  158. if (this.onLODLevelSelection) {
  159. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  160. }
  161. return this;
  162. }
  163. for (var index = 0; index < this._LODLevels.length; index++) {
  164. var level = this._LODLevels[index];
  165. if (level.distance < distanceToCamera) {
  166. if (level.mesh) {
  167. level.mesh._preActivate();
  168. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  169. }
  170. if (this.onLODLevelSelection) {
  171. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  172. }
  173. return level.mesh;
  174. }
  175. }
  176. if (this.onLODLevelSelection) {
  177. this.onLODLevelSelection(distanceToCamera, this, this);
  178. }
  179. return this;
  180. }
  181. public get geometry(): Geometry {
  182. return this._geometry;
  183. }
  184. public getTotalVertices(): number {
  185. if (!this._geometry) {
  186. return 0;
  187. }
  188. return this._geometry.getTotalVertices();
  189. }
  190. public getVerticesData(kind: string, copyWhenShared? : boolean): number[] {
  191. if (!this._geometry) {
  192. return null;
  193. }
  194. return this._geometry.getVerticesData(kind, copyWhenShared);
  195. }
  196. public getVertexBuffer(kind): VertexBuffer {
  197. if (!this._geometry) {
  198. return undefined;
  199. }
  200. return this._geometry.getVertexBuffer(kind);
  201. }
  202. public isVerticesDataPresent(kind: string): boolean {
  203. if (!this._geometry) {
  204. if (this._delayInfo) {
  205. return this._delayInfo.indexOf(kind) !== -1;
  206. }
  207. return false;
  208. }
  209. return this._geometry.isVerticesDataPresent(kind);
  210. }
  211. public getVerticesDataKinds(): string[] {
  212. if (!this._geometry) {
  213. var result = [];
  214. if (this._delayInfo) {
  215. for (var kind in this._delayInfo) {
  216. result.push(kind);
  217. }
  218. }
  219. return result;
  220. }
  221. return this._geometry.getVerticesDataKinds();
  222. }
  223. public getTotalIndices(): number {
  224. if (!this._geometry) {
  225. return 0;
  226. }
  227. return this._geometry.getTotalIndices();
  228. }
  229. public getIndices(copyWhenShared? : boolean): number[] {
  230. if (!this._geometry) {
  231. return [];
  232. }
  233. return this._geometry.getIndices(copyWhenShared);
  234. }
  235. public get isBlocked(): boolean {
  236. return this._masterMesh !== null && this._masterMesh !== undefined;
  237. }
  238. public isReady(): boolean {
  239. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  240. return false;
  241. }
  242. return super.isReady();
  243. }
  244. public isDisposed(): boolean {
  245. return this._isDisposed;
  246. }
  247. public get sideOrientation(): number {
  248. return this._sideOrientation;
  249. }
  250. public set sideOrientation(sideO: number) {
  251. this._sideOrientation = sideO;
  252. }
  253. // Methods
  254. public _preActivate(): void {
  255. var sceneRenderId = this.getScene().getRenderId();
  256. if (this._preActivateId === sceneRenderId) {
  257. return;
  258. }
  259. this._preActivateId = sceneRenderId;
  260. this._visibleInstances = null;
  261. }
  262. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  263. if (!this._visibleInstances) {
  264. this._visibleInstances = {};
  265. this._visibleInstances.defaultRenderId = renderId;
  266. this._visibleInstances.selfDefaultRenderId = this._renderId;
  267. }
  268. if (!this._visibleInstances[renderId]) {
  269. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  270. }
  271. this._visibleInstances[renderId].push(instance);
  272. }
  273. public refreshBoundingInfo(): void {
  274. var data = this.getVerticesData(VertexBuffer.PositionKind);
  275. if (data) {
  276. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  277. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  278. }
  279. if (this.subMeshes) {
  280. for (var index = 0; index < this.subMeshes.length; index++) {
  281. this.subMeshes[index].refreshBoundingInfo();
  282. }
  283. }
  284. this._updateBoundingInfo();
  285. }
  286. public _createGlobalSubMesh(): SubMesh {
  287. var totalVertices = this.getTotalVertices();
  288. if (!totalVertices || !this.getIndices()) {
  289. return null;
  290. }
  291. this.releaseSubMeshes();
  292. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  293. }
  294. public subdivide(count: number): void {
  295. if (count < 1) {
  296. return;
  297. }
  298. var totalIndices = this.getTotalIndices();
  299. var subdivisionSize = (totalIndices / count) | 0;
  300. var offset = 0;
  301. // Ensure that subdivisionSize is a multiple of 3
  302. while (subdivisionSize % 3 !== 0) {
  303. subdivisionSize++;
  304. }
  305. this.releaseSubMeshes();
  306. for (var index = 0; index < count; index++) {
  307. if (offset >= totalIndices) {
  308. break;
  309. }
  310. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  311. offset += subdivisionSize;
  312. }
  313. this.synchronizeInstances();
  314. }
  315. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  316. if (kind instanceof Array) {
  317. var temp = data;
  318. data = kind;
  319. kind = temp;
  320. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  321. }
  322. if (!this._geometry) {
  323. var vertexData = new VertexData();
  324. vertexData.set(data, kind);
  325. var scene = this.getScene();
  326. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  327. }
  328. else {
  329. this._geometry.setVerticesData(kind, data, updatable, stride);
  330. }
  331. }
  332. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  333. if (!this._geometry) {
  334. return;
  335. }
  336. if (!makeItUnique) {
  337. this._geometry.updateVerticesData(kind, data, updateExtends);
  338. }
  339. else {
  340. this.makeGeometryUnique();
  341. this.updateVerticesData(kind, data, updateExtends, false);
  342. }
  343. }
  344. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  345. if (!this._geometry) {
  346. return;
  347. }
  348. if (!makeItUnique) {
  349. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  350. }
  351. else {
  352. this.makeGeometryUnique();
  353. this.updateVerticesDataDirectly(kind, data, offset, false);
  354. }
  355. }
  356. // Mesh positions update function :
  357. // updates the mesh positions according to the positionFunction returned values.
  358. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  359. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  360. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  361. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  362. positionFunction(positions);
  363. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  364. if (computeNormals) {
  365. var indices = this.getIndices();
  366. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  367. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  368. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  369. }
  370. }
  371. public makeGeometryUnique() {
  372. if (!this._geometry) {
  373. return;
  374. }
  375. var geometry = this._geometry.copy(Geometry.RandomId());
  376. geometry.applyToMesh(this);
  377. }
  378. public setIndices(indices: number[], totalVertices?: number): void {
  379. if (!this._geometry) {
  380. var vertexData = new VertexData();
  381. vertexData.indices = indices;
  382. var scene = this.getScene();
  383. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  384. }
  385. else {
  386. this._geometry.setIndices(indices, totalVertices);
  387. }
  388. }
  389. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  390. var engine = this.getScene().getEngine();
  391. // Wireframe
  392. var indexToBind;
  393. switch (fillMode) {
  394. case Material.PointFillMode:
  395. indexToBind = null;
  396. break;
  397. case Material.WireFrameFillMode:
  398. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  399. break;
  400. default:
  401. case Material.TriangleFillMode:
  402. indexToBind = this._geometry.getIndexBuffer();
  403. break;
  404. }
  405. // VBOs
  406. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  407. }
  408. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  409. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  410. return;
  411. }
  412. var engine = this.getScene().getEngine();
  413. // Draw order
  414. switch (fillMode) {
  415. case Material.PointFillMode:
  416. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  417. break;
  418. case Material.WireFrameFillMode:
  419. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  420. break;
  421. default:
  422. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  423. }
  424. }
  425. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  426. this._onBeforeRenderCallbacks.push(func);
  427. }
  428. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  429. var index = this._onBeforeRenderCallbacks.indexOf(func);
  430. if (index > -1) {
  431. this._onBeforeRenderCallbacks.splice(index, 1);
  432. }
  433. }
  434. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  435. this._onAfterRenderCallbacks.push(func);
  436. }
  437. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  438. var index = this._onAfterRenderCallbacks.indexOf(func);
  439. if (index > -1) {
  440. this._onAfterRenderCallbacks.splice(index, 1);
  441. }
  442. }
  443. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  444. var scene = this.getScene();
  445. this._batchCache.mustReturn = false;
  446. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  447. this._batchCache.visibleInstances[subMeshId] = null;
  448. if (this._visibleInstances) {
  449. var currentRenderId = scene.getRenderId();
  450. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  451. var selfRenderId = this._renderId;
  452. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  453. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  454. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  455. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  456. }
  457. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  458. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  459. this._batchCache.mustReturn = true;
  460. return this._batchCache;
  461. }
  462. if (currentRenderId !== selfRenderId) {
  463. this._batchCache.renderSelf[subMeshId] = false;
  464. }
  465. }
  466. this._renderIdForInstances[subMeshId] = currentRenderId;
  467. }
  468. return this._batchCache;
  469. }
  470. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  471. var visibleInstances = batch.visibleInstances[subMesh._id];
  472. var matricesCount = visibleInstances.length + 1;
  473. var bufferSize = matricesCount * 16 * 4;
  474. while (this._instancesBufferSize < bufferSize) {
  475. this._instancesBufferSize *= 2;
  476. }
  477. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  478. if (this._worldMatricesInstancesBuffer) {
  479. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  480. }
  481. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  482. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  483. }
  484. var offset = 0;
  485. var instancesCount = 0;
  486. var world = this.getWorldMatrix();
  487. if (batch.renderSelf[subMesh._id]) {
  488. world.copyToArray(this._worldMatricesInstancesArray, offset);
  489. offset += 16;
  490. instancesCount++;
  491. }
  492. if (visibleInstances) {
  493. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  494. var instance = visibleInstances[instanceIndex];
  495. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  496. offset += 16;
  497. instancesCount++;
  498. }
  499. }
  500. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  501. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  502. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  503. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  504. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  505. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  506. this._draw(subMesh, fillMode, instancesCount);
  507. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  508. }
  509. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  510. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  511. var scene = this.getScene();
  512. var engine = scene.getEngine();
  513. if (hardwareInstancedRendering) {
  514. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  515. } else {
  516. if (batch.renderSelf[subMesh._id]) {
  517. // Draw
  518. if (onBeforeDraw) {
  519. onBeforeDraw(false, this.getWorldMatrix());
  520. }
  521. this._draw(subMesh, fillMode);
  522. }
  523. if (batch.visibleInstances[subMesh._id]) {
  524. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  525. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  526. // World
  527. var world = instance.getWorldMatrix();
  528. if (onBeforeDraw) {
  529. onBeforeDraw(true, world);
  530. }
  531. // Draw
  532. this._draw(subMesh, fillMode);
  533. }
  534. }
  535. }
  536. }
  537. public render(subMesh: SubMesh): void {
  538. var scene = this.getScene();
  539. // Managing instances
  540. var batch = this._getInstancesRenderList(subMesh._id);
  541. if (batch.mustReturn) {
  542. return;
  543. }
  544. // Checking geometry state
  545. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  546. return;
  547. }
  548. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  549. this._onBeforeRenderCallbacks[callbackIndex](this);
  550. }
  551. var engine = scene.getEngine();
  552. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  553. // Material
  554. var effectiveMaterial = subMesh.getMaterial();
  555. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  556. return;
  557. }
  558. // Outline - step 1
  559. var savedDepthWrite = engine.getDepthWrite();
  560. if (this.renderOutline) {
  561. engine.setDepthWrite(false);
  562. scene.getOutlineRenderer().render(subMesh, batch);
  563. engine.setDepthWrite(savedDepthWrite);
  564. }
  565. effectiveMaterial._preBind();
  566. var effect = effectiveMaterial.getEffect();
  567. // Bind
  568. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  569. this._bind(subMesh, effect, fillMode);
  570. var world = this.getWorldMatrix();
  571. effectiveMaterial.bind(world, this);
  572. // Draw
  573. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  574. (isInstance, world) => {
  575. if (isInstance) {
  576. effectiveMaterial.bindOnlyWorldMatrix(world);
  577. }
  578. });
  579. // Unbind
  580. effectiveMaterial.unbind();
  581. // Outline - step 2
  582. if (this.renderOutline && savedDepthWrite) {
  583. engine.setDepthWrite(true);
  584. engine.setColorWrite(false);
  585. scene.getOutlineRenderer().render(subMesh, batch);
  586. engine.setColorWrite(true);
  587. }
  588. // Overlay
  589. if (this.renderOverlay) {
  590. var currentMode = engine.getAlphaMode();
  591. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  592. scene.getOutlineRenderer().render(subMesh, batch, true);
  593. engine.setAlphaMode(currentMode);
  594. }
  595. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  596. this._onAfterRenderCallbacks[callbackIndex](this);
  597. }
  598. }
  599. public getEmittedParticleSystems(): ParticleSystem[] {
  600. var results = new Array<ParticleSystem>();
  601. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  602. var particleSystem = this.getScene().particleSystems[index];
  603. if (particleSystem.emitter === this) {
  604. results.push(particleSystem);
  605. }
  606. }
  607. return results;
  608. }
  609. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  610. var results = new Array<ParticleSystem>();
  611. var descendants = this.getDescendants();
  612. descendants.push(this);
  613. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  614. var particleSystem = this.getScene().particleSystems[index];
  615. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  616. results.push(particleSystem);
  617. }
  618. }
  619. return results;
  620. }
  621. public getChildren(): Node[] {
  622. var results = [];
  623. for (var index = 0; index < this.getScene().meshes.length; index++) {
  624. var mesh = this.getScene().meshes[index];
  625. if (mesh.parent === this) {
  626. results.push(mesh);
  627. }
  628. }
  629. return results;
  630. }
  631. public _checkDelayState(): void {
  632. var that = this;
  633. var scene = this.getScene();
  634. if (this._geometry) {
  635. this._geometry.load(scene);
  636. }
  637. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  638. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  639. scene._addPendingData(that);
  640. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  641. Tools.LoadFile(this.delayLoadingFile, data => {
  642. if (data instanceof ArrayBuffer) {
  643. this._delayLoadingFunction(data, this);
  644. }
  645. else {
  646. this._delayLoadingFunction(JSON.parse(data), this);
  647. }
  648. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  649. scene._removePendingData(this);
  650. },() => { }, scene.database, getBinaryData);
  651. }
  652. }
  653. public isInFrustum(frustumPlanes: Plane[]): boolean {
  654. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  655. return false;
  656. }
  657. if (!super.isInFrustum(frustumPlanes)) {
  658. return false;
  659. }
  660. this._checkDelayState();
  661. return true;
  662. }
  663. public setMaterialByID(id: string): void {
  664. var materials = this.getScene().materials;
  665. for (var index = 0; index < materials.length; index++) {
  666. if (materials[index].id === id) {
  667. this.material = materials[index];
  668. return;
  669. }
  670. }
  671. // Multi
  672. var multiMaterials = this.getScene().multiMaterials;
  673. for (index = 0; index < multiMaterials.length; index++) {
  674. if (multiMaterials[index].id === id) {
  675. this.material = multiMaterials[index];
  676. return;
  677. }
  678. }
  679. }
  680. public getAnimatables(): IAnimatable[] {
  681. var results = [];
  682. if (this.material) {
  683. results.push(this.material);
  684. }
  685. if (this.skeleton) {
  686. results.push(this.skeleton);
  687. }
  688. return results;
  689. }
  690. // Geometry
  691. public bakeTransformIntoVertices(transform: Matrix): void {
  692. // Position
  693. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  694. return;
  695. }
  696. this._resetPointsArrayCache();
  697. var data = this.getVerticesData(VertexBuffer.PositionKind);
  698. var temp = [];
  699. for (var index = 0; index < data.length; index += 3) {
  700. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  701. }
  702. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  703. // Normals
  704. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  705. return;
  706. }
  707. data = this.getVerticesData(VertexBuffer.NormalKind);
  708. for (index = 0; index < data.length; index += 3) {
  709. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  710. }
  711. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  712. }
  713. // Cache
  714. public _resetPointsArrayCache(): void {
  715. this._positions = null;
  716. }
  717. public _generatePointsArray(): boolean {
  718. if (this._positions)
  719. return true;
  720. this._positions = [];
  721. var data = this.getVerticesData(VertexBuffer.PositionKind);
  722. if (!data) {
  723. return false;
  724. }
  725. for (var index = 0; index < data.length; index += 3) {
  726. this._positions.push(Vector3.FromArray(data, index));
  727. }
  728. return true;
  729. }
  730. // Clone
  731. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  732. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  733. }
  734. // Dispose
  735. public dispose(doNotRecurse?: boolean): void {
  736. if (this._geometry) {
  737. this._geometry.releaseForMesh(this, true);
  738. }
  739. // Instances
  740. if (this._worldMatricesInstancesBuffer) {
  741. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  742. this._worldMatricesInstancesBuffer = null;
  743. }
  744. while (this.instances.length) {
  745. this.instances[0].dispose();
  746. }
  747. super.dispose(doNotRecurse);
  748. }
  749. // Geometric tools
  750. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  751. var scene = this.getScene();
  752. var onload = img => {
  753. // Getting height map data
  754. var canvas = document.createElement("canvas");
  755. var context = canvas.getContext("2d");
  756. var heightMapWidth = img.width;
  757. var heightMapHeight = img.height;
  758. canvas.width = heightMapWidth;
  759. canvas.height = heightMapHeight;
  760. context.drawImage(img, 0, 0);
  761. // Create VertexData from map data
  762. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  763. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  764. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  765. //execute success callback, if set
  766. if (onSuccess) {
  767. onSuccess(this);
  768. }
  769. };
  770. Tools.LoadImage(url, onload,() => { }, scene.database);
  771. }
  772. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  773. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  774. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  775. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  776. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  777. return;
  778. }
  779. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  780. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  781. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  782. var position = Vector3.Zero();
  783. var normal = Vector3.Zero();
  784. var uv = Vector2.Zero();
  785. for (var index = 0; index < positions.length; index += 3) {
  786. Vector3.FromArrayToRef(positions, index, position);
  787. Vector3.FromArrayToRef(normals, index, normal);
  788. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  789. // Compute height
  790. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  791. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  792. var pos = (u + v * heightMapWidth) * 4;
  793. var r = buffer[pos] / 255.0;
  794. var g = buffer[pos + 1] / 255.0;
  795. var b = buffer[pos + 2] / 255.0;
  796. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  797. normal.normalize();
  798. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  799. position = position.add(normal);
  800. position.toArray(positions, index);
  801. }
  802. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  803. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  804. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  805. }
  806. public convertToFlatShadedMesh(): void {
  807. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  808. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  809. var kinds = this.getVerticesDataKinds();
  810. var vbs = [];
  811. var data = [];
  812. var newdata = [];
  813. var updatableNormals = false;
  814. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  815. var kind = kinds[kindIndex];
  816. var vertexBuffer = this.getVertexBuffer(kind);
  817. if (kind === VertexBuffer.NormalKind) {
  818. updatableNormals = vertexBuffer.isUpdatable();
  819. kinds.splice(kindIndex, 1);
  820. kindIndex--;
  821. continue;
  822. }
  823. vbs[kind] = vertexBuffer;
  824. data[kind] = vbs[kind].getData();
  825. newdata[kind] = [];
  826. }
  827. // Save previous submeshes
  828. var previousSubmeshes = this.subMeshes.slice(0);
  829. var indices = this.getIndices();
  830. var totalIndices = this.getTotalIndices();
  831. // Generating unique vertices per face
  832. for (var index = 0; index < totalIndices; index++) {
  833. var vertexIndex = indices[index];
  834. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  835. kind = kinds[kindIndex];
  836. var stride = vbs[kind].getStrideSize();
  837. for (var offset = 0; offset < stride; offset++) {
  838. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  839. }
  840. }
  841. }
  842. // Updating faces & normal
  843. var normals = [];
  844. var positions = newdata[VertexBuffer.PositionKind];
  845. for (index = 0; index < totalIndices; index += 3) {
  846. indices[index] = index;
  847. indices[index + 1] = index + 1;
  848. indices[index + 2] = index + 2;
  849. var p1 = Vector3.FromArray(positions, index * 3);
  850. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  851. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  852. var p1p2 = p1.subtract(p2);
  853. var p3p2 = p3.subtract(p2);
  854. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  855. // Store same normals for every vertex
  856. for (var localIndex = 0; localIndex < 3; localIndex++) {
  857. normals.push(normal.x);
  858. normals.push(normal.y);
  859. normals.push(normal.z);
  860. }
  861. }
  862. this.setIndices(indices);
  863. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  864. // Updating vertex buffers
  865. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  866. kind = kinds[kindIndex];
  867. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  868. }
  869. // Updating submeshes
  870. this.releaseSubMeshes();
  871. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  872. var previousOne = previousSubmeshes[submeshIndex];
  873. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  874. }
  875. this.synchronizeInstances();
  876. }
  877. // Instances
  878. public createInstance(name: string): InstancedMesh {
  879. return new InstancedMesh(name, this);
  880. }
  881. public synchronizeInstances(): void {
  882. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  883. var instance = this.instances[instanceIndex];
  884. instance._syncSubMeshes();
  885. }
  886. }
  887. /**
  888. * Simplify the mesh according to the given array of settings.
  889. * Function will return immediately and will simplify async.
  890. * @param settings a collection of simplification settings.
  891. * @param parallelProcessing should all levels calculate parallel or one after the other.
  892. * @param type the type of simplification to run.
  893. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  894. */
  895. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  896. this.getScene().simplificationQueue.addTask({
  897. settings: settings,
  898. parallelProcessing: parallelProcessing,
  899. mesh: this,
  900. simplificationType: simplificationType,
  901. successCallback: successCallback
  902. });
  903. }
  904. /**
  905. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  906. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  907. * This should be used together with the simplification to avoid disappearing triangles.
  908. * @param successCallback an optional success callback to be called after the optimization finished.
  909. */
  910. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  911. var indices = this.getIndices();
  912. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  913. var vectorPositions = [];
  914. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  915. vectorPositions.push(Vector3.FromArray(positions, pos));
  916. }
  917. var dupes = [];
  918. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40,(iteration) => {
  919. var realPos = vectorPositions.length - 1 - iteration;
  920. var testedPosition = vectorPositions[realPos];
  921. for (var j = 0; j < realPos; ++j) {
  922. var againstPosition = vectorPositions[j];
  923. if (testedPosition.equals(againstPosition)) {
  924. dupes[realPos] = j;
  925. break;
  926. }
  927. }
  928. },() => {
  929. for (var i = 0; i < indices.length; ++i) {
  930. indices[i] = dupes[indices[i]] || indices[i];
  931. }
  932. //indices are now reordered
  933. var originalSubMeshes = this.subMeshes.slice(0);
  934. this.setIndices(indices);
  935. this.subMeshes = originalSubMeshes;
  936. if (successCallback) {
  937. successCallback(this);
  938. }
  939. });
  940. }
  941. // Statics
  942. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, ribbonInstance: Mesh = null): Mesh {
  943. if (ribbonInstance) { // existing ribbon instance update
  944. // positionFunction : ribbon case
  945. // only pathArray and sideOrientation parameters are taken into account for positions update
  946. var positionsOfRibbon = function (pathArray, sideOrientation) {
  947. var positionFunction = function (positions) {
  948. var minlg = pathArray[0].length;
  949. var i = 0;
  950. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  951. for (var si = 1; si <= ns; si++) {
  952. for (var p = 0; p < pathArray.length; p++) {
  953. var path = pathArray[p];
  954. var l = path.length;
  955. minlg = (minlg < l) ? minlg : l;
  956. var j = 0;
  957. while (j < minlg) {
  958. positions[i] = path[j].x;
  959. positions[i + 1] = path[j].y;
  960. positions[i + 2] = path[j].z;
  961. j++;
  962. i += 3;
  963. }
  964. }
  965. }
  966. };
  967. return positionFunction;
  968. };
  969. var sideOrientation = ribbonInstance.sideOrientation;
  970. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  971. ribbonInstance.updateMeshPositions(positionFunction, true);
  972. return ribbonInstance;
  973. }
  974. else { // new ribbon creation
  975. var ribbon = new Mesh(name, scene);
  976. ribbon.sideOrientation = sideOrientation;
  977. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  978. vertexData.applyToMesh(ribbon, updatable);
  979. return ribbon;
  980. }
  981. }
  982. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  983. var disc = new Mesh(name, scene);
  984. var vertexData = VertexData.CreateDisc(radius, tessellation, sideOrientation);
  985. vertexData.applyToMesh(disc, updatable);
  986. return disc;
  987. }
  988. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  989. var box = new Mesh(name, scene);
  990. var vertexData = VertexData.CreateBox(size, sideOrientation);
  991. vertexData.applyToMesh(box, updatable);
  992. return box;
  993. }
  994. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  995. var sphere = new Mesh(name, scene);
  996. var vertexData = VertexData.CreateSphere(segments, diameter, sideOrientation);
  997. vertexData.applyToMesh(sphere, updatable);
  998. return sphere;
  999. }
  1000. // Cylinder and cone (Code inspired by SharpDX.org)
  1001. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1002. // subdivisions is a new parameter, we need to support old signature
  1003. if (scene === undefined || !(scene instanceof Scene)) {
  1004. if (scene !== undefined) {
  1005. updatable = scene;
  1006. }
  1007. scene = <Scene>subdivisions;
  1008. subdivisions = 1;
  1009. }
  1010. var cylinder = new Mesh(name, scene);
  1011. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  1012. vertexData.applyToMesh(cylinder, updatable);
  1013. return cylinder;
  1014. }
  1015. // Torus (Code from SharpDX.org)
  1016. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1017. var torus = new Mesh(name, scene);
  1018. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1019. vertexData.applyToMesh(torus, updatable);
  1020. return torus;
  1021. }
  1022. 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 {
  1023. var torusKnot = new Mesh(name, scene);
  1024. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1025. vertexData.applyToMesh(torusKnot, updatable);
  1026. return torusKnot;
  1027. }
  1028. // Lines
  1029. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, linesInstance: LinesMesh = null): LinesMesh {
  1030. if (linesInstance) { // lines update
  1031. var positionsOfLines = function (points) {
  1032. var positionFunction = function (positions) {
  1033. var i = 0;
  1034. for (var p = 0; p < points.length; p++) {
  1035. positions[i] = points[p].x;
  1036. positions[i + 1] = points[p].y;
  1037. positions[i + 2] = points[p].z;
  1038. i += 3;
  1039. }
  1040. };
  1041. return positionFunction;
  1042. };
  1043. var positionFunction = positionsOfLines(points);
  1044. linesInstance.updateMeshPositions(positionFunction, false);
  1045. return linesInstance;
  1046. }
  1047. // lines creation
  1048. var lines = new LinesMesh(name, scene, updatable);
  1049. var vertexData = VertexData.CreateLines(points);
  1050. vertexData.applyToMesh(lines, updatable);
  1051. return lines;
  1052. }
  1053. // Extrusion
  1054. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1055. scale = scale || 1;
  1056. rotation = rotation || 0;
  1057. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  1058. return extruded;
  1059. }
  1060. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1061. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  1062. return extrudedCustom;
  1063. }
  1064. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh): Mesh {
  1065. // extrusion geometry
  1066. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  1067. var tangents = path3D.getTangents();
  1068. var normals = path3D.getNormals();
  1069. var binormals = path3D.getBinormals();
  1070. var distances = path3D.getDistances();
  1071. var angle = 0;
  1072. var returnScale: { (i: number, distance: number): number; } = (i, distance) => { return scale; };
  1073. var returnRotation: { (i: number, distance: number): number; } = (i, distance) => { return rotation; };
  1074. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1075. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1076. var index = 0;
  1077. for (var i = 0; i < curve.length; i++) {
  1078. var shapePath = new Array<Vector3>();
  1079. var angleStep = rotate(i, distances[i]);
  1080. var scaleRatio = scl(i, distances[i]);
  1081. for (var p = 0; p < shape.length; p++) {
  1082. var rotationMatrix = Matrix.RotationAxis(tangents[i], angle);
  1083. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1084. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1085. shapePath.push(rotated);
  1086. }
  1087. shapePaths[index] = shapePath;
  1088. angle += angleStep;
  1089. index++;
  1090. }
  1091. return shapePaths;
  1092. };
  1093. if (instance) { // instance update
  1094. var path3D = ((<any>instance).path3D).update(curve);
  1095. var pathArray = extrusionPathArray(shape, curve,(<any>instance).path3D,(<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  1096. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1097. return instance;
  1098. }
  1099. // extruded shape creation
  1100. var path3D = <any>new Path3D(curve);
  1101. var newShapePaths = new Array<Array<Vector3>>();
  1102. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  1103. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1104. (<any>extrudedGeneric).pathArray = pathArray;
  1105. (<any>extrudedGeneric).path3D = path3D;
  1106. return extrudedGeneric;
  1107. }
  1108. // Plane & ground
  1109. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1110. var plane = new Mesh(name, scene);
  1111. var vertexData = VertexData.CreatePlane(size, sideOrientation);
  1112. vertexData.applyToMesh(plane, updatable);
  1113. return plane;
  1114. }
  1115. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1116. var ground = new GroundMesh(name, scene);
  1117. ground._setReady(false);
  1118. ground._subdivisions = subdivisions;
  1119. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  1120. vertexData.applyToMesh(ground, updatable);
  1121. ground._setReady(true);
  1122. return ground;
  1123. }
  1124. 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 {
  1125. var tiledGround = new Mesh(name, scene);
  1126. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1127. vertexData.applyToMesh(tiledGround, updatable);
  1128. return tiledGround;
  1129. }
  1130. 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 {
  1131. var ground = new GroundMesh(name, scene);
  1132. ground._subdivisions = subdivisions;
  1133. ground._setReady(false);
  1134. var onload = img => {
  1135. // Getting height map data
  1136. var canvas = document.createElement("canvas");
  1137. var context = canvas.getContext("2d");
  1138. var heightMapWidth = img.width;
  1139. var heightMapHeight = img.height;
  1140. canvas.width = heightMapWidth;
  1141. canvas.height = heightMapHeight;
  1142. context.drawImage(img, 0, 0);
  1143. // Create VertexData from map data
  1144. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1145. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1146. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1147. vertexData.applyToMesh(ground, updatable);
  1148. ground._setReady(true);
  1149. //execute ready callback, if set
  1150. if (onReady) {
  1151. onReady(ground);
  1152. }
  1153. };
  1154. Tools.LoadImage(url, onload,() => { }, scene.database);
  1155. return ground;
  1156. }
  1157. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, tubeInstance: Mesh = null): Mesh {
  1158. // tube geometry
  1159. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  1160. var tangents = path3D.getTangents();
  1161. var normals = path3D.getNormals();
  1162. var distances = path3D.getDistances();
  1163. var pi2 = Math.PI * 2;
  1164. var step = pi2 / tessellation;
  1165. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1166. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1167. var circlePath: Vector3[];
  1168. var rad: number;
  1169. var normal: Vector3;
  1170. var rotated: Vector3;
  1171. var rotationMatrix: Matrix;
  1172. var index = 0;
  1173. for (var i = 0; i < path.length; i++) {
  1174. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1175. circlePath = Array<Vector3>(); // current circle array
  1176. normal = normals[i]; // current normal
  1177. for (var ang = 0; ang < pi2; ang += step) {
  1178. rotationMatrix = Matrix.RotationAxis(tangents[i], ang);
  1179. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1180. circlePath.push(rotated);
  1181. }
  1182. circlePaths[index] = circlePath;
  1183. index++;
  1184. }
  1185. return circlePaths;
  1186. };
  1187. if (tubeInstance) { // tube update
  1188. var path3D = ((<any>tubeInstance).path3D).update(path);
  1189. var pathArray = tubePathArray(path, path3D,(<any>tubeInstance).pathArray, radius,(<any>tubeInstance).tessellation, radiusFunction);
  1190. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1191. return tubeInstance;
  1192. }
  1193. // tube creation
  1194. var path3D = <any>new Path3D(path);
  1195. var newPathArray = new Array<Array<Vector3>>();
  1196. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  1197. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1198. (<any>tube).pathArray = pathArray;
  1199. (<any>tube).path3D = path3D;
  1200. (<any>tube).tessellation = tessellation;
  1201. return tube;
  1202. }
  1203. // Decals
  1204. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number = 0) {
  1205. var indices = sourceMesh.getIndices();
  1206. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  1207. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  1208. // Getting correct rotation
  1209. if (!normal) {
  1210. var target = new Vector3(0, 0, 1);
  1211. var camera = sourceMesh.getScene().activeCamera;
  1212. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1213. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1214. }
  1215. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1216. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1217. var pitch = Math.atan2(normal.y, len);
  1218. // Matrix
  1219. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1220. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1221. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1222. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1223. var vertexData = new VertexData();
  1224. vertexData.indices = [];
  1225. vertexData.positions = [];
  1226. vertexData.normals = [];
  1227. vertexData.uvs = [];
  1228. var currentVertexDataIndex = 0;
  1229. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1230. var vertexId = indices[indexId];
  1231. var result = new PositionNormalVertex();
  1232. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1233. // Send vector to decal local world
  1234. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1235. // Get normal
  1236. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1237. return result;
  1238. }
  1239. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1240. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  1241. if (vertices.length === 0) {
  1242. return vertices;
  1243. }
  1244. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1245. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1246. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1247. return new PositionNormalVertex(
  1248. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1249. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1250. );
  1251. }
  1252. var result = new Array<PositionNormalVertex>();
  1253. for (var index = 0; index < vertices.length; index += 3) {
  1254. var v1Out: boolean;
  1255. var v2Out: boolean;
  1256. var v3Out: boolean;
  1257. var total = 0;
  1258. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  1259. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1260. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1261. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1262. v1Out = d1 > 0;
  1263. v2Out = d2 > 0;
  1264. v3Out = d3 > 0;
  1265. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1266. switch (total) {
  1267. case 0:
  1268. result.push(vertices[index]);
  1269. result.push(vertices[index + 1]);
  1270. result.push(vertices[index + 2]);
  1271. break;
  1272. case 1:
  1273. if (v1Out) {
  1274. nV1 = vertices[index + 1];
  1275. nV2 = vertices[index + 2];
  1276. nV3 = clipVertices(vertices[index], nV1);
  1277. nV4 = clipVertices(vertices[index], nV2);
  1278. }
  1279. if (v2Out) {
  1280. nV1 = vertices[index];
  1281. nV2 = vertices[index + 2];
  1282. nV3 = clipVertices(vertices[index + 1], nV1);
  1283. nV4 = clipVertices(vertices[index + 1], nV2);
  1284. result.push(nV3);
  1285. result.push(nV2.clone());
  1286. result.push(nV1.clone());
  1287. result.push(nV2.clone());
  1288. result.push(nV3.clone());
  1289. result.push(nV4);
  1290. break;
  1291. }
  1292. if (v3Out) {
  1293. nV1 = vertices[index];
  1294. nV2 = vertices[index + 1];
  1295. nV3 = clipVertices(vertices[index + 2], nV1);
  1296. nV4 = clipVertices(vertices[index + 2], nV2);
  1297. }
  1298. result.push(nV1.clone());
  1299. result.push(nV2.clone());
  1300. result.push(nV3);
  1301. result.push(nV4);
  1302. result.push(nV3.clone());
  1303. result.push(nV2.clone());
  1304. break;
  1305. case 2:
  1306. if (!v1Out) {
  1307. nV1 = vertices[index].clone();
  1308. nV2 = clipVertices(nV1, vertices[index + 1]);
  1309. nV3 = clipVertices(nV1, vertices[index + 2]);
  1310. result.push(nV1);
  1311. result.push(nV2);
  1312. result.push(nV3);
  1313. }
  1314. if (!v2Out) {
  1315. nV1 = vertices[index + 1].clone();
  1316. nV2 = clipVertices(nV1, vertices[index + 2]);
  1317. nV3 = clipVertices(nV1, vertices[index]);
  1318. result.push(nV1);
  1319. result.push(nV2);
  1320. result.push(nV3);
  1321. }
  1322. if (!v3Out) {
  1323. nV1 = vertices[index + 2].clone();
  1324. nV2 = clipVertices(nV1, vertices[index]);
  1325. nV3 = clipVertices(nV1, vertices[index + 1]);
  1326. result.push(nV1);
  1327. result.push(nV2);
  1328. result.push(nV3);
  1329. }
  1330. break;
  1331. case 3:
  1332. break;
  1333. }
  1334. }
  1335. return result;
  1336. }
  1337. for (var index = 0; index < indices.length; index += 3) {
  1338. var faceVertices = new Array<PositionNormalVertex>();
  1339. faceVertices.push(extractDecalVector3(index));
  1340. faceVertices.push(extractDecalVector3(index + 1));
  1341. faceVertices.push(extractDecalVector3(index + 2));
  1342. // Clip
  1343. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1344. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1345. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1346. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1347. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1348. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1349. if (faceVertices.length === 0) {
  1350. continue;
  1351. }
  1352. // Add UVs and get back to world
  1353. var localRotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  1354. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1355. var vertex = faceVertices[vIndex];
  1356. vertexData.indices.push(currentVertexDataIndex);
  1357. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1358. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1359. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1360. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1361. currentVertexDataIndex++;
  1362. }
  1363. }
  1364. // Return mesh
  1365. var decal = new Mesh(name, sourceMesh.getScene());
  1366. vertexData.applyToMesh(decal);
  1367. decal.position = position.clone();
  1368. decal.rotation = new Vector3(pitch, yaw, angle);
  1369. return decal;
  1370. }
  1371. // Tools
  1372. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1373. var minVector: Vector3 = null;
  1374. var maxVector: Vector3 = null;
  1375. for (var i in meshes) {
  1376. var mesh = meshes[i];
  1377. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1378. if (!minVector) {
  1379. minVector = boundingBox.minimumWorld;
  1380. maxVector = boundingBox.maximumWorld;
  1381. continue;
  1382. }
  1383. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1384. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1385. }
  1386. return {
  1387. min: minVector,
  1388. max: maxVector
  1389. };
  1390. }
  1391. public static Center(meshesOrMinMaxVector): Vector3 {
  1392. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1393. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1394. }
  1395. /**
  1396. * Merge the array of meshes into a single mesh for performance reasons.
  1397. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1398. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1399. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1400. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1401. */
  1402. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1403. if (!allow32BitsIndices) {
  1404. var totalVertices = 0;
  1405. // Counting vertices
  1406. for (var index = 0; index < meshes.length; index++) {
  1407. if (meshes[index]){
  1408. totalVertices += meshes[index].getTotalVertices();
  1409. if (totalVertices > 65536) {
  1410. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1411. return null;
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // Merge
  1417. var vertexData : VertexData;
  1418. var otherVertexData : VertexData;
  1419. var source : Mesh;
  1420. for (index = 0; index < meshes.length; index++) {
  1421. if (meshes[index]){
  1422. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1423. otherVertexData.transform(meshes[index].getWorldMatrix());
  1424. if (vertexData){
  1425. vertexData.merge(otherVertexData);
  1426. }else{
  1427. vertexData = otherVertexData;
  1428. source = meshes[index];
  1429. }
  1430. }
  1431. }
  1432. if (!meshSubclass){
  1433. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1434. }
  1435. vertexData.applyToMesh(meshSubclass);
  1436. // Setting properties
  1437. meshSubclass.material = source.material;
  1438. meshSubclass.checkCollisions = source.checkCollisions;
  1439. // Cleaning
  1440. if (disposeSource) {
  1441. for (index = 0; index < meshes.length; index++) {
  1442. if (meshes[index]){
  1443. meshes[index].dispose();
  1444. }
  1445. }
  1446. }
  1447. return meshSubclass;
  1448. }
  1449. }
  1450. }