babylon.mesh.ts 127 KB

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