babylon.mesh.ts 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612
  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 _NO_CAP = 0;
  14. public static _CAP_START = 1;
  15. public static _CAP_END = 2;
  16. public static _CAP_ALL = 3;
  17. /**
  18. * Mesh side orientation : usually the external or front surface
  19. */
  20. public static get FRONTSIDE(): number {
  21. return Mesh._FRONTSIDE;
  22. }
  23. /**
  24. * Mesh side orientation : usually the internal or back surface
  25. */
  26. public static get BACKSIDE(): number {
  27. return Mesh._BACKSIDE;
  28. }
  29. /**
  30. * Mesh side orientation : both internal and external or front and back surfaces
  31. */
  32. public static get DOUBLESIDE(): number {
  33. return Mesh._DOUBLESIDE;
  34. }
  35. /**
  36. * Mesh side orientation : by default, `FRONTSIDE`
  37. */
  38. public static get DEFAULTSIDE(): number {
  39. return Mesh._DEFAULTSIDE;
  40. }
  41. /**
  42. * Mesh cap setting : no cap
  43. */
  44. public static get NO_CAP(): number {
  45. return Mesh._NO_CAP;
  46. }
  47. /**
  48. * Mesh cap setting : one cap at the beginning of the mesh
  49. */
  50. public static get CAP_START(): number {
  51. return Mesh._CAP_START;
  52. }
  53. /**
  54. * Mesh cap setting : one cap at the end of the mesh
  55. */
  56. public static get CAP_END(): number {
  57. return Mesh._CAP_END;
  58. }
  59. /**
  60. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  61. */
  62. public static get CAP_ALL(): number {
  63. return Mesh._CAP_ALL;
  64. }
  65. // Events
  66. /**
  67. * An event triggered before rendering the mesh
  68. * @type {BABYLON.Observable}
  69. */
  70. public onBeforeRenderObservable = new Observable<Mesh>();
  71. /**
  72. * An event triggered after rendering the mesh
  73. * @type {BABYLON.Observable}
  74. */
  75. public onAfterRenderObservable = new Observable<Mesh>();
  76. /**
  77. * An event triggered before drawing the mesh
  78. * @type {BABYLON.Observable}
  79. */
  80. public onBeforeDrawObservable = new Observable<Mesh>();
  81. private _onBeforeDrawObserver: Observer<Mesh>;
  82. public set onBeforeDraw(callback: () => void) {
  83. if (this._onBeforeDrawObserver) {
  84. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  85. }
  86. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  87. }
  88. // Members
  89. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  90. public instances = new Array<InstancedMesh>();
  91. public delayLoadingFile: string;
  92. public _binaryInfo: any;
  93. private _LODLevels = new Array<Internals.MeshLODLevel>();
  94. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  95. // Private
  96. public _geometry: Geometry;
  97. public _delayInfo; //ANY
  98. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  99. public _visibleInstances: any = {};
  100. private _renderIdForInstances = new Array<number>();
  101. private _batchCache = new _InstancesBatch();
  102. private _worldMatricesInstancesBuffer: WebGLBuffer;
  103. private _worldMatricesInstancesArray: Float32Array;
  104. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  105. public _shouldGenerateFlatShading: boolean;
  106. private _preActivateId: number;
  107. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  108. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  109. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  110. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  111. /**
  112. * @constructor
  113. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  114. * @param {Scene} scene - The scene to add this mesh to.
  115. * @param {Node} parent - The parent of this mesh, if it has one
  116. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  117. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  118. * When false, achieved by calling a clone(), also passing False.
  119. * This will make creation of children, recursive.
  120. */
  121. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  122. super(name, scene);
  123. if (source) {
  124. // Geometry
  125. if (source._geometry) {
  126. source._geometry.applyToMesh(this);
  127. }
  128. // Deep copy
  129. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  130. // Pivot
  131. this.setPivotMatrix(source.getPivotMatrix());
  132. this.id = name + "." + source.id;
  133. // Material
  134. this.material = source.material;
  135. var index: number;
  136. if (!doNotCloneChildren) {
  137. // Children
  138. for (index = 0; index < scene.meshes.length; index++) {
  139. var mesh = scene.meshes[index];
  140. if (mesh.parent === source) {
  141. // doNotCloneChildren is always going to be False
  142. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  143. }
  144. }
  145. }
  146. // Physics clone
  147. var physicsEngine = this.getScene().getPhysicsEngine();
  148. if (clonePhysicsImpostor && physicsEngine) {
  149. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  150. if (impostor) {
  151. this.physicsImpostor = impostor.clone(this);
  152. }
  153. }
  154. // Particles
  155. for (index = 0; index < scene.particleSystems.length; index++) {
  156. var system = scene.particleSystems[index];
  157. if (system.emitter === source) {
  158. system.clone(system.name, this);
  159. }
  160. }
  161. this.computeWorldMatrix(true);
  162. }
  163. // Parent
  164. if (parent !== null) {
  165. this.parent = parent;
  166. }
  167. }
  168. // Methods
  169. /**
  170. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  171. */
  172. public toString(fullDetails?: boolean): string {
  173. var ret = super.toString(fullDetails);
  174. ret += ", n vertices: " + this.getTotalVertices();
  175. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  176. if (this.animations) {
  177. for (var i = 0; i < this.animations.length; i++) {
  178. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  179. }
  180. }
  181. if (fullDetails) {
  182. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  183. }
  184. return ret;
  185. }
  186. public get hasLODLevels(): boolean {
  187. return this._LODLevels.length > 0;
  188. }
  189. private _sortLODLevels(): void {
  190. this._LODLevels.sort((a, b) => {
  191. if (a.distance < b.distance) {
  192. return 1;
  193. }
  194. if (a.distance > b.distance) {
  195. return -1;
  196. }
  197. return 0;
  198. });
  199. }
  200. /**
  201. * Add a mesh as LOD level triggered at the given distance.
  202. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  203. * @param {number} distance - the distance from the center of the object to show this level
  204. * @param {Mesh} mesh - the mesh to be added as LOD level
  205. * @return {Mesh} this mesh (for chaining)
  206. */
  207. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  208. if (mesh && mesh._masterMesh) {
  209. Tools.Warn("You cannot use a mesh as LOD level twice");
  210. return this;
  211. }
  212. var level = new Internals.MeshLODLevel(distance, mesh);
  213. this._LODLevels.push(level);
  214. if (mesh) {
  215. mesh._masterMesh = this;
  216. }
  217. this._sortLODLevels();
  218. return this;
  219. }
  220. /**
  221. * Returns the LOD level mesh at the passed distance or null if not found.
  222. * It is related to the method `addLODLevel(distance, mesh)`.
  223. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  224. */
  225. public getLODLevelAtDistance(distance: number): Mesh {
  226. for (var index = 0; index < this._LODLevels.length; index++) {
  227. var level = this._LODLevels[index];
  228. if (level.distance === distance) {
  229. return level.mesh;
  230. }
  231. }
  232. return null;
  233. }
  234. /**
  235. * Remove a mesh from the LOD array
  236. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  237. * @param {Mesh} mesh - the mesh to be removed.
  238. * @return {Mesh} this mesh (for chaining)
  239. */
  240. public removeLODLevel(mesh: Mesh): Mesh {
  241. for (var index = 0; index < this._LODLevels.length; index++) {
  242. if (this._LODLevels[index].mesh === mesh) {
  243. this._LODLevels.splice(index, 1);
  244. if (mesh) {
  245. mesh._masterMesh = null;
  246. }
  247. }
  248. }
  249. this._sortLODLevels();
  250. return this;
  251. }
  252. /**
  253. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  254. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  255. */
  256. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  257. if (!this._LODLevels || this._LODLevels.length === 0) {
  258. return this;
  259. }
  260. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  261. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  262. if (this.onLODLevelSelection) {
  263. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  264. }
  265. return this;
  266. }
  267. for (var index = 0; index < this._LODLevels.length; index++) {
  268. var level = this._LODLevels[index];
  269. if (level.distance < distanceToCamera) {
  270. if (level.mesh) {
  271. level.mesh._preActivate();
  272. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  273. }
  274. if (this.onLODLevelSelection) {
  275. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  276. }
  277. return level.mesh;
  278. }
  279. }
  280. if (this.onLODLevelSelection) {
  281. this.onLODLevelSelection(distanceToCamera, this, this);
  282. }
  283. return this;
  284. }
  285. /**
  286. * Returns the mesh internal `Geometry` object.
  287. */
  288. public get geometry(): Geometry {
  289. return this._geometry;
  290. }
  291. /**
  292. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  293. */
  294. public getTotalVertices(): number {
  295. if (!this._geometry) {
  296. return 0;
  297. }
  298. return this._geometry.getTotalVertices();
  299. }
  300. /**
  301. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  302. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  303. * Returns null if the mesh has no geometry or no vertex buffer.
  304. * Possible `kind` values :
  305. * - BABYLON.VertexBuffer.PositionKind
  306. * - BABYLON.VertexBuffer.UVKind
  307. * - BABYLON.VertexBuffer.UV2Kind
  308. * - BABYLON.VertexBuffer.UV3Kind
  309. * - BABYLON.VertexBuffer.UV4Kind
  310. * - BABYLON.VertexBuffer.UV5Kind
  311. * - BABYLON.VertexBuffer.UV6Kind
  312. * - BABYLON.VertexBuffer.ColorKind
  313. * - BABYLON.VertexBuffer.MatricesIndicesKind
  314. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  315. * - BABYLON.VertexBuffer.MatricesWeightsKind
  316. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  317. */
  318. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array {
  319. if (!this._geometry) {
  320. return null;
  321. }
  322. return this._geometry.getVerticesData(kind, copyWhenShared);
  323. }
  324. /**
  325. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  326. * Returns `undefined` if the mesh has no geometry.
  327. * Possible `kind` values :
  328. * - BABYLON.VertexBuffer.PositionKind
  329. * - BABYLON.VertexBuffer.UVKind
  330. * - BABYLON.VertexBuffer.UV2Kind
  331. * - BABYLON.VertexBuffer.UV3Kind
  332. * - BABYLON.VertexBuffer.UV4Kind
  333. * - BABYLON.VertexBuffer.UV5Kind
  334. * - BABYLON.VertexBuffer.UV6Kind
  335. * - BABYLON.VertexBuffer.ColorKind
  336. * - BABYLON.VertexBuffer.MatricesIndicesKind
  337. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  338. * - BABYLON.VertexBuffer.MatricesWeightsKind
  339. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  340. */
  341. public getVertexBuffer(kind): VertexBuffer {
  342. if (!this._geometry) {
  343. return undefined;
  344. }
  345. return this._geometry.getVertexBuffer(kind);
  346. }
  347. /**
  348. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  349. * Possible `kind` values :
  350. * - BABYLON.VertexBuffer.PositionKind
  351. * - BABYLON.VertexBuffer.UVKind
  352. * - BABYLON.VertexBuffer.UV2Kind
  353. * - BABYLON.VertexBuffer.UV3Kind
  354. * - BABYLON.VertexBuffer.UV4Kind
  355. * - BABYLON.VertexBuffer.UV5Kind
  356. * - BABYLON.VertexBuffer.UV6Kind
  357. * - BABYLON.VertexBuffer.ColorKind
  358. * - BABYLON.VertexBuffer.MatricesIndicesKind
  359. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  360. * - BABYLON.VertexBuffer.MatricesWeightsKind
  361. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  362. */
  363. public isVerticesDataPresent(kind: string): boolean {
  364. if (!this._geometry) {
  365. if (this._delayInfo) {
  366. return this._delayInfo.indexOf(kind) !== -1;
  367. }
  368. return false;
  369. }
  370. return this._geometry.isVerticesDataPresent(kind);
  371. }
  372. /**
  373. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  374. * Possible `kind` values :
  375. * - BABYLON.VertexBuffer.PositionKind
  376. * - BABYLON.VertexBuffer.UVKind
  377. * - BABYLON.VertexBuffer.UV2Kind
  378. * - BABYLON.VertexBuffer.UV3Kind
  379. * - BABYLON.VertexBuffer.UV4Kind
  380. * - BABYLON.VertexBuffer.UV5Kind
  381. * - BABYLON.VertexBuffer.UV6Kind
  382. * - BABYLON.VertexBuffer.ColorKind
  383. * - BABYLON.VertexBuffer.MatricesIndicesKind
  384. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  385. * - BABYLON.VertexBuffer.MatricesWeightsKind
  386. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  387. */
  388. public getVerticesDataKinds(): string[] {
  389. if (!this._geometry) {
  390. var result = [];
  391. if (this._delayInfo) {
  392. for (var kind in this._delayInfo) {
  393. result.push(kind);
  394. }
  395. }
  396. return result;
  397. }
  398. return this._geometry.getVerticesDataKinds();
  399. }
  400. /**
  401. * Returns a positive integer : the total number of indices in this mesh geometry.
  402. * Returns zero if the mesh has no geometry.
  403. */
  404. public getTotalIndices(): number {
  405. if (!this._geometry) {
  406. return 0;
  407. }
  408. return this._geometry.getTotalIndices();
  409. }
  410. /**
  411. * Returns an array of integers or a Int32Array populated with the mesh indices.
  412. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  413. * Returns an empty array if the mesh has no geometry.
  414. */
  415. public getIndices(copyWhenShared?: boolean): number[] | Int32Array {
  416. if (!this._geometry) {
  417. return [];
  418. }
  419. return this._geometry.getIndices(copyWhenShared);
  420. }
  421. public get isBlocked(): boolean {
  422. return this._masterMesh !== null && this._masterMesh !== undefined;
  423. }
  424. /**
  425. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  426. */
  427. public isReady(): boolean {
  428. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  429. return false;
  430. }
  431. return super.isReady();
  432. }
  433. /**
  434. * Boolean : true if the mesh has been disposed.
  435. */
  436. public isDisposed(): boolean {
  437. return this._isDisposed;
  438. }
  439. public get sideOrientation(): number {
  440. return this._sideOrientation;
  441. }
  442. /**
  443. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  444. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  445. */
  446. public set sideOrientation(sideO: number) {
  447. this._sideOrientation = sideO;
  448. }
  449. /**
  450. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  451. * This property is pertinent only for updatable parametric shapes.
  452. */
  453. public get areNormalsFrozen(): boolean {
  454. return this._areNormalsFrozen;
  455. }
  456. /**
  457. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  458. * It has no effect at all on other shapes.
  459. * It prevents the mesh normals from being recomputed on next `positions` array update.
  460. */
  461. public freezeNormals(): void {
  462. this._areNormalsFrozen = true;
  463. }
  464. /**
  465. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  466. * It has no effect at all on other shapes.
  467. * It reactivates the mesh normals computation if it was previously frozen.
  468. */
  469. public unfreezeNormals(): void {
  470. this._areNormalsFrozen = false;
  471. }
  472. // Methods
  473. public _preActivate(): void {
  474. var sceneRenderId = this.getScene().getRenderId();
  475. if (this._preActivateId === sceneRenderId) {
  476. return;
  477. }
  478. this._preActivateId = sceneRenderId;
  479. this._visibleInstances = null;
  480. }
  481. public _preActivateForIntermediateRendering(renderId: number): void {
  482. if (this._visibleInstances) {
  483. this._visibleInstances.intermediateDefaultRenderId = renderId;
  484. }
  485. }
  486. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  487. if (!this._visibleInstances) {
  488. this._visibleInstances = {};
  489. this._visibleInstances.defaultRenderId = renderId;
  490. this._visibleInstances.selfDefaultRenderId = this._renderId;
  491. }
  492. if (!this._visibleInstances[renderId]) {
  493. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  494. }
  495. this._visibleInstances[renderId].push(instance);
  496. }
  497. /**
  498. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  499. * This means the mesh underlying bounding box and sphere are recomputed.
  500. */
  501. public refreshBoundingInfo(): void {
  502. if (this._boundingInfo.isLocked) {
  503. return;
  504. }
  505. var data = this.getVerticesData(VertexBuffer.PositionKind);
  506. if (data) {
  507. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  508. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  509. }
  510. if (this.subMeshes) {
  511. for (var index = 0; index < this.subMeshes.length; index++) {
  512. this.subMeshes[index].refreshBoundingInfo();
  513. }
  514. }
  515. this._updateBoundingInfo();
  516. }
  517. public _createGlobalSubMesh(): SubMesh {
  518. var totalVertices = this.getTotalVertices();
  519. if (!totalVertices || !this.getIndices()) {
  520. return null;
  521. }
  522. this.releaseSubMeshes();
  523. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  524. }
  525. public subdivide(count: number): void {
  526. if (count < 1) {
  527. return;
  528. }
  529. var totalIndices = this.getTotalIndices();
  530. var subdivisionSize = (totalIndices / count) | 0;
  531. var offset = 0;
  532. // Ensure that subdivisionSize is a multiple of 3
  533. while (subdivisionSize % 3 !== 0) {
  534. subdivisionSize++;
  535. }
  536. this.releaseSubMeshes();
  537. for (var index = 0; index < count; index++) {
  538. if (offset >= totalIndices) {
  539. break;
  540. }
  541. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  542. offset += subdivisionSize;
  543. }
  544. this.synchronizeInstances();
  545. }
  546. /**
  547. * Sets the vertex data of the mesh geometry for the requested `kind`.
  548. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  549. * The `data` are either a numeric array either a Float32Array.
  550. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  551. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  552. * Note that a new underlying `VertexBuffer` object is created each call.
  553. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  554. *
  555. * Possible `kind` values :
  556. * - BABYLON.VertexBuffer.PositionKind
  557. * - BABYLON.VertexBuffer.UVKind
  558. * - BABYLON.VertexBuffer.UV2Kind
  559. * - BABYLON.VertexBuffer.UV3Kind
  560. * - BABYLON.VertexBuffer.UV4Kind
  561. * - BABYLON.VertexBuffer.UV5Kind
  562. * - BABYLON.VertexBuffer.UV6Kind
  563. * - BABYLON.VertexBuffer.ColorKind
  564. * - BABYLON.VertexBuffer.MatricesIndicesKind
  565. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  566. * - BABYLON.VertexBuffer.MatricesWeightsKind
  567. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  568. */
  569. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void {
  570. if (!this._geometry) {
  571. var vertexData = new VertexData();
  572. vertexData.set(data, kind);
  573. var scene = this.getScene();
  574. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  575. }
  576. else {
  577. this._geometry.setVerticesData(kind, data, updatable, stride);
  578. }
  579. }
  580. /**
  581. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  582. * If the mesh has no geometry, it is simply returned as it is.
  583. * The `data` are either a numeric array either a Float32Array.
  584. * No new underlying `VertexBuffer` object is created.
  585. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  586. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  587. *
  588. * Possible `kind` values :
  589. * - BABYLON.VertexBuffer.PositionKind
  590. * - BABYLON.VertexBuffer.UVKind
  591. * - BABYLON.VertexBuffer.UV2Kind
  592. * - BABYLON.VertexBuffer.UV3Kind
  593. * - BABYLON.VertexBuffer.UV4Kind
  594. * - BABYLON.VertexBuffer.UV5Kind
  595. * - BABYLON.VertexBuffer.UV6Kind
  596. * - BABYLON.VertexBuffer.ColorKind
  597. * - BABYLON.VertexBuffer.MatricesIndicesKind
  598. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  599. * - BABYLON.VertexBuffer.MatricesWeightsKind
  600. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  601. */
  602. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void {
  603. if (!this._geometry) {
  604. return;
  605. }
  606. if (!makeItUnique) {
  607. this._geometry.updateVerticesData(kind, data, updateExtends);
  608. }
  609. else {
  610. this.makeGeometryUnique();
  611. this.updateVerticesData(kind, data, updateExtends, false);
  612. }
  613. }
  614. /**
  615. * Deprecated since BabylonJS v2.3
  616. */
  617. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  618. Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  619. if (!this._geometry) {
  620. return;
  621. }
  622. if (!makeItUnique) {
  623. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  624. }
  625. else {
  626. this.makeGeometryUnique();
  627. this.updateVerticesDataDirectly(kind, data, offset, false);
  628. }
  629. }
  630. /**
  631. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  632. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  633. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  634. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  635. */
  636. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  637. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  638. positionFunction(positions);
  639. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  640. if (computeNormals) {
  641. var indices = this.getIndices();
  642. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  643. VertexData.ComputeNormals(positions, indices, normals);
  644. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  645. }
  646. }
  647. /**
  648. * If the mesh geometry is shared among several other meshes, this function creates a dedicated geometry instance by copying it from the shared one.
  649. */
  650. public makeGeometryUnique() {
  651. if (!this._geometry) {
  652. return;
  653. }
  654. var geometry = this._geometry.copy(Geometry.RandomId());
  655. geometry.applyToMesh(this);
  656. }
  657. /**
  658. * Sets the mesh indices.
  659. * Expects an array populated with integers or a Int32Array.
  660. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  661. * This method creates a new index buffer each call.
  662. */
  663. public setIndices(indices: number[] | Int32Array, totalVertices?: number): void {
  664. if (!this._geometry) {
  665. var vertexData = new VertexData();
  666. vertexData.indices = indices;
  667. var scene = this.getScene();
  668. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  669. }
  670. else {
  671. this._geometry.setIndices(indices, totalVertices);
  672. }
  673. }
  674. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  675. var engine = this.getScene().getEngine();
  676. // Wireframe
  677. var indexToBind;
  678. if (this._unIndexed) {
  679. indexToBind = null;
  680. } else {
  681. switch (fillMode) {
  682. case Material.PointFillMode:
  683. indexToBind = null;
  684. break;
  685. case Material.WireFrameFillMode:
  686. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  687. break;
  688. default:
  689. case Material.TriangleFillMode:
  690. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  691. break;
  692. }
  693. }
  694. // VBOs
  695. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  696. }
  697. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  698. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  699. return;
  700. }
  701. this.onBeforeDrawObservable.notifyObservers(this);
  702. var engine = this.getScene().getEngine();
  703. // Draw order
  704. switch (fillMode) {
  705. case Material.PointFillMode:
  706. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  707. break;
  708. case Material.WireFrameFillMode:
  709. if (this._unIndexed) {
  710. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  711. } else {
  712. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  713. }
  714. break;
  715. default:
  716. if (this._unIndexed) {
  717. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  718. } else {
  719. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  720. }
  721. }
  722. }
  723. /**
  724. * Registers for this mesh a javascript function called just before the rendering process.
  725. * This function is passed the current mesh and doesn't return anything.
  726. */
  727. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  728. this.onBeforeRenderObservable.add(func);
  729. }
  730. /**
  731. * Disposes a previously registered javascript function called before the rendering.
  732. * This function is passed the current mesh and doesn't return anything.
  733. */
  734. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  735. this.onBeforeRenderObservable.removeCallback(func);
  736. }
  737. /**
  738. * Registers for this mesh a javascript function called just after the rendering is complete.
  739. * This function is passed the current mesh and doesn't return anything.
  740. */
  741. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  742. this.onAfterRenderObservable.add(func);
  743. }
  744. /**
  745. * Disposes a previously registered javascript function called after the rendering.
  746. * This function is passed the current mesh and doesn't return anything.
  747. */
  748. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  749. this.onAfterRenderObservable.removeCallback(func);
  750. }
  751. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  752. var scene = this.getScene();
  753. this._batchCache.mustReturn = false;
  754. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  755. this._batchCache.visibleInstances[subMeshId] = null;
  756. if (this._visibleInstances) {
  757. var currentRenderId = scene.getRenderId();
  758. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  759. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  760. var selfRenderId = this._renderId;
  761. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  762. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  763. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  764. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  765. }
  766. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  767. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  768. this._batchCache.mustReturn = true;
  769. return this._batchCache;
  770. }
  771. if (currentRenderId !== selfRenderId) {
  772. this._batchCache.renderSelf[subMeshId] = false;
  773. }
  774. }
  775. this._renderIdForInstances[subMeshId] = currentRenderId;
  776. }
  777. return this._batchCache;
  778. }
  779. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  780. var visibleInstances = batch.visibleInstances[subMesh._id];
  781. var matricesCount = visibleInstances.length + 1;
  782. var bufferSize = matricesCount * 16 * 4;
  783. while (this._instancesBufferSize < bufferSize) {
  784. this._instancesBufferSize *= 2;
  785. }
  786. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  787. if (this._worldMatricesInstancesBuffer) {
  788. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  789. }
  790. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  791. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  792. }
  793. var offset = 0;
  794. var instancesCount = 0;
  795. var world = this.getWorldMatrix();
  796. if (batch.renderSelf[subMesh._id]) {
  797. world.copyToArray(this._worldMatricesInstancesArray, offset);
  798. offset += 16;
  799. instancesCount++;
  800. }
  801. if (visibleInstances) {
  802. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  803. var instance = visibleInstances[instanceIndex];
  804. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  805. offset += 16;
  806. instancesCount++;
  807. }
  808. }
  809. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  810. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  811. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  812. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  813. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  814. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  815. this._draw(subMesh, fillMode, instancesCount);
  816. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  817. }
  818. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  819. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  820. var scene = this.getScene();
  821. var engine = scene.getEngine();
  822. if (hardwareInstancedRendering) {
  823. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  824. } else {
  825. if (batch.renderSelf[subMesh._id]) {
  826. // Draw
  827. if (onBeforeDraw) {
  828. onBeforeDraw(false, this.getWorldMatrix());
  829. }
  830. this._draw(subMesh, fillMode);
  831. }
  832. if (batch.visibleInstances[subMesh._id]) {
  833. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  834. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  835. // World
  836. var world = instance.getWorldMatrix();
  837. if (onBeforeDraw) {
  838. onBeforeDraw(true, world);
  839. }
  840. // Draw
  841. this._draw(subMesh, fillMode);
  842. }
  843. }
  844. }
  845. }
  846. /**
  847. * Triggers the draw call for the mesh.
  848. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  849. */
  850. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  851. var scene = this.getScene();
  852. // Managing instances
  853. var batch = this._getInstancesRenderList(subMesh._id);
  854. if (batch.mustReturn) {
  855. return;
  856. }
  857. // Checking geometry state
  858. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  859. return;
  860. }
  861. var callbackIndex: number;
  862. this.onBeforeRenderObservable.notifyObservers(this);
  863. var engine = scene.getEngine();
  864. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  865. // Material
  866. var effectiveMaterial = subMesh.getMaterial();
  867. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  868. return;
  869. }
  870. // Outline - step 1
  871. var savedDepthWrite = engine.getDepthWrite();
  872. if (this.renderOutline) {
  873. engine.setDepthWrite(false);
  874. scene.getOutlineRenderer().render(subMesh, batch);
  875. engine.setDepthWrite(savedDepthWrite);
  876. }
  877. effectiveMaterial._preBind();
  878. var effect = effectiveMaterial.getEffect();
  879. // Bind
  880. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  881. this._bind(subMesh, effect, fillMode);
  882. var world = this.getWorldMatrix();
  883. effectiveMaterial.bind(world, this);
  884. // Alpha mode
  885. if (enableAlphaMode) {
  886. engine.setAlphaMode(effectiveMaterial.alphaMode);
  887. }
  888. // Draw
  889. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  890. (isInstance, world) => {
  891. if (isInstance) {
  892. effectiveMaterial.bindOnlyWorldMatrix(world);
  893. }
  894. });
  895. // Unbind
  896. effectiveMaterial.unbind();
  897. // Outline - step 2
  898. if (this.renderOutline && savedDepthWrite) {
  899. engine.setDepthWrite(true);
  900. engine.setColorWrite(false);
  901. scene.getOutlineRenderer().render(subMesh, batch);
  902. engine.setColorWrite(true);
  903. }
  904. // Overlay
  905. if (this.renderOverlay) {
  906. var currentMode = engine.getAlphaMode();
  907. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  908. scene.getOutlineRenderer().render(subMesh, batch, true);
  909. engine.setAlphaMode(currentMode);
  910. }
  911. this.onAfterRenderObservable.notifyObservers(this);
  912. }
  913. /**
  914. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  915. */
  916. public getEmittedParticleSystems(): ParticleSystem[] {
  917. var results = new Array<ParticleSystem>();
  918. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  919. var particleSystem = this.getScene().particleSystems[index];
  920. if (particleSystem.emitter === this) {
  921. results.push(particleSystem);
  922. }
  923. }
  924. return results;
  925. }
  926. /**
  927. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  928. */
  929. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  930. var results = new Array<ParticleSystem>();
  931. var descendants = this.getDescendants();
  932. descendants.push(this);
  933. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  934. var particleSystem = this.getScene().particleSystems[index];
  935. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  936. results.push(particleSystem);
  937. }
  938. }
  939. return results;
  940. }
  941. public _checkDelayState(): void {
  942. var that = this;
  943. var scene = this.getScene();
  944. if (this._geometry) {
  945. this._geometry.load(scene);
  946. }
  947. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  948. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  949. scene._addPendingData(that);
  950. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  951. Tools.LoadFile(this.delayLoadingFile, data => {
  952. if (data instanceof ArrayBuffer) {
  953. this._delayLoadingFunction(data, this);
  954. }
  955. else {
  956. this._delayLoadingFunction(JSON.parse(data), this);
  957. }
  958. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  959. scene._removePendingData(this);
  960. }, () => { }, scene.database, getBinaryData);
  961. }
  962. }
  963. /**
  964. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  965. */
  966. public isInFrustum(frustumPlanes: Plane[]): boolean {
  967. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  968. return false;
  969. }
  970. if (!super.isInFrustum(frustumPlanes)) {
  971. return false;
  972. }
  973. this._checkDelayState();
  974. return true;
  975. }
  976. /**
  977. * Sets the mesh material by the material or multiMaterial `id` property.
  978. * The material `id` is a string identifying the material or the multiMaterial.
  979. * This method returns nothing.
  980. */
  981. public setMaterialByID(id: string): void {
  982. var materials = this.getScene().materials;
  983. var index: number;
  984. for (index = 0; index < materials.length; index++) {
  985. if (materials[index].id === id) {
  986. this.material = materials[index];
  987. return;
  988. }
  989. }
  990. // Multi
  991. var multiMaterials = this.getScene().multiMaterials;
  992. for (index = 0; index < multiMaterials.length; index++) {
  993. if (multiMaterials[index].id === id) {
  994. this.material = multiMaterials[index];
  995. return;
  996. }
  997. }
  998. }
  999. /**
  1000. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  1001. */
  1002. public getAnimatables(): IAnimatable[] {
  1003. var results = [];
  1004. if (this.material) {
  1005. results.push(this.material);
  1006. }
  1007. if (this.skeleton) {
  1008. results.push(this.skeleton);
  1009. }
  1010. return results;
  1011. }
  1012. /**
  1013. * Modifies the mesh geometry according to the passed transformation matrix.
  1014. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  1015. * The mesh normals are modified accordingly the same transformation.
  1016. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1017. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1018. */
  1019. public bakeTransformIntoVertices(transform: Matrix): void {
  1020. // Position
  1021. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1022. return;
  1023. }
  1024. this._resetPointsArrayCache();
  1025. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1026. var temp = [];
  1027. var index: number;
  1028. for (index = 0; index < data.length; index += 3) {
  1029. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1030. }
  1031. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  1032. // Normals
  1033. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1034. return;
  1035. }
  1036. data = this.getVerticesData(VertexBuffer.NormalKind);
  1037. temp = [];
  1038. for (index = 0; index < data.length; index += 3) {
  1039. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1040. }
  1041. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  1042. // flip faces?
  1043. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1044. }
  1045. /**
  1046. * Modifies the mesh geometry according to its own current World Matrix.
  1047. * The mesh World Matrix is then reset.
  1048. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  1049. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1050. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1051. */
  1052. public bakeCurrentTransformIntoVertices(): void {
  1053. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1054. this.scaling.copyFromFloats(1, 1, 1);
  1055. this.position.copyFromFloats(0, 0, 0);
  1056. this.rotation.copyFromFloats(0, 0, 0);
  1057. //only if quaternion is already set
  1058. if (this.rotationQuaternion) {
  1059. this.rotationQuaternion = Quaternion.Identity();
  1060. }
  1061. this._worldMatrix = Matrix.Identity();
  1062. }
  1063. // Cache
  1064. public _resetPointsArrayCache(): void {
  1065. this._positions = null;
  1066. }
  1067. public _generatePointsArray(): boolean {
  1068. if (this._positions)
  1069. return true;
  1070. this._positions = [];
  1071. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1072. if (!data) {
  1073. return false;
  1074. }
  1075. for (var index = 0; index < data.length; index += 3) {
  1076. this._positions.push(Vector3.FromArray(data, index));
  1077. }
  1078. return true;
  1079. }
  1080. /**
  1081. * Returns a new `Mesh` object generated from the current mesh properties.
  1082. * This method must not get confused with createInstance().
  1083. * The parameter `name` is a string, the name given to the new mesh.
  1084. * The optional parameter `newParent` can be any `Node` object (default `null`).
  1085. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  1086. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  1087. */
  1088. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1089. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1090. }
  1091. /**
  1092. * Disposes the mesh.
  1093. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  1094. */
  1095. public dispose(doNotRecurse?: boolean): void {
  1096. if (this._geometry) {
  1097. this._geometry.releaseForMesh(this, true);
  1098. }
  1099. // Instances
  1100. if (this._worldMatricesInstancesBuffer) {
  1101. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  1102. this._worldMatricesInstancesBuffer = null;
  1103. }
  1104. while (this.instances.length) {
  1105. this.instances[0].dispose();
  1106. }
  1107. super.dispose(doNotRecurse);
  1108. }
  1109. /**
  1110. * Modifies the mesh geometry according to a displacement map.
  1111. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1112. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1113. * This method returns nothing.
  1114. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  1115. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1116. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  1117. */
  1118. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  1119. var scene = this.getScene();
  1120. var onload = img => {
  1121. // Getting height map data
  1122. var canvas = document.createElement("canvas");
  1123. var context = canvas.getContext("2d");
  1124. var heightMapWidth = img.width;
  1125. var heightMapHeight = img.height;
  1126. canvas.width = heightMapWidth;
  1127. canvas.height = heightMapHeight;
  1128. context.drawImage(img, 0, 0);
  1129. // Create VertexData from map data
  1130. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1131. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1132. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  1133. //execute success callback, if set
  1134. if (onSuccess) {
  1135. onSuccess(this);
  1136. }
  1137. };
  1138. Tools.LoadImage(url, onload, () => { }, scene.database);
  1139. }
  1140. /**
  1141. * Modifies the mesh geometry according to a displacementMap buffer.
  1142. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1143. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1144. * This method returns nothing.
  1145. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  1146. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  1147. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1148. */
  1149. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  1150. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1151. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1152. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1153. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1154. return;
  1155. }
  1156. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1157. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1158. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  1159. var position = Vector3.Zero();
  1160. var normal = Vector3.Zero();
  1161. var uv = Vector2.Zero();
  1162. for (var index = 0; index < positions.length; index += 3) {
  1163. Vector3.FromArrayToRef(positions, index, position);
  1164. Vector3.FromArrayToRef(normals, index, normal);
  1165. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1166. // Compute height
  1167. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  1168. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  1169. var pos = (u + v * heightMapWidth) * 4;
  1170. var r = buffer[pos] / 255.0;
  1171. var g = buffer[pos + 1] / 255.0;
  1172. var b = buffer[pos + 2] / 255.0;
  1173. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1174. normal.normalize();
  1175. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1176. position = position.add(normal);
  1177. position.toArray(positions, index);
  1178. }
  1179. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1180. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1181. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1182. }
  1183. /**
  1184. * Modify the mesh to get a flat shading rendering.
  1185. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1186. * This method returns nothing.
  1187. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  1188. */
  1189. public convertToFlatShadedMesh(): void {
  1190. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  1191. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1192. var kinds = this.getVerticesDataKinds();
  1193. var vbs = [];
  1194. var data = [];
  1195. var newdata = [];
  1196. var updatableNormals = false;
  1197. var kindIndex: number;
  1198. var kind: string;
  1199. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1200. kind = kinds[kindIndex];
  1201. var vertexBuffer = this.getVertexBuffer(kind);
  1202. if (kind === VertexBuffer.NormalKind) {
  1203. updatableNormals = vertexBuffer.isUpdatable();
  1204. kinds.splice(kindIndex, 1);
  1205. kindIndex--;
  1206. continue;
  1207. }
  1208. vbs[kind] = vertexBuffer;
  1209. data[kind] = vbs[kind].getData();
  1210. newdata[kind] = [];
  1211. }
  1212. // Save previous submeshes
  1213. var previousSubmeshes = this.subMeshes.slice(0);
  1214. var indices = this.getIndices();
  1215. var totalIndices = this.getTotalIndices();
  1216. // Generating unique vertices per face
  1217. var index: number;
  1218. for (index = 0; index < totalIndices; index++) {
  1219. var vertexIndex = indices[index];
  1220. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1221. kind = kinds[kindIndex];
  1222. var stride = vbs[kind].getStrideSize();
  1223. for (var offset = 0; offset < stride; offset++) {
  1224. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1225. }
  1226. }
  1227. }
  1228. // Updating faces & normal
  1229. var normals = [];
  1230. var positions = newdata[VertexBuffer.PositionKind];
  1231. for (index = 0; index < totalIndices; index += 3) {
  1232. indices[index] = index;
  1233. indices[index + 1] = index + 1;
  1234. indices[index + 2] = index + 2;
  1235. var p1 = Vector3.FromArray(positions, index * 3);
  1236. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1237. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1238. var p1p2 = p1.subtract(p2);
  1239. var p3p2 = p3.subtract(p2);
  1240. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1241. // Store same normals for every vertex
  1242. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1243. normals.push(normal.x);
  1244. normals.push(normal.y);
  1245. normals.push(normal.z);
  1246. }
  1247. }
  1248. this.setIndices(indices);
  1249. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1250. // Updating vertex buffers
  1251. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1252. kind = kinds[kindIndex];
  1253. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1254. }
  1255. // Updating submeshes
  1256. this.releaseSubMeshes();
  1257. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1258. var previousOne = previousSubmeshes[submeshIndex];
  1259. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1260. }
  1261. this.synchronizeInstances();
  1262. }
  1263. /**
  1264. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1265. * In other words, more vertices, no more indices and a single bigger VBO.
  1266. * This method returns nothing.
  1267. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  1268. *
  1269. */
  1270. public convertToUnIndexedMesh(): void {
  1271. /// <summary>Remove indices by unfolding faces into buffers</summary>
  1272. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1273. var kinds = this.getVerticesDataKinds();
  1274. var vbs = [];
  1275. var data = [];
  1276. var newdata = [];
  1277. var updatableNormals = false;
  1278. var kindIndex: number;
  1279. var kind: string;
  1280. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1281. kind = kinds[kindIndex];
  1282. var vertexBuffer = this.getVertexBuffer(kind);
  1283. vbs[kind] = vertexBuffer;
  1284. data[kind] = vbs[kind].getData();
  1285. newdata[kind] = [];
  1286. }
  1287. // Save previous submeshes
  1288. var previousSubmeshes = this.subMeshes.slice(0);
  1289. var indices = this.getIndices();
  1290. var totalIndices = this.getTotalIndices();
  1291. // Generating unique vertices per face
  1292. var index: number;
  1293. for (index = 0; index < totalIndices; index++) {
  1294. var vertexIndex = indices[index];
  1295. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1296. kind = kinds[kindIndex];
  1297. var stride = vbs[kind].getStrideSize();
  1298. for (var offset = 0; offset < stride; offset++) {
  1299. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1300. }
  1301. }
  1302. }
  1303. // Updating indices
  1304. for (index = 0; index < totalIndices; index += 3) {
  1305. indices[index] = index;
  1306. indices[index + 1] = index + 1;
  1307. indices[index + 2] = index + 2;
  1308. }
  1309. this.setIndices(indices);
  1310. // Updating vertex buffers
  1311. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1312. kind = kinds[kindIndex];
  1313. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1314. }
  1315. // Updating submeshes
  1316. this.releaseSubMeshes();
  1317. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1318. var previousOne = previousSubmeshes[submeshIndex];
  1319. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1320. }
  1321. this._unIndexed = true;
  1322. this.synchronizeInstances();
  1323. }
  1324. /**
  1325. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  1326. * This method returns nothing.
  1327. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  1328. */
  1329. public flipFaces(flipNormals: boolean = false): void {
  1330. var vertex_data = VertexData.ExtractFromMesh(this);
  1331. var i: number;
  1332. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1333. for (i = 0; i < vertex_data.normals.length; i++) {
  1334. vertex_data.normals[i] *= -1;
  1335. }
  1336. }
  1337. var temp;
  1338. for (i = 0; i < vertex_data.indices.length; i += 3) {
  1339. // reassign indices
  1340. temp = vertex_data.indices[i + 1];
  1341. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  1342. vertex_data.indices[i + 2] = temp;
  1343. }
  1344. vertex_data.applyToMesh(this);
  1345. }
  1346. // Instances
  1347. /**
  1348. * Creates a new `InstancedMesh` object from the mesh model.
  1349. * An instance shares the same properties and the same material than its model.
  1350. * Only these properties of each instance can then be set individually :
  1351. * - position
  1352. * - rotation
  1353. * - rotationQuaternion
  1354. * - setPivotMatrix
  1355. * - scaling
  1356. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  1357. */
  1358. public createInstance(name: string): InstancedMesh {
  1359. return new InstancedMesh(name, this);
  1360. }
  1361. /**
  1362. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  1363. * After this call, all the mesh instances have the same submeshes than the current mesh.
  1364. * This method returns nothing.
  1365. */
  1366. public synchronizeInstances(): void {
  1367. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  1368. var instance = this.instances[instanceIndex];
  1369. instance._syncSubMeshes();
  1370. }
  1371. }
  1372. /**
  1373. * Simplify the mesh according to the given array of settings.
  1374. * Function will return immediately and will simplify async. It returns nothing.
  1375. * @param settings a collection of simplification settings.
  1376. * @param parallelProcessing should all levels calculate parallel or one after the other.
  1377. * @param type the type of simplification to run.
  1378. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  1379. */
  1380. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  1381. this.getScene().simplificationQueue.addTask({
  1382. settings: settings,
  1383. parallelProcessing: parallelProcessing,
  1384. mesh: this,
  1385. simplificationType: simplificationType,
  1386. successCallback: successCallback
  1387. });
  1388. }
  1389. /**
  1390. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  1391. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  1392. * This should be used together with the simplification to avoid disappearing triangles.
  1393. * @param successCallback an optional success callback to be called after the optimization finished.
  1394. */
  1395. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  1396. var indices = this.getIndices();
  1397. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1398. var vectorPositions = [];
  1399. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  1400. vectorPositions.push(Vector3.FromArray(positions, pos));
  1401. }
  1402. var dupes = [];
  1403. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  1404. var realPos = vectorPositions.length - 1 - iteration;
  1405. var testedPosition = vectorPositions[realPos];
  1406. for (var j = 0; j < realPos; ++j) {
  1407. var againstPosition = vectorPositions[j];
  1408. if (testedPosition.equals(againstPosition)) {
  1409. dupes[realPos] = j;
  1410. break;
  1411. }
  1412. }
  1413. }, () => {
  1414. for (var i = 0; i < indices.length; ++i) {
  1415. indices[i] = dupes[indices[i]] || indices[i];
  1416. }
  1417. //indices are now reordered
  1418. var originalSubMeshes = this.subMeshes.slice(0);
  1419. this.setIndices(indices);
  1420. this.subMeshes = originalSubMeshes;
  1421. if (successCallback) {
  1422. successCallback(this);
  1423. }
  1424. });
  1425. }
  1426. // Statics
  1427. /**
  1428. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  1429. * The parameter `parsedMesh` is the mesh to be copied.
  1430. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  1431. *
  1432. */
  1433. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  1434. var mesh = new Mesh(parsedMesh.name, scene);
  1435. mesh.id = parsedMesh.id;
  1436. Tags.AddTagsTo(mesh, parsedMesh.tags);
  1437. mesh.position = Vector3.FromArray(parsedMesh.position);
  1438. if (parsedMesh.rotationQuaternion) {
  1439. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  1440. } else if (parsedMesh.rotation) {
  1441. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  1442. }
  1443. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  1444. if (parsedMesh.localMatrix) {
  1445. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  1446. } else if (parsedMesh.pivotMatrix) {
  1447. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  1448. }
  1449. mesh.setEnabled(parsedMesh.isEnabled);
  1450. mesh.isVisible = parsedMesh.isVisible;
  1451. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  1452. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  1453. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  1454. if (parsedMesh.applyFog !== undefined) {
  1455. mesh.applyFog = parsedMesh.applyFog;
  1456. }
  1457. if (parsedMesh.pickable !== undefined) {
  1458. mesh.isPickable = parsedMesh.pickable;
  1459. }
  1460. if (parsedMesh.alphaIndex !== undefined) {
  1461. mesh.alphaIndex = parsedMesh.alphaIndex;
  1462. }
  1463. mesh.receiveShadows = parsedMesh.receiveShadows;
  1464. mesh.billboardMode = parsedMesh.billboardMode;
  1465. if (parsedMesh.visibility !== undefined) {
  1466. mesh.visibility = parsedMesh.visibility;
  1467. }
  1468. mesh.checkCollisions = parsedMesh.checkCollisions;
  1469. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  1470. // freezeWorldMatrix
  1471. if (parsedMesh.freezeWorldMatrix) {
  1472. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  1473. }
  1474. // Parent
  1475. if (parsedMesh.parentId) {
  1476. mesh._waitingParentId = parsedMesh.parentId;
  1477. }
  1478. // Actions
  1479. if (parsedMesh.actions !== undefined) {
  1480. mesh._waitingActions = parsedMesh.actions;
  1481. }
  1482. // Geometry
  1483. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  1484. if (parsedMesh.delayLoadingFile) {
  1485. mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1486. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  1487. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  1488. if (parsedMesh._binaryInfo) {
  1489. mesh._binaryInfo = parsedMesh._binaryInfo;
  1490. }
  1491. mesh._delayInfo = [];
  1492. if (parsedMesh.hasUVs) {
  1493. mesh._delayInfo.push(VertexBuffer.UVKind);
  1494. }
  1495. if (parsedMesh.hasUVs2) {
  1496. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  1497. }
  1498. if (parsedMesh.hasUVs3) {
  1499. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  1500. }
  1501. if (parsedMesh.hasUVs4) {
  1502. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  1503. }
  1504. if (parsedMesh.hasUVs5) {
  1505. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  1506. }
  1507. if (parsedMesh.hasUVs6) {
  1508. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  1509. }
  1510. if (parsedMesh.hasColors) {
  1511. mesh._delayInfo.push(VertexBuffer.ColorKind);
  1512. }
  1513. if (parsedMesh.hasMatricesIndices) {
  1514. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1515. }
  1516. if (parsedMesh.hasMatricesWeights) {
  1517. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1518. }
  1519. mesh._delayLoadingFunction = Geometry.ImportGeometry;
  1520. if (SceneLoader.ForceFullSceneLoadingForIncremental) {
  1521. mesh._checkDelayState();
  1522. }
  1523. } else {
  1524. Geometry.ImportGeometry(parsedMesh, mesh);
  1525. }
  1526. // Material
  1527. if (parsedMesh.materialId) {
  1528. mesh.setMaterialByID(parsedMesh.materialId);
  1529. } else {
  1530. mesh.material = null;
  1531. }
  1532. // Skeleton
  1533. if (parsedMesh.skeletonId > -1) {
  1534. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  1535. if (parsedMesh.numBoneInfluencers) {
  1536. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  1537. }
  1538. }
  1539. // Animations
  1540. if (parsedMesh.animations) {
  1541. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1542. var parsedAnimation = parsedMesh.animations[animationIndex];
  1543. mesh.animations.push(Animation.Parse(parsedAnimation));
  1544. }
  1545. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  1546. }
  1547. if (parsedMesh.autoAnimate) {
  1548. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  1549. }
  1550. // Layer Mask
  1551. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  1552. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  1553. } else {
  1554. mesh.layerMask = 0x0FFFFFFF;
  1555. }
  1556. //(Deprecated) physics
  1557. if (parsedMesh.physicsImpostor) {
  1558. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  1559. mass: parsedMesh.physicsMass,
  1560. friction: parsedMesh.physicsFriction,
  1561. restitution: parsedMesh.physicsRestitution
  1562. }, scene);
  1563. }
  1564. // Instances
  1565. if (parsedMesh.instances) {
  1566. for (var index = 0; index < parsedMesh.instances.length; index++) {
  1567. var parsedInstance = parsedMesh.instances[index];
  1568. var instance = mesh.createInstance(parsedInstance.name);
  1569. Tags.AddTagsTo(instance, parsedInstance.tags);
  1570. instance.position = Vector3.FromArray(parsedInstance.position);
  1571. if (parsedInstance.rotationQuaternion) {
  1572. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  1573. } else if (parsedInstance.rotation) {
  1574. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  1575. }
  1576. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  1577. instance.checkCollisions = mesh.checkCollisions;
  1578. if (parsedMesh.animations) {
  1579. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1580. parsedAnimation = parsedMesh.animations[animationIndex];
  1581. instance.animations.push(Animation.Parse(parsedAnimation));
  1582. }
  1583. Node.ParseAnimationRanges(instance, parsedMesh, scene);
  1584. }
  1585. }
  1586. }
  1587. return mesh;
  1588. }
  1589. /**
  1590. * Creates a ribbon mesh.
  1591. * Please consider using the same method from the `MeshBuilder` class instead.
  1592. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1593. *
  1594. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  1595. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  1596. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  1597. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  1598. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  1599. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  1600. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  1601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1602. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1604. */
  1605. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1606. return MeshBuilder.CreateRibbon(name, {
  1607. pathArray: pathArray,
  1608. closeArray: closeArray,
  1609. closePath: closePath,
  1610. offset: offset,
  1611. updatable: updatable,
  1612. sideOrientation: sideOrientation,
  1613. instance: instance
  1614. }, scene);
  1615. }
  1616. /**
  1617. * Creates a plane polygonal mesh. By default, this is a disc.
  1618. * Please consider using the same method from the `MeshBuilder` class instead.
  1619. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  1620. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  1621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1624. */
  1625. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1626. var options = {
  1627. radius: radius,
  1628. tessellation: tessellation,
  1629. sideOrientation: sideOrientation,
  1630. updatable: updatable
  1631. }
  1632. return MeshBuilder.CreateDisc(name, options, scene);
  1633. }
  1634. /**
  1635. * Creates a box mesh.
  1636. * Please consider using the same method from the `MeshBuilder` class instead.
  1637. * The parameter `size` sets the size (float) of each box side (default 1).
  1638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1641. */
  1642. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1643. var options = {
  1644. size: size,
  1645. sideOrientation: sideOrientation,
  1646. updatable: updatable
  1647. };
  1648. return MeshBuilder.CreateBox(name, options, scene);
  1649. }
  1650. /**
  1651. * Creates a sphere mesh.
  1652. * Please consider using the same method from the `MeshBuilder` class instead.
  1653. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  1654. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  1655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1656. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1658. */
  1659. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1660. var options = {
  1661. segments: segments,
  1662. diameterX: diameter,
  1663. diameterY: diameter,
  1664. diameterZ: diameter,
  1665. sideOrientation: sideOrientation,
  1666. updatable: updatable
  1667. }
  1668. return MeshBuilder.CreateSphere(name, options, scene);
  1669. }
  1670. /**
  1671. * Creates a cylinder or a cone mesh.
  1672. * Please consider using the same method from the `MeshBuilder` class instead.
  1673. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  1674. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  1675. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  1676. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  1677. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  1678. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1679. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1680. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1681. */
  1682. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh {
  1683. if (scene === undefined || !(scene instanceof Scene)) {
  1684. if (scene !== undefined) {
  1685. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  1686. updatable = scene;
  1687. }
  1688. scene = <Scene>subdivisions;
  1689. subdivisions = 1;
  1690. }
  1691. var options = {
  1692. height: height,
  1693. diameterTop: diameterTop,
  1694. diameterBottom: diameterBottom,
  1695. tessellation: tessellation,
  1696. subdivisions: subdivisions,
  1697. sideOrientation: sideOrientation,
  1698. updatable: updatable
  1699. }
  1700. return MeshBuilder.CreateCylinder(name, options, scene);
  1701. }
  1702. // Torus (Code from SharpDX.org)
  1703. /**
  1704. * Creates a torus mesh.
  1705. * Please consider using the same method from the `MeshBuilder` class instead.
  1706. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  1707. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  1708. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  1709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1710. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1712. */
  1713. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1714. var options = {
  1715. diameter: diameter,
  1716. thickness: thickness,
  1717. tessellation: tessellation,
  1718. sideOrientation: sideOrientation,
  1719. updatable: updatable
  1720. }
  1721. return MeshBuilder.CreateTorus(name, options, scene);
  1722. }
  1723. /**
  1724. * Creates a torus knot mesh.
  1725. * Please consider using the same method from the `MeshBuilder` class instead.
  1726. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  1727. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  1728. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  1729. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  1730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1733. */
  1734. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1735. var options = {
  1736. radius: radius,
  1737. tube: tube,
  1738. radialSegments: radialSegments,
  1739. tubularSegments: tubularSegments,
  1740. p: p,
  1741. q: q,
  1742. sideOrientation: sideOrientation,
  1743. updatable: updatable
  1744. }
  1745. return MeshBuilder.CreateTorusKnot(name, options, scene);
  1746. }
  1747. /**
  1748. * Creates a line mesh.
  1749. * Please consider using the same method from the `MeshBuilder` class instead.
  1750. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1751. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1752. * The parameter `points` is an array successive Vector3.
  1753. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1754. * When updating an instance, remember that only point positions can change, not the number of points.
  1755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1756. */
  1757. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1758. var options = {
  1759. points: points,
  1760. updatable: updatable,
  1761. instance: instance
  1762. }
  1763. return MeshBuilder.CreateLines(name, options, scene);
  1764. }
  1765. /**
  1766. * Creates a dashed line mesh.
  1767. * Please consider using the same method from the `MeshBuilder` class instead.
  1768. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1769. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1770. * The parameter `points` is an array successive Vector3.
  1771. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  1772. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  1773. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  1774. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1775. * When updating an instance, remember that only point positions can change, not the number of points.
  1776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1777. */
  1778. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1779. var options = {
  1780. points: points,
  1781. dashSize: dashSize,
  1782. gapSize: gapSize,
  1783. dashNb: dashNb,
  1784. updatable: updatable
  1785. }
  1786. return MeshBuilder.CreateDashedLines(name, options, scene);
  1787. }
  1788. /**
  1789. * Creates an extruded shape mesh.
  1790. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1791. * Please consider using the same method from the `MeshBuilder` class instead.
  1792. *
  1793. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1794. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1795. * extruded along the Z axis.
  1796. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1797. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  1798. * The parameter `scale` (float, default 1) is the value to scale the shape.
  1799. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1800. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1801. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1803. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1805. */
  1806. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1807. var options = {
  1808. shape: shape,
  1809. path: path,
  1810. scale: scale,
  1811. rotation: rotation,
  1812. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1813. sideOrientation: sideOrientation,
  1814. instance: instance,
  1815. updatable: updatable
  1816. }
  1817. return MeshBuilder.ExtrudeShape(name, options, scene);
  1818. }
  1819. /**
  1820. * Creates an custom extruded shape mesh.
  1821. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1822. * Please consider using the same method from the `MeshBuilder` class instead.
  1823. *
  1824. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1825. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1826. * extruded along the Z axis.
  1827. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1828. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1829. * and the distance of this point from the begining of the path :
  1830. * ```rotationFunction = function(i, distance) {
  1831. * // do things
  1832. * return rotationValue; }```
  1833. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  1834. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1835. * and the distance of this point from the begining of the path :
  1836. * ````scaleFunction = function(i, distance) {
  1837. * // do things
  1838. * return scaleValue;}```
  1839. * It must returns a float value that will be the scale value applied to the shape on each path point.
  1840. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  1841. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  1842. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1843. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1844. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1848. */
  1849. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1850. var options = {
  1851. shape: shape,
  1852. path: path,
  1853. scaleFunction: scaleFunction,
  1854. rotationFunction: rotationFunction,
  1855. ribbonCloseArray: ribbonCloseArray,
  1856. ribbonClosePath: ribbonClosePath,
  1857. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1858. sideOrientation: sideOrientation,
  1859. instance: instance,
  1860. updatable: updatable
  1861. }
  1862. return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  1863. }
  1864. /**
  1865. * Creates lathe mesh.
  1866. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  1867. * Please consider using the same method from the `MeshBuilder` class instead.
  1868. *
  1869. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  1870. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  1871. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  1872. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  1873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1876. */
  1877. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1878. var options = {
  1879. shape: shape,
  1880. radius: radius,
  1881. tessellation: tessellation,
  1882. sideOrientation: sideOrientation,
  1883. updatable: updatable
  1884. };
  1885. return MeshBuilder.CreateLathe(name, options, scene);
  1886. }
  1887. /**
  1888. * Creates a plane mesh.
  1889. * Please consider using the same method from the `MeshBuilder` class instead.
  1890. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  1891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1894. */
  1895. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1896. var options = {
  1897. size: size,
  1898. width: size,
  1899. height: size,
  1900. sideOrientation: sideOrientation,
  1901. updatable: updatable
  1902. }
  1903. return MeshBuilder.CreatePlane(name, options, scene);
  1904. }
  1905. /**
  1906. * Creates a ground mesh.
  1907. * Please consider using the same method from the `MeshBuilder` class instead.
  1908. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  1909. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  1910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1911. */
  1912. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1913. var options = {
  1914. width: width,
  1915. height: height,
  1916. subdivisions: subdivisions,
  1917. updatable: updatable
  1918. }
  1919. return MeshBuilder.CreateGround(name, options, scene);
  1920. }
  1921. /**
  1922. * Creates a tiled ground mesh.
  1923. * Please consider using the same method from the `MeshBuilder` class instead.
  1924. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  1925. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  1926. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  1927. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  1928. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  1929. * numbers of subdivisions on the ground width and height of each tile.
  1930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1931. */
  1932. 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 {
  1933. var options = {
  1934. xmin: xmin,
  1935. zmin: zmin,
  1936. xmax: xmax,
  1937. zmax: zmax,
  1938. subdivisions: subdivisions,
  1939. precision: precision,
  1940. updatable: updatable
  1941. }
  1942. return MeshBuilder.CreateTiledGround(name, options, scene);
  1943. }
  1944. /**
  1945. * Creates a ground mesh from a height map.
  1946. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  1947. * Please consider using the same method from the `MeshBuilder` class instead.
  1948. * The parameter `url` sets the URL of the height map image resource.
  1949. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  1950. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  1951. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  1952. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  1953. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  1954. * This function is passed the newly built mesh : ```function(mesh) { // do things
  1955. * return; }```
  1956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1957. */
  1958. 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 {
  1959. var options = {
  1960. width: width,
  1961. height: height,
  1962. subdivisions: subdivisions,
  1963. minHeight: minHeight,
  1964. maxHeight: maxHeight,
  1965. updatable: updatable,
  1966. onReady: onReady
  1967. };
  1968. return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  1969. }
  1970. /**
  1971. * Creates a tube mesh.
  1972. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1973. *
  1974. * Please consider using the same method from the `MeshBuilder` class instead.
  1975. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  1976. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  1977. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  1978. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  1979. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  1980. * It must return a radius value (positive float) :
  1981. * ```var radiusFunction = function(i, distance) {
  1982. * // do things
  1983. * return radius; }```
  1984. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1985. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  1986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1989. */
  1990. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1991. var options = {
  1992. path: path,
  1993. radius: radius,
  1994. tessellation: tessellation,
  1995. radiusFunction: radiusFunction,
  1996. arc: 1,
  1997. cap: cap,
  1998. updatable: updatable,
  1999. sideOrientation: sideOrientation,
  2000. instance: instance
  2001. }
  2002. return MeshBuilder.CreateTube(name, options, scene);
  2003. }
  2004. /**
  2005. * Creates a polyhedron mesh.
  2006. *
  2007. * Please consider using the same method from the `MeshBuilder` class instead.
  2008. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  2009. * to choose the wanted type.
  2010. * The parameter `size` (positive float, default 1) sets the polygon size.
  2011. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  2012. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  2013. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  2014. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  2015. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  2016. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  2017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2020. */
  2021. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  2022. return MeshBuilder.CreatePolyhedron(name, options, scene);
  2023. }
  2024. /**
  2025. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  2026. * Please consider using the same method from the `MeshBuilder` class instead.
  2027. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  2028. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  2029. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  2030. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  2031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2032. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2034. */
  2035. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  2036. return MeshBuilder.CreateIcoSphere(name, options, scene);
  2037. }
  2038. /**
  2039. * Creates a decal mesh.
  2040. * Please consider using the same method from the `MeshBuilder` class instead.
  2041. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  2042. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  2043. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  2044. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  2045. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  2046. */
  2047. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  2048. var options = {
  2049. position: position,
  2050. normal: normal,
  2051. size: size,
  2052. angle: angle
  2053. }
  2054. return MeshBuilder.CreateDecal(name, sourceMesh, options);
  2055. }
  2056. // Skeletons
  2057. /**
  2058. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2059. */
  2060. public setPositionsForCPUSkinning(): Float32Array {
  2061. var source: number[] | Float32Array;
  2062. if (!this._sourcePositions) {
  2063. source = this.getVerticesData(VertexBuffer.PositionKind);
  2064. this._sourcePositions = new Float32Array(<any>source);
  2065. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  2066. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  2067. }
  2068. }
  2069. return this._sourcePositions;
  2070. }
  2071. /**
  2072. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2073. */
  2074. public setNormalsForCPUSkinning(): Float32Array {
  2075. var source: number[] | Float32Array;
  2076. if (!this._sourceNormals) {
  2077. source = this.getVerticesData(VertexBuffer.NormalKind);
  2078. this._sourceNormals = new Float32Array(<any>source);
  2079. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  2080. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  2081. }
  2082. }
  2083. return this._sourceNormals;
  2084. }
  2085. /**
  2086. * Update the vertex buffers by applying transformation from the bones
  2087. * @param {skeleton} skeleton to apply
  2088. */
  2089. public applySkeleton(skeleton: Skeleton): Mesh {
  2090. if (!this.geometry) {
  2091. return;
  2092. }
  2093. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  2094. return;
  2095. }
  2096. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  2097. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  2098. return this;
  2099. }
  2100. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  2101. return this;
  2102. }
  2103. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  2104. return this;
  2105. }
  2106. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  2107. return this;
  2108. }
  2109. if (!this._sourcePositions) {
  2110. this.setPositionsForCPUSkinning();
  2111. }
  2112. if (!this._sourceNormals) {
  2113. this.setNormalsForCPUSkinning();
  2114. }
  2115. // positionsData checks for not being Float32Array will only pass at most once
  2116. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  2117. if (!(positionsData instanceof Float32Array)) {
  2118. positionsData = new Float32Array(positionsData);
  2119. }
  2120. // normalsData checks for not being Float32Array will only pass at most once
  2121. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  2122. if (!(normalsData instanceof Float32Array)) {
  2123. normalsData = new Float32Array(normalsData);
  2124. }
  2125. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  2126. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  2127. var needExtras = this.numBoneInfluencers > 4;
  2128. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  2129. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  2130. var skeletonMatrices = skeleton.getTransformMatrices(this);
  2131. var tempVector3 = Vector3.Zero();
  2132. var finalMatrix = new Matrix();
  2133. var tempMatrix = new Matrix();
  2134. var matWeightIdx = 0;
  2135. var inf: number;
  2136. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  2137. var weight: number;
  2138. for (inf = 0; inf < 4; inf++) {
  2139. weight = matricesWeightsData[matWeightIdx + inf];
  2140. if (weight > 0) {
  2141. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2142. finalMatrix.addToSelf(tempMatrix);
  2143. } else break;
  2144. }
  2145. if (needExtras) {
  2146. for (inf = 0; inf < 4; inf++) {
  2147. weight = matricesWeightsExtraData[matWeightIdx + inf];
  2148. if (weight > 0) {
  2149. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2150. finalMatrix.addToSelf(tempMatrix);
  2151. } else break;
  2152. }
  2153. }
  2154. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  2155. tempVector3.toArray(positionsData, index);
  2156. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  2157. tempVector3.toArray(normalsData, index);
  2158. finalMatrix.reset();
  2159. }
  2160. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  2161. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  2162. return this;
  2163. }
  2164. // Tools
  2165. /**
  2166. * Returns an object `{min: Vector3, max: Vector3}`
  2167. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  2168. */
  2169. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  2170. var minVector: Vector3 = null;
  2171. var maxVector: Vector3 = null;
  2172. for (var i in meshes) {
  2173. var mesh = meshes[i];
  2174. var boundingBox = mesh.getBoundingInfo().boundingBox;
  2175. if (!minVector) {
  2176. minVector = boundingBox.minimumWorld;
  2177. maxVector = boundingBox.maximumWorld;
  2178. continue;
  2179. }
  2180. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  2181. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  2182. }
  2183. return {
  2184. min: minVector,
  2185. max: maxVector
  2186. };
  2187. }
  2188. /**
  2189. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  2190. */
  2191. public static Center(meshesOrMinMaxVector): Vector3 {
  2192. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  2193. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  2194. }
  2195. /**
  2196. * Merge the array of meshes into a single mesh for performance reasons.
  2197. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  2198. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  2199. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  2200. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  2201. */
  2202. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  2203. var index: number;
  2204. if (!allow32BitsIndices) {
  2205. var totalVertices = 0;
  2206. // Counting vertices
  2207. for (index = 0; index < meshes.length; index++) {
  2208. if (meshes[index]) {
  2209. totalVertices += meshes[index].getTotalVertices();
  2210. if (totalVertices > 65536) {
  2211. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  2212. return null;
  2213. }
  2214. }
  2215. }
  2216. }
  2217. // Merge
  2218. var vertexData: VertexData;
  2219. var otherVertexData: VertexData;
  2220. var source: Mesh;
  2221. for (index = 0; index < meshes.length; index++) {
  2222. if (meshes[index]) {
  2223. meshes[index].computeWorldMatrix(true);
  2224. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  2225. otherVertexData.transform(meshes[index].getWorldMatrix());
  2226. if (vertexData) {
  2227. vertexData.merge(otherVertexData);
  2228. } else {
  2229. vertexData = otherVertexData;
  2230. source = meshes[index];
  2231. }
  2232. }
  2233. }
  2234. if (!meshSubclass) {
  2235. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  2236. }
  2237. vertexData.applyToMesh(meshSubclass);
  2238. // Setting properties
  2239. meshSubclass.material = source.material;
  2240. meshSubclass.checkCollisions = source.checkCollisions;
  2241. // Cleaning
  2242. if (disposeSource) {
  2243. for (index = 0; index < meshes.length; index++) {
  2244. if (meshes[index]) {
  2245. meshes[index].dispose();
  2246. }
  2247. }
  2248. }
  2249. return meshSubclass;
  2250. }
  2251. }
  2252. }