babylon.mesh.ts 156 KB

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