babylon.mesh.ts 145 KB

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