babylon.mesh.ts 144 KB

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