babylon.mesh.ts 157 KB

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