babylon.mesh.ts 126 KB

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