babylon.mesh.ts 118 KB

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