babylon.glTF1FileLoader.js 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. /// <reference path="../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * Mode that determines the coordinate system to use.
  7. */
  8. var GLTFLoaderCoordinateSystemMode;
  9. (function (GLTFLoaderCoordinateSystemMode) {
  10. /**
  11. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  14. /**
  15. * Sets the useRightHandedSystem flag on the scene.
  16. */
  17. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  18. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  19. /**
  20. * Mode that determines what animations will start.
  21. */
  22. var GLTFLoaderAnimationStartMode;
  23. (function (GLTFLoaderAnimationStartMode) {
  24. /**
  25. * No animation will start.
  26. */
  27. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  28. /**
  29. * The first animation will start.
  30. */
  31. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  32. /**
  33. * All animations will start.
  34. */
  35. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  36. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  37. /**
  38. * Loader state.
  39. */
  40. var GLTFLoaderState;
  41. (function (GLTFLoaderState) {
  42. /**
  43. * The asset is loading.
  44. */
  45. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  46. /**
  47. * The asset is ready for rendering.
  48. */
  49. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  50. /**
  51. * The asset is completely loaded.
  52. */
  53. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  54. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  55. /**
  56. * File loader for loading glTF files into a scene.
  57. */
  58. var GLTFFileLoader = /** @class */ (function () {
  59. function GLTFFileLoader() {
  60. // --------------
  61. // Common options
  62. // --------------
  63. /**
  64. * Raised when the asset has been parsed
  65. */
  66. this.onParsedObservable = new BABYLON.Observable();
  67. // ----------
  68. // V2 options
  69. // ----------
  70. /**
  71. * The coordinate system mode. Defaults to AUTO.
  72. */
  73. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  74. /**
  75. * The animation start mode. Defaults to FIRST.
  76. */
  77. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  78. /**
  79. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  80. */
  81. this.compileMaterials = false;
  82. /**
  83. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  84. */
  85. this.useClipPlane = false;
  86. /**
  87. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  88. */
  89. this.compileShadowGenerators = false;
  90. /**
  91. * Defines if the Alpha blended materials are only applied as coverage.
  92. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  93. * If true, no extra effects are applied to transparent pixels.
  94. */
  95. this.transparencyAsCoverage = false;
  96. /**
  97. * Function called before loading a url referenced by the asset.
  98. */
  99. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  100. /**
  101. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102. */
  103. this.onMeshLoadedObservable = new BABYLON.Observable();
  104. /**
  105. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106. */
  107. this.onTextureLoadedObservable = new BABYLON.Observable();
  108. /**
  109. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  110. */
  111. this.onMaterialLoadedObservable = new BABYLON.Observable();
  112. /**
  113. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  114. */
  115. this.onCameraLoadedObservable = new BABYLON.Observable();
  116. /**
  117. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  118. * For assets with LODs, raised when all of the LODs are complete.
  119. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  120. */
  121. this.onCompleteObservable = new BABYLON.Observable();
  122. /**
  123. * Observable raised when an error occurs.
  124. */
  125. this.onErrorObservable = new BABYLON.Observable();
  126. /**
  127. * Observable raised after the loader is disposed.
  128. */
  129. this.onDisposeObservable = new BABYLON.Observable();
  130. /**
  131. * Observable raised after a loader extension is created.
  132. * Set additional options for a loader extension in this event.
  133. */
  134. this.onExtensionLoadedObservable = new BABYLON.Observable();
  135. /**
  136. * Defines if the loader should validate the asset.
  137. */
  138. this.validate = false;
  139. /**
  140. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  141. */
  142. this.onValidatedObservable = new BABYLON.Observable();
  143. this._loader = null;
  144. /**
  145. * Name of the loader ("gltf")
  146. */
  147. this.name = "gltf";
  148. /**
  149. * Supported file extensions of the loader (.gltf, .glb)
  150. */
  151. this.extensions = {
  152. ".gltf": { isBinary: false },
  153. ".glb": { isBinary: true }
  154. };
  155. this._logIndentLevel = 0;
  156. this._loggingEnabled = false;
  157. /** @hidden */
  158. this._log = this._logDisabled;
  159. this._capturePerformanceCounters = false;
  160. /** @hidden */
  161. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  162. /** @hidden */
  163. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  164. }
  165. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  166. /**
  167. * Raised when the asset has been parsed
  168. */
  169. set: function (callback) {
  170. if (this._onParsedObserver) {
  171. this.onParsedObservable.remove(this._onParsedObserver);
  172. }
  173. this._onParsedObserver = this.onParsedObservable.add(callback);
  174. },
  175. enumerable: true,
  176. configurable: true
  177. });
  178. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  179. /**
  180. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  181. */
  182. set: function (callback) {
  183. if (this._onMeshLoadedObserver) {
  184. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  185. }
  186. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  187. },
  188. enumerable: true,
  189. configurable: true
  190. });
  191. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  192. /**
  193. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  194. */
  195. set: function (callback) {
  196. if (this._onTextureLoadedObserver) {
  197. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  198. }
  199. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  200. },
  201. enumerable: true,
  202. configurable: true
  203. });
  204. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  205. /**
  206. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  207. */
  208. set: function (callback) {
  209. if (this._onMaterialLoadedObserver) {
  210. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  211. }
  212. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  213. },
  214. enumerable: true,
  215. configurable: true
  216. });
  217. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  218. /**
  219. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  220. */
  221. set: function (callback) {
  222. if (this._onCameraLoadedObserver) {
  223. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  224. }
  225. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  226. },
  227. enumerable: true,
  228. configurable: true
  229. });
  230. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  231. /**
  232. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  233. * For assets with LODs, raised when all of the LODs are complete.
  234. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  235. */
  236. set: function (callback) {
  237. if (this._onCompleteObserver) {
  238. this.onCompleteObservable.remove(this._onCompleteObserver);
  239. }
  240. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  241. },
  242. enumerable: true,
  243. configurable: true
  244. });
  245. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  246. /**
  247. * Callback raised when an error occurs.
  248. */
  249. set: function (callback) {
  250. if (this._onErrorObserver) {
  251. this.onErrorObservable.remove(this._onErrorObserver);
  252. }
  253. this._onErrorObserver = this.onErrorObservable.add(callback);
  254. },
  255. enumerable: true,
  256. configurable: true
  257. });
  258. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  259. /**
  260. * Callback raised after the loader is disposed.
  261. */
  262. set: function (callback) {
  263. if (this._onDisposeObserver) {
  264. this.onDisposeObservable.remove(this._onDisposeObserver);
  265. }
  266. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  267. },
  268. enumerable: true,
  269. configurable: true
  270. });
  271. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  272. /**
  273. * Callback raised after a loader extension is created.
  274. */
  275. set: function (callback) {
  276. if (this._onExtensionLoadedObserver) {
  277. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  278. }
  279. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  280. },
  281. enumerable: true,
  282. configurable: true
  283. });
  284. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  285. /**
  286. * Defines if the loader logging is enabled.
  287. */
  288. get: function () {
  289. return this._loggingEnabled;
  290. },
  291. set: function (value) {
  292. if (this._loggingEnabled === value) {
  293. return;
  294. }
  295. this._loggingEnabled = value;
  296. if (this._loggingEnabled) {
  297. this._log = this._logEnabled;
  298. }
  299. else {
  300. this._log = this._logDisabled;
  301. }
  302. },
  303. enumerable: true,
  304. configurable: true
  305. });
  306. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  307. /**
  308. * Defines if the loader should capture performance counters.
  309. */
  310. get: function () {
  311. return this._capturePerformanceCounters;
  312. },
  313. set: function (value) {
  314. if (this._capturePerformanceCounters === value) {
  315. return;
  316. }
  317. this._capturePerformanceCounters = value;
  318. if (this._capturePerformanceCounters) {
  319. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  320. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  321. }
  322. else {
  323. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  324. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  325. }
  326. },
  327. enumerable: true,
  328. configurable: true
  329. });
  330. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  331. /**
  332. * Callback raised after a loader extension is created.
  333. */
  334. set: function (callback) {
  335. if (this._onValidatedObserver) {
  336. this.onValidatedObservable.remove(this._onValidatedObserver);
  337. }
  338. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  339. },
  340. enumerable: true,
  341. configurable: true
  342. });
  343. /**
  344. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  345. */
  346. GLTFFileLoader.prototype.dispose = function () {
  347. if (this._loader) {
  348. this._loader.dispose();
  349. this._loader = null;
  350. }
  351. this._clear();
  352. this.onDisposeObservable.notifyObservers(undefined);
  353. this.onDisposeObservable.clear();
  354. };
  355. /** @hidden */
  356. GLTFFileLoader.prototype._clear = function () {
  357. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  358. this.onMeshLoadedObservable.clear();
  359. this.onTextureLoadedObservable.clear();
  360. this.onMaterialLoadedObservable.clear();
  361. this.onCameraLoadedObservable.clear();
  362. this.onCompleteObservable.clear();
  363. this.onExtensionLoadedObservable.clear();
  364. };
  365. /**
  366. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  367. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  368. * @param scene the scene the meshes should be added to
  369. * @param data the glTF data to load
  370. * @param rootUrl root url to load from
  371. * @param onProgress event that fires when loading progress has occured
  372. * @param fileName Defines the name of the file to load
  373. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  374. */
  375. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  376. var _this = this;
  377. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  378. _this._log("Loading " + (fileName || ""));
  379. _this._loader = _this._getLoader(loaderData);
  380. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  381. });
  382. };
  383. /**
  384. * Imports all objects from the loaded glTF data and adds them to the scene
  385. * @param scene the scene the objects should be added to
  386. * @param data the glTF data to load
  387. * @param rootUrl root url to load from
  388. * @param onProgress event that fires when loading progress has occured
  389. * @param fileName Defines the name of the file to load
  390. * @returns a promise which completes when objects have been loaded to the scene
  391. */
  392. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  393. var _this = this;
  394. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  395. _this._log("Loading " + (fileName || ""));
  396. _this._loader = _this._getLoader(loaderData);
  397. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  398. });
  399. };
  400. /**
  401. * Load into an asset container.
  402. * @param scene The scene to load into
  403. * @param data The data to import
  404. * @param rootUrl The root url for scene and resources
  405. * @param onProgress The callback when the load progresses
  406. * @param fileName Defines the name of the file to load
  407. * @returns The loaded asset container
  408. */
  409. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  410. var _this = this;
  411. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  412. _this._log("Loading " + (fileName || ""));
  413. _this._loader = _this._getLoader(loaderData);
  414. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  415. var container = new BABYLON.AssetContainer(scene);
  416. Array.prototype.push.apply(container.meshes, result.meshes);
  417. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  418. Array.prototype.push.apply(container.skeletons, result.skeletons);
  419. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  420. container.removeAllFromScene();
  421. return container;
  422. });
  423. });
  424. };
  425. /**
  426. * If the data string can be loaded directly.
  427. * @param data string contianing the file data
  428. * @returns if the data can be loaded directly
  429. */
  430. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  431. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  432. };
  433. /**
  434. * Instantiates a glTF file loader plugin.
  435. * @returns the created plugin
  436. */
  437. GLTFFileLoader.prototype.createPlugin = function () {
  438. return new GLTFFileLoader();
  439. };
  440. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  441. /**
  442. * The loader state or null if the loader is not active.
  443. */
  444. get: function () {
  445. return this._loader ? this._loader.state : null;
  446. },
  447. enumerable: true,
  448. configurable: true
  449. });
  450. /**
  451. * Returns a promise that resolves when the asset is completely loaded.
  452. * @returns a promise that resolves when the asset is completely loaded.
  453. */
  454. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  455. var _this = this;
  456. return new Promise(function (resolve, reject) {
  457. _this.onCompleteObservable.addOnce(function () {
  458. resolve();
  459. });
  460. _this.onErrorObservable.addOnce(function (reason) {
  461. reject(reason);
  462. });
  463. });
  464. };
  465. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  466. var _this = this;
  467. return Promise.resolve().then(function () {
  468. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  469. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  470. _this._startPerformanceCounter("Parse JSON");
  471. _this._log("JSON length: " + unpacked.json.length);
  472. var loaderData = {
  473. json: JSON.parse(unpacked.json),
  474. bin: unpacked.bin
  475. };
  476. _this._endPerformanceCounter("Parse JSON");
  477. _this.onParsedObservable.notifyObservers(loaderData);
  478. _this.onParsedObservable.clear();
  479. return loaderData;
  480. });
  481. });
  482. };
  483. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  484. var _this = this;
  485. if (!this.validate || typeof GLTFValidator === "undefined") {
  486. return Promise.resolve();
  487. }
  488. this._startPerformanceCounter("Validate JSON");
  489. var options = {
  490. externalResourceFunction: function (uri) {
  491. return _this.preprocessUrlAsync(rootUrl + uri)
  492. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  493. .then(function (data) { return new Uint8Array(data); });
  494. }
  495. };
  496. if (fileName && fileName.substr(0, 5) !== "data:") {
  497. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  498. }
  499. return GLTFValidator.validateString(json, options).then(function (result) {
  500. _this._endPerformanceCounter("Validate JSON");
  501. _this.onValidatedObservable.notifyObservers(result);
  502. _this.onValidatedObservable.clear();
  503. });
  504. };
  505. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  506. var asset = loaderData.json.asset || {};
  507. this._log("Asset version: " + asset.version);
  508. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  509. asset.generator && this._log("Asset generator: " + asset.generator);
  510. var version = GLTFFileLoader._parseVersion(asset.version);
  511. if (!version) {
  512. throw new Error("Invalid version: " + asset.version);
  513. }
  514. if (asset.minVersion !== undefined) {
  515. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  516. if (!minVersion) {
  517. throw new Error("Invalid minimum version: " + asset.minVersion);
  518. }
  519. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  520. throw new Error("Incompatible minimum version: " + asset.minVersion);
  521. }
  522. }
  523. var createLoaders = {
  524. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  525. 2: GLTFFileLoader._CreateGLTFLoaderV2
  526. };
  527. var createLoader = createLoaders[version.major];
  528. if (!createLoader) {
  529. throw new Error("Unsupported version: " + asset.version);
  530. }
  531. return createLoader(this);
  532. };
  533. GLTFFileLoader.prototype._unpackBinary = function (data) {
  534. this._startPerformanceCounter("Unpack binary");
  535. this._log("Binary length: " + data.byteLength);
  536. var Binary = {
  537. Magic: 0x46546C67
  538. };
  539. var binaryReader = new BinaryReader(data);
  540. var magic = binaryReader.readUint32();
  541. if (magic !== Binary.Magic) {
  542. throw new Error("Unexpected magic: " + magic);
  543. }
  544. var version = binaryReader.readUint32();
  545. if (this.loggingEnabled) {
  546. this._log("Binary version: " + version);
  547. }
  548. var unpacked;
  549. switch (version) {
  550. case 1: {
  551. unpacked = this._unpackBinaryV1(binaryReader);
  552. break;
  553. }
  554. case 2: {
  555. unpacked = this._unpackBinaryV2(binaryReader);
  556. break;
  557. }
  558. default: {
  559. throw new Error("Unsupported version: " + version);
  560. }
  561. }
  562. this._endPerformanceCounter("Unpack binary");
  563. return unpacked;
  564. };
  565. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  566. var ContentFormat = {
  567. JSON: 0
  568. };
  569. var length = binaryReader.readUint32();
  570. if (length != binaryReader.getLength()) {
  571. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  572. }
  573. var contentLength = binaryReader.readUint32();
  574. var contentFormat = binaryReader.readUint32();
  575. var content;
  576. switch (contentFormat) {
  577. case ContentFormat.JSON: {
  578. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  579. break;
  580. }
  581. default: {
  582. throw new Error("Unexpected content format: " + contentFormat);
  583. }
  584. }
  585. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  586. var body = binaryReader.readUint8Array(bytesRemaining);
  587. return {
  588. json: content,
  589. bin: body
  590. };
  591. };
  592. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  593. var ChunkFormat = {
  594. JSON: 0x4E4F534A,
  595. BIN: 0x004E4942
  596. };
  597. var length = binaryReader.readUint32();
  598. if (length !== binaryReader.getLength()) {
  599. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  600. }
  601. // JSON chunk
  602. var chunkLength = binaryReader.readUint32();
  603. var chunkFormat = binaryReader.readUint32();
  604. if (chunkFormat !== ChunkFormat.JSON) {
  605. throw new Error("First chunk format is not JSON");
  606. }
  607. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  608. // Look for BIN chunk
  609. var bin = null;
  610. while (binaryReader.getPosition() < binaryReader.getLength()) {
  611. var chunkLength_1 = binaryReader.readUint32();
  612. var chunkFormat_1 = binaryReader.readUint32();
  613. switch (chunkFormat_1) {
  614. case ChunkFormat.JSON: {
  615. throw new Error("Unexpected JSON chunk");
  616. }
  617. case ChunkFormat.BIN: {
  618. bin = binaryReader.readUint8Array(chunkLength_1);
  619. break;
  620. }
  621. default: {
  622. // ignore unrecognized chunkFormat
  623. binaryReader.skipBytes(chunkLength_1);
  624. break;
  625. }
  626. }
  627. }
  628. return {
  629. json: json,
  630. bin: bin
  631. };
  632. };
  633. GLTFFileLoader._parseVersion = function (version) {
  634. if (version === "1.0" || version === "1.0.1") {
  635. return {
  636. major: 1,
  637. minor: 0
  638. };
  639. }
  640. var match = (version + "").match(/^(\d+)\.(\d+)/);
  641. if (!match) {
  642. return null;
  643. }
  644. return {
  645. major: parseInt(match[1]),
  646. minor: parseInt(match[2])
  647. };
  648. };
  649. GLTFFileLoader._compareVersion = function (a, b) {
  650. if (a.major > b.major) {
  651. return 1;
  652. }
  653. if (a.major < b.major) {
  654. return -1;
  655. }
  656. if (a.minor > b.minor) {
  657. return 1;
  658. }
  659. if (a.minor < b.minor) {
  660. return -1;
  661. }
  662. return 0;
  663. };
  664. GLTFFileLoader._decodeBufferToText = function (buffer) {
  665. var result = "";
  666. var length = buffer.byteLength;
  667. for (var i = 0; i < length; i++) {
  668. result += String.fromCharCode(buffer[i]);
  669. }
  670. return result;
  671. };
  672. /** @hidden */
  673. GLTFFileLoader.prototype._logOpen = function (message) {
  674. this._log(message);
  675. this._logIndentLevel++;
  676. };
  677. /** @hidden */
  678. GLTFFileLoader.prototype._logClose = function () {
  679. --this._logIndentLevel;
  680. };
  681. GLTFFileLoader.prototype._logEnabled = function (message) {
  682. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  683. BABYLON.Tools.Log("" + spaces + message);
  684. };
  685. GLTFFileLoader.prototype._logDisabled = function (message) {
  686. };
  687. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  688. BABYLON.Tools.StartPerformanceCounter(counterName);
  689. };
  690. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  691. };
  692. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  693. BABYLON.Tools.EndPerformanceCounter(counterName);
  694. };
  695. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  696. };
  697. // ----------
  698. // V1 options
  699. // ----------
  700. /**
  701. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  702. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  703. * Defaults to true.
  704. * @hidden
  705. */
  706. GLTFFileLoader.IncrementalLoading = true;
  707. /**
  708. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  709. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  710. * @hidden
  711. */
  712. GLTFFileLoader.HomogeneousCoordinates = false;
  713. GLTFFileLoader._logSpaces = " ";
  714. return GLTFFileLoader;
  715. }());
  716. BABYLON.GLTFFileLoader = GLTFFileLoader;
  717. var BinaryReader = /** @class */ (function () {
  718. function BinaryReader(arrayBuffer) {
  719. this._arrayBuffer = arrayBuffer;
  720. this._dataView = new DataView(arrayBuffer);
  721. this._byteOffset = 0;
  722. }
  723. BinaryReader.prototype.getPosition = function () {
  724. return this._byteOffset;
  725. };
  726. BinaryReader.prototype.getLength = function () {
  727. return this._arrayBuffer.byteLength;
  728. };
  729. BinaryReader.prototype.readUint32 = function () {
  730. var value = this._dataView.getUint32(this._byteOffset, true);
  731. this._byteOffset += 4;
  732. return value;
  733. };
  734. BinaryReader.prototype.readUint8Array = function (length) {
  735. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  736. this._byteOffset += length;
  737. return value;
  738. };
  739. BinaryReader.prototype.skipBytes = function (length) {
  740. this._byteOffset += length;
  741. };
  742. return BinaryReader;
  743. }());
  744. if (BABYLON.SceneLoader) {
  745. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  746. }
  747. })(BABYLON || (BABYLON = {}));
  748. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  749. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  750. var BABYLON;
  751. (function (BABYLON) {
  752. var GLTF1;
  753. (function (GLTF1) {
  754. /**
  755. * Enums
  756. */
  757. var EComponentType;
  758. (function (EComponentType) {
  759. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  760. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  761. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  762. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  763. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  764. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  765. var EShaderType;
  766. (function (EShaderType) {
  767. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  768. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  769. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  770. var EParameterType;
  771. (function (EParameterType) {
  772. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  773. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  774. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  775. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  776. EParameterType[EParameterType["INT"] = 5124] = "INT";
  777. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  778. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  779. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  780. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  781. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  782. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  783. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  784. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  785. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  786. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  787. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  788. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  789. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  790. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  791. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  792. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  793. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  794. var ETextureWrapMode;
  795. (function (ETextureWrapMode) {
  796. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  797. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  798. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  799. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  800. var ETextureFilterType;
  801. (function (ETextureFilterType) {
  802. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  803. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  804. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  805. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  806. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  807. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  808. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  809. var ETextureFormat;
  810. (function (ETextureFormat) {
  811. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  812. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  813. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  814. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  815. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  816. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  817. var ECullingType;
  818. (function (ECullingType) {
  819. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  820. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  821. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  822. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  823. var EBlendingFunction;
  824. (function (EBlendingFunction) {
  825. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  826. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  827. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  828. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  829. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  830. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  831. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  832. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  833. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  834. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  835. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  836. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  837. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  838. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  839. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  840. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  841. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  842. })(BABYLON || (BABYLON = {}));
  843. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  844. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  845. var BABYLON;
  846. (function (BABYLON) {
  847. var GLTF1;
  848. (function (GLTF1) {
  849. /**
  850. * Tokenizer. Used for shaders compatibility
  851. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  852. */
  853. var ETokenType;
  854. (function (ETokenType) {
  855. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  856. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  857. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  858. })(ETokenType || (ETokenType = {}));
  859. var Tokenizer = /** @class */ (function () {
  860. function Tokenizer(toParse) {
  861. this._pos = 0;
  862. this.currentToken = ETokenType.UNKNOWN;
  863. this.currentIdentifier = "";
  864. this.currentString = "";
  865. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  866. this._toParse = toParse;
  867. this._maxPos = toParse.length;
  868. }
  869. Tokenizer.prototype.getNextToken = function () {
  870. if (this.isEnd()) {
  871. return ETokenType.END_OF_INPUT;
  872. }
  873. this.currentString = this.read();
  874. this.currentToken = ETokenType.UNKNOWN;
  875. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  876. this.currentToken = ETokenType.IDENTIFIER;
  877. this.currentIdentifier = this.currentString;
  878. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  879. this.currentIdentifier += this.currentString;
  880. this.forward();
  881. }
  882. }
  883. return this.currentToken;
  884. };
  885. Tokenizer.prototype.peek = function () {
  886. return this._toParse[this._pos];
  887. };
  888. Tokenizer.prototype.read = function () {
  889. return this._toParse[this._pos++];
  890. };
  891. Tokenizer.prototype.forward = function () {
  892. this._pos++;
  893. };
  894. Tokenizer.prototype.isEnd = function () {
  895. return this._pos >= this._maxPos;
  896. };
  897. return Tokenizer;
  898. }());
  899. /**
  900. * Values
  901. */
  902. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  903. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  904. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  905. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  906. /**
  907. * Parse
  908. */
  909. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  910. for (var buf in parsedBuffers) {
  911. var parsedBuffer = parsedBuffers[buf];
  912. gltfRuntime.buffers[buf] = parsedBuffer;
  913. gltfRuntime.buffersCount++;
  914. }
  915. };
  916. var parseShaders = function (parsedShaders, gltfRuntime) {
  917. for (var sha in parsedShaders) {
  918. var parsedShader = parsedShaders[sha];
  919. gltfRuntime.shaders[sha] = parsedShader;
  920. gltfRuntime.shaderscount++;
  921. }
  922. };
  923. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  924. for (var object in parsedObjects) {
  925. var parsedObject = parsedObjects[object];
  926. gltfRuntime[runtimeProperty][object] = parsedObject;
  927. }
  928. };
  929. /**
  930. * Utils
  931. */
  932. var normalizeUVs = function (buffer) {
  933. if (!buffer) {
  934. return;
  935. }
  936. for (var i = 0; i < buffer.length / 2; i++) {
  937. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  938. }
  939. };
  940. var getAttribute = function (attributeParameter) {
  941. if (attributeParameter.semantic === "NORMAL") {
  942. return "normal";
  943. }
  944. else if (attributeParameter.semantic === "POSITION") {
  945. return "position";
  946. }
  947. else if (attributeParameter.semantic === "JOINT") {
  948. return "matricesIndices";
  949. }
  950. else if (attributeParameter.semantic === "WEIGHT") {
  951. return "matricesWeights";
  952. }
  953. else if (attributeParameter.semantic === "COLOR") {
  954. return "color";
  955. }
  956. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  957. var channel = Number(attributeParameter.semantic.split("_")[1]);
  958. return "uv" + (channel === 0 ? "" : channel + 1);
  959. }
  960. return null;
  961. };
  962. /**
  963. * Loads and creates animations
  964. */
  965. var loadAnimations = function (gltfRuntime) {
  966. for (var anim in gltfRuntime.animations) {
  967. var animation = gltfRuntime.animations[anim];
  968. if (!animation.channels || !animation.samplers) {
  969. continue;
  970. }
  971. var lastAnimation = null;
  972. for (var i = 0; i < animation.channels.length; i++) {
  973. // Get parameters and load buffers
  974. var channel = animation.channels[i];
  975. var sampler = animation.samplers[channel.sampler];
  976. if (!sampler) {
  977. continue;
  978. }
  979. var inputData = null;
  980. var outputData = null;
  981. if (animation.parameters) {
  982. inputData = animation.parameters[sampler.input];
  983. outputData = animation.parameters[sampler.output];
  984. }
  985. else {
  986. inputData = sampler.input;
  987. outputData = sampler.output;
  988. }
  989. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  990. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  991. var targetID = channel.target.id;
  992. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  993. if (targetNode === null) {
  994. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  995. }
  996. if (targetNode === null) {
  997. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  998. continue;
  999. }
  1000. var isBone = targetNode instanceof BABYLON.Bone;
  1001. // Get target path (position, rotation or scaling)
  1002. var targetPath = channel.target.path;
  1003. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1004. if (targetPathIndex !== -1) {
  1005. targetPath = babylonAnimationPaths[targetPathIndex];
  1006. }
  1007. // Determine animation type
  1008. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1009. if (!isBone) {
  1010. if (targetPath === "rotationQuaternion") {
  1011. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1012. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1013. }
  1014. else {
  1015. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1016. }
  1017. }
  1018. // Create animation and key frames
  1019. var babylonAnimation = null;
  1020. var keys = [];
  1021. var arrayOffset = 0;
  1022. var modifyKey = false;
  1023. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1024. babylonAnimation = lastAnimation;
  1025. modifyKey = true;
  1026. }
  1027. if (!modifyKey) {
  1028. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1029. }
  1030. // For each frame
  1031. for (var j = 0; j < bufferInput.length; j++) {
  1032. var value = null;
  1033. if (targetPath === "rotationQuaternion") { // VEC4
  1034. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1035. arrayOffset += 4;
  1036. }
  1037. else { // Position and scaling are VEC3
  1038. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1039. arrayOffset += 3;
  1040. }
  1041. if (isBone) {
  1042. var bone = targetNode;
  1043. var translation = BABYLON.Vector3.Zero();
  1044. var rotationQuaternion = new BABYLON.Quaternion();
  1045. var scaling = BABYLON.Vector3.Zero();
  1046. // Warning on decompose
  1047. var mat = bone.getBaseMatrix();
  1048. if (modifyKey && lastAnimation) {
  1049. mat = lastAnimation.getKeys()[j].value;
  1050. }
  1051. mat.decompose(scaling, rotationQuaternion, translation);
  1052. if (targetPath === "position") {
  1053. translation = value;
  1054. }
  1055. else if (targetPath === "rotationQuaternion") {
  1056. rotationQuaternion = value;
  1057. }
  1058. else {
  1059. scaling = value;
  1060. }
  1061. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1062. }
  1063. if (!modifyKey) {
  1064. keys.push({
  1065. frame: bufferInput[j],
  1066. value: value
  1067. });
  1068. }
  1069. else if (lastAnimation) {
  1070. lastAnimation.getKeys()[j].value = value;
  1071. }
  1072. }
  1073. // Finish
  1074. if (!modifyKey && babylonAnimation) {
  1075. babylonAnimation.setKeys(keys);
  1076. targetNode.animations.push(babylonAnimation);
  1077. }
  1078. lastAnimation = babylonAnimation;
  1079. gltfRuntime.scene.stopAnimation(targetNode);
  1080. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1081. }
  1082. }
  1083. };
  1084. /**
  1085. * Returns the bones transformation matrix
  1086. */
  1087. var configureBoneTransformation = function (node) {
  1088. var mat = null;
  1089. if (node.translation || node.rotation || node.scale) {
  1090. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1091. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1092. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1093. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1094. }
  1095. else {
  1096. mat = BABYLON.Matrix.FromArray(node.matrix);
  1097. }
  1098. return mat;
  1099. };
  1100. /**
  1101. * Returns the parent bone
  1102. */
  1103. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1104. // Try to find
  1105. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1106. if (newSkeleton.bones[i].name === jointName) {
  1107. return newSkeleton.bones[i];
  1108. }
  1109. }
  1110. // Not found, search in gltf nodes
  1111. var nodes = gltfRuntime.nodes;
  1112. for (var nde in nodes) {
  1113. var node = nodes[nde];
  1114. if (!node.jointName) {
  1115. continue;
  1116. }
  1117. var children = node.children;
  1118. for (var i = 0; i < children.length; i++) {
  1119. var child = gltfRuntime.nodes[children[i]];
  1120. if (!child.jointName) {
  1121. continue;
  1122. }
  1123. if (child.jointName === jointName) {
  1124. var mat = configureBoneTransformation(node);
  1125. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1126. bone.id = nde;
  1127. return bone;
  1128. }
  1129. }
  1130. }
  1131. return null;
  1132. };
  1133. /**
  1134. * Returns the appropriate root node
  1135. */
  1136. var getNodeToRoot = function (nodesToRoot, id) {
  1137. for (var i = 0; i < nodesToRoot.length; i++) {
  1138. var nodeToRoot = nodesToRoot[i];
  1139. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1140. var child = nodeToRoot.node.children[j];
  1141. if (child === id) {
  1142. return nodeToRoot.bone;
  1143. }
  1144. }
  1145. }
  1146. return null;
  1147. };
  1148. /**
  1149. * Returns the node with the joint name
  1150. */
  1151. var getJointNode = function (gltfRuntime, jointName) {
  1152. var nodes = gltfRuntime.nodes;
  1153. var node = nodes[jointName];
  1154. if (node) {
  1155. return {
  1156. node: node,
  1157. id: jointName
  1158. };
  1159. }
  1160. for (var nde in nodes) {
  1161. node = nodes[nde];
  1162. if (node.jointName === jointName) {
  1163. return {
  1164. node: node,
  1165. id: nde
  1166. };
  1167. }
  1168. }
  1169. return null;
  1170. };
  1171. /**
  1172. * Checks if a nodes is in joints
  1173. */
  1174. var nodeIsInJoints = function (skins, id) {
  1175. for (var i = 0; i < skins.jointNames.length; i++) {
  1176. if (skins.jointNames[i] === id) {
  1177. return true;
  1178. }
  1179. }
  1180. return false;
  1181. };
  1182. /**
  1183. * Fills the nodes to root for bones and builds hierarchy
  1184. */
  1185. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1186. // Creates nodes for root
  1187. for (var nde in gltfRuntime.nodes) {
  1188. var node = gltfRuntime.nodes[nde];
  1189. var id = nde;
  1190. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1191. continue;
  1192. }
  1193. // Create node to root bone
  1194. var mat = configureBoneTransformation(node);
  1195. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  1196. bone.id = id;
  1197. nodesToRoot.push({ bone: bone, node: node, id: id });
  1198. }
  1199. // Parenting
  1200. for (var i = 0; i < nodesToRoot.length; i++) {
  1201. var nodeToRoot = nodesToRoot[i];
  1202. var children = nodeToRoot.node.children;
  1203. for (var j = 0; j < children.length; j++) {
  1204. var child = null;
  1205. for (var k = 0; k < nodesToRoot.length; k++) {
  1206. if (nodesToRoot[k].id === children[j]) {
  1207. child = nodesToRoot[k];
  1208. break;
  1209. }
  1210. }
  1211. if (child) {
  1212. child.bone._parent = nodeToRoot.bone;
  1213. nodeToRoot.bone.children.push(child.bone);
  1214. }
  1215. }
  1216. }
  1217. };
  1218. /**
  1219. * Imports a skeleton
  1220. */
  1221. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1222. if (!newSkeleton) {
  1223. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1224. }
  1225. if (!skins.babylonSkeleton) {
  1226. return newSkeleton;
  1227. }
  1228. // Find the root bones
  1229. var nodesToRoot = [];
  1230. var nodesToRootToAdd = [];
  1231. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1232. newSkeleton.bones = [];
  1233. // Joints
  1234. for (var i = 0; i < skins.jointNames.length; i++) {
  1235. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1236. if (!jointNode) {
  1237. continue;
  1238. }
  1239. var node = jointNode.node;
  1240. if (!node) {
  1241. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1242. continue;
  1243. }
  1244. var id = jointNode.id;
  1245. // Optimize, if the bone already exists...
  1246. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1247. if (existingBone) {
  1248. newSkeleton.bones.push(existingBone);
  1249. continue;
  1250. }
  1251. // Search for parent bone
  1252. var foundBone = false;
  1253. var parentBone = null;
  1254. for (var j = 0; j < i; j++) {
  1255. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1256. if (!jointNode_1) {
  1257. continue;
  1258. }
  1259. var joint = jointNode_1.node;
  1260. if (!joint) {
  1261. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1262. continue;
  1263. }
  1264. var children = joint.children;
  1265. if (!children) {
  1266. continue;
  1267. }
  1268. foundBone = false;
  1269. for (var k = 0; k < children.length; k++) {
  1270. if (children[k] === id) {
  1271. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1272. foundBone = true;
  1273. break;
  1274. }
  1275. }
  1276. if (foundBone) {
  1277. break;
  1278. }
  1279. }
  1280. // Create bone
  1281. var mat = configureBoneTransformation(node);
  1282. if (!parentBone && nodesToRoot.length > 0) {
  1283. parentBone = getNodeToRoot(nodesToRoot, id);
  1284. if (parentBone) {
  1285. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1286. nodesToRootToAdd.push(parentBone);
  1287. }
  1288. }
  1289. }
  1290. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1291. bone.id = id;
  1292. }
  1293. // Polish
  1294. var bones = newSkeleton.bones;
  1295. newSkeleton.bones = [];
  1296. for (var i = 0; i < skins.jointNames.length; i++) {
  1297. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1298. if (!jointNode) {
  1299. continue;
  1300. }
  1301. for (var j = 0; j < bones.length; j++) {
  1302. if (bones[j].id === jointNode.id) {
  1303. newSkeleton.bones.push(bones[j]);
  1304. break;
  1305. }
  1306. }
  1307. }
  1308. newSkeleton.prepare();
  1309. // Finish
  1310. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1311. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1312. }
  1313. return newSkeleton;
  1314. };
  1315. /**
  1316. * Imports a mesh and its geometries
  1317. */
  1318. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1319. if (!newMesh) {
  1320. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1321. newMesh.id = id;
  1322. }
  1323. if (!node.babylonNode) {
  1324. return newMesh;
  1325. }
  1326. var subMaterials = [];
  1327. var vertexData = null;
  1328. var verticesStarts = new Array();
  1329. var verticesCounts = new Array();
  1330. var indexStarts = new Array();
  1331. var indexCounts = new Array();
  1332. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1333. var meshID = meshes[meshIndex];
  1334. var mesh = gltfRuntime.meshes[meshID];
  1335. if (!mesh) {
  1336. continue;
  1337. }
  1338. // Positions, normals and UVs
  1339. for (var i = 0; i < mesh.primitives.length; i++) {
  1340. // Temporary vertex data
  1341. var tempVertexData = new BABYLON.VertexData();
  1342. var primitive = mesh.primitives[i];
  1343. if (primitive.mode !== 4) {
  1344. // continue;
  1345. }
  1346. var attributes = primitive.attributes;
  1347. var accessor = null;
  1348. var buffer = null;
  1349. // Set positions, normal and uvs
  1350. for (var semantic in attributes) {
  1351. // Link accessor and buffer view
  1352. accessor = gltfRuntime.accessors[attributes[semantic]];
  1353. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1354. if (semantic === "NORMAL") {
  1355. tempVertexData.normals = new Float32Array(buffer.length);
  1356. tempVertexData.normals.set(buffer);
  1357. }
  1358. else if (semantic === "POSITION") {
  1359. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1360. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1361. for (var j = 0; j < buffer.length; j += 4) {
  1362. tempVertexData.positions[j] = buffer[j];
  1363. tempVertexData.positions[j + 1] = buffer[j + 1];
  1364. tempVertexData.positions[j + 2] = buffer[j + 2];
  1365. }
  1366. }
  1367. else {
  1368. tempVertexData.positions = new Float32Array(buffer.length);
  1369. tempVertexData.positions.set(buffer);
  1370. }
  1371. verticesCounts.push(tempVertexData.positions.length);
  1372. }
  1373. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1374. var channel = Number(semantic.split("_")[1]);
  1375. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1376. var uvs = new Float32Array(buffer.length);
  1377. uvs.set(buffer);
  1378. normalizeUVs(uvs);
  1379. tempVertexData.set(uvs, uvKind);
  1380. }
  1381. else if (semantic === "JOINT") {
  1382. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1383. tempVertexData.matricesIndices.set(buffer);
  1384. }
  1385. else if (semantic === "WEIGHT") {
  1386. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1387. tempVertexData.matricesWeights.set(buffer);
  1388. }
  1389. else if (semantic === "COLOR") {
  1390. tempVertexData.colors = new Float32Array(buffer.length);
  1391. tempVertexData.colors.set(buffer);
  1392. }
  1393. }
  1394. // Indices
  1395. accessor = gltfRuntime.accessors[primitive.indices];
  1396. if (accessor) {
  1397. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1398. tempVertexData.indices = new Int32Array(buffer.length);
  1399. tempVertexData.indices.set(buffer);
  1400. indexCounts.push(tempVertexData.indices.length);
  1401. }
  1402. else {
  1403. // Set indices on the fly
  1404. var indices = [];
  1405. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1406. indices.push(j);
  1407. }
  1408. tempVertexData.indices = new Int32Array(indices);
  1409. indexCounts.push(tempVertexData.indices.length);
  1410. }
  1411. if (!vertexData) {
  1412. vertexData = tempVertexData;
  1413. }
  1414. else {
  1415. vertexData.merge(tempVertexData);
  1416. }
  1417. // Sub material
  1418. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1419. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1420. // Update vertices start and index start
  1421. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1422. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1423. }
  1424. }
  1425. var material;
  1426. if (subMaterials.length > 1) {
  1427. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1428. material.subMaterials = subMaterials;
  1429. }
  1430. else {
  1431. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1432. }
  1433. if (subMaterials.length === 1) {
  1434. material = subMaterials[0];
  1435. }
  1436. if (!newMesh.material) {
  1437. newMesh.material = material;
  1438. }
  1439. // Apply geometry
  1440. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1441. newMesh.computeWorldMatrix(true);
  1442. // Apply submeshes
  1443. newMesh.subMeshes = [];
  1444. var index = 0;
  1445. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1446. var meshID = meshes[meshIndex];
  1447. var mesh = gltfRuntime.meshes[meshID];
  1448. if (!mesh) {
  1449. continue;
  1450. }
  1451. for (var i = 0; i < mesh.primitives.length; i++) {
  1452. if (mesh.primitives[i].mode !== 4) {
  1453. //continue;
  1454. }
  1455. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1456. index++;
  1457. }
  1458. }
  1459. // Finish
  1460. return newMesh;
  1461. };
  1462. /**
  1463. * Configure node transformation from position, rotation and scaling
  1464. */
  1465. var configureNode = function (newNode, position, rotation, scaling) {
  1466. if (newNode.position) {
  1467. newNode.position = position;
  1468. }
  1469. if (newNode.rotationQuaternion || newNode.rotation) {
  1470. newNode.rotationQuaternion = rotation;
  1471. }
  1472. if (newNode.scaling) {
  1473. newNode.scaling = scaling;
  1474. }
  1475. };
  1476. /**
  1477. * Configures node from transformation matrix
  1478. */
  1479. var configureNodeFromMatrix = function (newNode, node, parent) {
  1480. if (node.matrix) {
  1481. var position = new BABYLON.Vector3(0, 0, 0);
  1482. var rotation = new BABYLON.Quaternion();
  1483. var scaling = new BABYLON.Vector3(0, 0, 0);
  1484. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1485. mat.decompose(scaling, rotation, position);
  1486. configureNode(newNode, position, rotation, scaling);
  1487. }
  1488. else if (node.translation && node.rotation && node.scale) {
  1489. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1490. }
  1491. newNode.computeWorldMatrix(true);
  1492. };
  1493. /**
  1494. * Imports a node
  1495. */
  1496. var importNode = function (gltfRuntime, node, id, parent) {
  1497. var lastNode = null;
  1498. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1499. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1500. return null;
  1501. }
  1502. }
  1503. // Meshes
  1504. if (node.skin) {
  1505. if (node.meshes) {
  1506. var skin = gltfRuntime.skins[node.skin];
  1507. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1508. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1509. if (newMesh.skeleton === null) {
  1510. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1511. if (!skin.babylonSkeleton) {
  1512. skin.babylonSkeleton = newMesh.skeleton;
  1513. }
  1514. }
  1515. lastNode = newMesh;
  1516. }
  1517. }
  1518. else if (node.meshes) {
  1519. /**
  1520. * Improve meshes property
  1521. */
  1522. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1523. lastNode = newMesh;
  1524. }
  1525. // Lights
  1526. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1527. var light = gltfRuntime.lights[node.light];
  1528. if (light) {
  1529. if (light.type === "ambient") {
  1530. var ambienLight = light[light.type];
  1531. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1532. hemiLight.name = node.name || "";
  1533. if (ambienLight.color) {
  1534. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1535. }
  1536. lastNode = hemiLight;
  1537. }
  1538. else if (light.type === "directional") {
  1539. var directionalLight = light[light.type];
  1540. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1541. dirLight.name = node.name || "";
  1542. if (directionalLight.color) {
  1543. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1544. }
  1545. lastNode = dirLight;
  1546. }
  1547. else if (light.type === "point") {
  1548. var pointLight = light[light.type];
  1549. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1550. ptLight.name = node.name || "";
  1551. if (pointLight.color) {
  1552. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1553. }
  1554. lastNode = ptLight;
  1555. }
  1556. else if (light.type === "spot") {
  1557. var spotLight = light[light.type];
  1558. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1559. spLight.name = node.name || "";
  1560. if (spotLight.color) {
  1561. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1562. }
  1563. if (spotLight.fallOfAngle) {
  1564. spLight.angle = spotLight.fallOfAngle;
  1565. }
  1566. if (spotLight.fallOffExponent) {
  1567. spLight.exponent = spotLight.fallOffExponent;
  1568. }
  1569. lastNode = spLight;
  1570. }
  1571. }
  1572. }
  1573. // Cameras
  1574. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1575. var camera = gltfRuntime.cameras[node.camera];
  1576. if (camera) {
  1577. if (camera.type === "orthographic") {
  1578. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  1579. orthoCamera.name = node.name || "";
  1580. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1581. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1582. lastNode = orthoCamera;
  1583. }
  1584. else if (camera.type === "perspective") {
  1585. var perspectiveCamera = camera[camera.type];
  1586. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  1587. persCamera.name = node.name || "";
  1588. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1589. if (!perspectiveCamera.aspectRatio) {
  1590. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1591. }
  1592. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1593. persCamera.maxZ = perspectiveCamera.zfar;
  1594. persCamera.minZ = perspectiveCamera.znear;
  1595. }
  1596. lastNode = persCamera;
  1597. }
  1598. }
  1599. }
  1600. // Empty node
  1601. if (!node.jointName) {
  1602. if (node.babylonNode) {
  1603. return node.babylonNode;
  1604. }
  1605. else if (lastNode === null) {
  1606. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1607. node.babylonNode = dummy;
  1608. lastNode = dummy;
  1609. }
  1610. }
  1611. if (lastNode !== null) {
  1612. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1613. configureNodeFromMatrix(lastNode, node, parent);
  1614. }
  1615. else {
  1616. var translation = node.translation || [0, 0, 0];
  1617. var rotation = node.rotation || [0, 0, 0, 1];
  1618. var scale = node.scale || [1, 1, 1];
  1619. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1620. }
  1621. lastNode.updateCache(true);
  1622. node.babylonNode = lastNode;
  1623. }
  1624. return lastNode;
  1625. };
  1626. /**
  1627. * Traverses nodes and creates them
  1628. */
  1629. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1630. if (meshIncluded === void 0) { meshIncluded = false; }
  1631. var node = gltfRuntime.nodes[id];
  1632. var newNode = null;
  1633. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1634. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1635. meshIncluded = true;
  1636. }
  1637. else {
  1638. meshIncluded = false;
  1639. }
  1640. }
  1641. else {
  1642. meshIncluded = true;
  1643. }
  1644. if (!node.jointName && meshIncluded) {
  1645. newNode = importNode(gltfRuntime, node, id, parent);
  1646. if (newNode !== null) {
  1647. newNode.id = id;
  1648. newNode.parent = parent;
  1649. }
  1650. }
  1651. if (node.children) {
  1652. for (var i = 0; i < node.children.length; i++) {
  1653. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1654. }
  1655. }
  1656. };
  1657. /**
  1658. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1659. */
  1660. var postLoad = function (gltfRuntime) {
  1661. // Nodes
  1662. var currentScene = gltfRuntime.currentScene;
  1663. if (currentScene) {
  1664. for (var i = 0; i < currentScene.nodes.length; i++) {
  1665. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1666. }
  1667. }
  1668. else {
  1669. for (var thing in gltfRuntime.scenes) {
  1670. currentScene = gltfRuntime.scenes[thing];
  1671. for (var i = 0; i < currentScene.nodes.length; i++) {
  1672. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1673. }
  1674. }
  1675. }
  1676. // Set animations
  1677. loadAnimations(gltfRuntime);
  1678. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1679. var skeleton = gltfRuntime.scene.skeletons[i];
  1680. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1681. }
  1682. };
  1683. /**
  1684. * onBind shaderrs callback to set uniforms and matrices
  1685. */
  1686. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1687. var materialValues = material.values || technique.parameters;
  1688. for (var unif in unTreatedUniforms) {
  1689. var uniform = unTreatedUniforms[unif];
  1690. var type = uniform.type;
  1691. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1692. if (uniform.semantic && !uniform.source && !uniform.node) {
  1693. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1694. }
  1695. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1696. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1697. if (source === null) {
  1698. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1699. }
  1700. if (source === null) {
  1701. continue;
  1702. }
  1703. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1704. }
  1705. }
  1706. else {
  1707. var value = materialValues[technique.uniforms[unif]];
  1708. if (!value) {
  1709. continue;
  1710. }
  1711. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1712. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1713. if (texture === null || texture === undefined) {
  1714. continue;
  1715. }
  1716. shaderMaterial.getEffect().setTexture(unif, texture);
  1717. }
  1718. else {
  1719. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1720. }
  1721. }
  1722. }
  1723. onSuccess(shaderMaterial);
  1724. };
  1725. /**
  1726. * Prepare uniforms to send the only one time
  1727. * Loads the appropriate textures
  1728. */
  1729. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1730. var materialValues = material.values || technique.parameters;
  1731. var techniqueUniforms = technique.uniforms;
  1732. /**
  1733. * Prepare values here (not matrices)
  1734. */
  1735. for (var unif in unTreatedUniforms) {
  1736. var uniform = unTreatedUniforms[unif];
  1737. var type = uniform.type;
  1738. var value = materialValues[techniqueUniforms[unif]];
  1739. if (value === undefined) {
  1740. // In case the value is the same for all materials
  1741. value = uniform.value;
  1742. }
  1743. if (!value) {
  1744. continue;
  1745. }
  1746. var onLoadTexture = function (uniformName) {
  1747. return function (texture) {
  1748. if (uniform.value && uniformName) {
  1749. // Static uniform
  1750. shaderMaterial.setTexture(uniformName, texture);
  1751. delete unTreatedUniforms[uniformName];
  1752. }
  1753. };
  1754. };
  1755. // Texture (sampler2D)
  1756. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1757. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1758. }
  1759. // Others
  1760. else {
  1761. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1762. // Static uniform
  1763. delete unTreatedUniforms[unif];
  1764. }
  1765. }
  1766. }
  1767. };
  1768. /**
  1769. * Shader compilation failed
  1770. */
  1771. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1772. return function (effect, error) {
  1773. shaderMaterial.dispose(true);
  1774. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1775. };
  1776. };
  1777. /**
  1778. * Shader compilation success
  1779. */
  1780. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1781. return function (_) {
  1782. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1783. shaderMaterial.onBind = function (mesh) {
  1784. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1785. };
  1786. };
  1787. };
  1788. /**
  1789. * Returns the appropriate uniform if already handled by babylon
  1790. */
  1791. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1792. for (var unif in technique.uniforms) {
  1793. var uniform = technique.uniforms[unif];
  1794. var uniformParameter = technique.parameters[uniform];
  1795. if (tokenizer.currentIdentifier === unif) {
  1796. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1797. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1798. if (transformIndex !== -1) {
  1799. delete unTreatedUniforms[unif];
  1800. return babylonTransforms[transformIndex];
  1801. }
  1802. }
  1803. }
  1804. }
  1805. return tokenizer.currentIdentifier;
  1806. };
  1807. /**
  1808. * All shaders loaded. Create materials one by one
  1809. */
  1810. var importMaterials = function (gltfRuntime) {
  1811. // Create materials
  1812. for (var mat in gltfRuntime.materials) {
  1813. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1814. }
  1815. };
  1816. /**
  1817. * Implementation of the base glTF spec
  1818. */
  1819. var GLTFLoaderBase = /** @class */ (function () {
  1820. function GLTFLoaderBase() {
  1821. }
  1822. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1823. var gltfRuntime = {
  1824. extensions: {},
  1825. accessors: {},
  1826. buffers: {},
  1827. bufferViews: {},
  1828. meshes: {},
  1829. lights: {},
  1830. cameras: {},
  1831. nodes: {},
  1832. images: {},
  1833. textures: {},
  1834. shaders: {},
  1835. programs: {},
  1836. samplers: {},
  1837. techniques: {},
  1838. materials: {},
  1839. animations: {},
  1840. skins: {},
  1841. extensionsUsed: [],
  1842. scenes: {},
  1843. buffersCount: 0,
  1844. shaderscount: 0,
  1845. scene: scene,
  1846. rootUrl: rootUrl,
  1847. loadedBufferCount: 0,
  1848. loadedBufferViews: {},
  1849. loadedShaderCount: 0,
  1850. importOnlyMeshes: false,
  1851. dummyNodes: []
  1852. };
  1853. // Parse
  1854. if (parsedData.extensions) {
  1855. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1856. }
  1857. if (parsedData.extensionsUsed) {
  1858. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1859. }
  1860. if (parsedData.buffers) {
  1861. parseBuffers(parsedData.buffers, gltfRuntime);
  1862. }
  1863. if (parsedData.bufferViews) {
  1864. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1865. }
  1866. if (parsedData.accessors) {
  1867. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1868. }
  1869. if (parsedData.meshes) {
  1870. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1871. }
  1872. if (parsedData.lights) {
  1873. parseObject(parsedData.lights, "lights", gltfRuntime);
  1874. }
  1875. if (parsedData.cameras) {
  1876. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1877. }
  1878. if (parsedData.nodes) {
  1879. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1880. }
  1881. if (parsedData.images) {
  1882. parseObject(parsedData.images, "images", gltfRuntime);
  1883. }
  1884. if (parsedData.textures) {
  1885. parseObject(parsedData.textures, "textures", gltfRuntime);
  1886. }
  1887. if (parsedData.shaders) {
  1888. parseShaders(parsedData.shaders, gltfRuntime);
  1889. }
  1890. if (parsedData.programs) {
  1891. parseObject(parsedData.programs, "programs", gltfRuntime);
  1892. }
  1893. if (parsedData.samplers) {
  1894. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1895. }
  1896. if (parsedData.techniques) {
  1897. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1898. }
  1899. if (parsedData.materials) {
  1900. parseObject(parsedData.materials, "materials", gltfRuntime);
  1901. }
  1902. if (parsedData.animations) {
  1903. parseObject(parsedData.animations, "animations", gltfRuntime);
  1904. }
  1905. if (parsedData.skins) {
  1906. parseObject(parsedData.skins, "skins", gltfRuntime);
  1907. }
  1908. if (parsedData.scenes) {
  1909. gltfRuntime.scenes = parsedData.scenes;
  1910. }
  1911. if (parsedData.scene && parsedData.scenes) {
  1912. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1913. }
  1914. return gltfRuntime;
  1915. };
  1916. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1917. var buffer = gltfRuntime.buffers[id];
  1918. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1919. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1920. }
  1921. else {
  1922. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1923. if (request) {
  1924. onError(request.status + " " + request.statusText);
  1925. }
  1926. });
  1927. }
  1928. };
  1929. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1930. var texture = gltfRuntime.textures[id];
  1931. if (!texture || !texture.source) {
  1932. onError("");
  1933. return;
  1934. }
  1935. if (texture.babylonTexture) {
  1936. onSuccess(null);
  1937. return;
  1938. }
  1939. var source = gltfRuntime.images[texture.source];
  1940. if (BABYLON.Tools.IsBase64(source.uri)) {
  1941. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1942. }
  1943. else {
  1944. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1945. if (request) {
  1946. onError(request.status + " " + request.statusText);
  1947. }
  1948. });
  1949. }
  1950. };
  1951. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1952. var texture = gltfRuntime.textures[id];
  1953. if (texture.babylonTexture) {
  1954. onSuccess(texture.babylonTexture);
  1955. return;
  1956. }
  1957. var sampler = gltfRuntime.samplers[texture.sampler];
  1958. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1959. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1960. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1961. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1962. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1963. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1964. var blobURL = URL.createObjectURL(blob);
  1965. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1966. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1967. if (sampler.wrapS !== undefined) {
  1968. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1969. }
  1970. if (sampler.wrapT !== undefined) {
  1971. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1972. }
  1973. newTexture.name = id;
  1974. texture.babylonTexture = newTexture;
  1975. onSuccess(newTexture);
  1976. };
  1977. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1978. var shader = gltfRuntime.shaders[id];
  1979. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1980. var shaderString = atob(shader.uri.split(",")[1]);
  1981. if (onSuccess) {
  1982. onSuccess(shaderString);
  1983. }
  1984. }
  1985. else {
  1986. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1987. if (request && onError) {
  1988. onError(request.status + " " + request.statusText);
  1989. }
  1990. });
  1991. }
  1992. };
  1993. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1994. var material = gltfRuntime.materials[id];
  1995. if (!material.technique) {
  1996. if (onError) {
  1997. onError("No technique found.");
  1998. }
  1999. return;
  2000. }
  2001. var technique = gltfRuntime.techniques[material.technique];
  2002. if (!technique) {
  2003. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2004. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2005. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2006. onSuccess(defaultMaterial);
  2007. return;
  2008. }
  2009. var program = gltfRuntime.programs[technique.program];
  2010. var states = technique.states;
  2011. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2012. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2013. var newVertexShader = "";
  2014. var newPixelShader = "";
  2015. var vertexTokenizer = new Tokenizer(vertexShader);
  2016. var pixelTokenizer = new Tokenizer(pixelShader);
  2017. var unTreatedUniforms = {};
  2018. var uniforms = [];
  2019. var attributes = [];
  2020. var samplers = [];
  2021. // Fill uniform, sampler2D and attributes
  2022. for (var unif in technique.uniforms) {
  2023. var uniform = technique.uniforms[unif];
  2024. var uniformParameter = technique.parameters[uniform];
  2025. unTreatedUniforms[unif] = uniformParameter;
  2026. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2027. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2028. if (transformIndex !== -1) {
  2029. uniforms.push(babylonTransforms[transformIndex]);
  2030. delete unTreatedUniforms[unif];
  2031. }
  2032. else {
  2033. uniforms.push(unif);
  2034. }
  2035. }
  2036. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2037. samplers.push(unif);
  2038. }
  2039. else {
  2040. uniforms.push(unif);
  2041. }
  2042. }
  2043. for (var attr in technique.attributes) {
  2044. var attribute = technique.attributes[attr];
  2045. var attributeParameter = technique.parameters[attribute];
  2046. if (attributeParameter.semantic) {
  2047. var name_1 = getAttribute(attributeParameter);
  2048. if (name_1) {
  2049. attributes.push(name_1);
  2050. }
  2051. }
  2052. }
  2053. // Configure vertex shader
  2054. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2055. var tokenType = vertexTokenizer.currentToken;
  2056. if (tokenType !== ETokenType.IDENTIFIER) {
  2057. newVertexShader += vertexTokenizer.currentString;
  2058. continue;
  2059. }
  2060. var foundAttribute = false;
  2061. for (var attr in technique.attributes) {
  2062. var attribute = technique.attributes[attr];
  2063. var attributeParameter = technique.parameters[attribute];
  2064. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2065. newVertexShader += getAttribute(attributeParameter);
  2066. foundAttribute = true;
  2067. break;
  2068. }
  2069. }
  2070. if (foundAttribute) {
  2071. continue;
  2072. }
  2073. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2074. }
  2075. // Configure pixel shader
  2076. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2077. var tokenType = pixelTokenizer.currentToken;
  2078. if (tokenType !== ETokenType.IDENTIFIER) {
  2079. newPixelShader += pixelTokenizer.currentString;
  2080. continue;
  2081. }
  2082. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2083. }
  2084. // Create shader material
  2085. var shaderPath = {
  2086. vertex: program.vertexShader + id,
  2087. fragment: program.fragmentShader + id
  2088. };
  2089. var options = {
  2090. attributes: attributes,
  2091. uniforms: uniforms,
  2092. samplers: samplers,
  2093. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2094. };
  2095. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2096. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2097. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2098. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2099. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2100. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2101. if (states && states.functions) {
  2102. var functions = states.functions;
  2103. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2104. shaderMaterial.backFaceCulling = false;
  2105. }
  2106. var blendFunc = functions.blendFuncSeparate;
  2107. if (blendFunc) {
  2108. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2109. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2110. }
  2111. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2112. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2113. }
  2114. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2115. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2116. }
  2117. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2118. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2119. }
  2120. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2121. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2122. }
  2123. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2124. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2125. }
  2126. }
  2127. }
  2128. };
  2129. return GLTFLoaderBase;
  2130. }());
  2131. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2132. /**
  2133. * glTF V1 Loader
  2134. */
  2135. var GLTFLoader = /** @class */ (function () {
  2136. function GLTFLoader() {
  2137. this.state = null;
  2138. }
  2139. GLTFLoader.RegisterExtension = function (extension) {
  2140. if (GLTFLoader.Extensions[extension.name]) {
  2141. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2142. return;
  2143. }
  2144. GLTFLoader.Extensions[extension.name] = extension;
  2145. };
  2146. GLTFLoader.prototype.dispose = function () {
  2147. // do nothing
  2148. };
  2149. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2150. var _this = this;
  2151. scene.useRightHandedSystem = true;
  2152. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2153. gltfRuntime.importOnlyMeshes = true;
  2154. if (meshesNames === "") {
  2155. gltfRuntime.importMeshesNames = [];
  2156. }
  2157. else if (typeof meshesNames === "string") {
  2158. gltfRuntime.importMeshesNames = [meshesNames];
  2159. }
  2160. else if (meshesNames && !(meshesNames instanceof Array)) {
  2161. gltfRuntime.importMeshesNames = [meshesNames];
  2162. }
  2163. else {
  2164. gltfRuntime.importMeshesNames = [];
  2165. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2166. }
  2167. // Create nodes
  2168. _this._createNodes(gltfRuntime);
  2169. var meshes = new Array();
  2170. var skeletons = new Array();
  2171. // Fill arrays of meshes and skeletons
  2172. for (var nde in gltfRuntime.nodes) {
  2173. var node = gltfRuntime.nodes[nde];
  2174. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2175. meshes.push(node.babylonNode);
  2176. }
  2177. }
  2178. for (var skl in gltfRuntime.skins) {
  2179. var skin = gltfRuntime.skins[skl];
  2180. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2181. skeletons.push(skin.babylonSkeleton);
  2182. }
  2183. }
  2184. // Load buffers, shaders, materials, etc.
  2185. _this._loadBuffersAsync(gltfRuntime, function () {
  2186. _this._loadShadersAsync(gltfRuntime, function () {
  2187. importMaterials(gltfRuntime);
  2188. postLoad(gltfRuntime);
  2189. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2190. onSuccess(meshes, skeletons);
  2191. }
  2192. });
  2193. }, onProgress);
  2194. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2195. onSuccess(meshes, skeletons);
  2196. }
  2197. }, onError);
  2198. return true;
  2199. };
  2200. /**
  2201. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2202. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2203. * @param scene the scene the meshes should be added to
  2204. * @param data gltf data containing information of the meshes in a loaded file
  2205. * @param rootUrl root url to load from
  2206. * @param onProgress event that fires when loading progress has occured
  2207. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2208. */
  2209. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2210. var _this = this;
  2211. return new Promise(function (resolve, reject) {
  2212. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  2213. resolve({
  2214. meshes: meshes,
  2215. particleSystems: [],
  2216. skeletons: skeletons,
  2217. animationGroups: []
  2218. });
  2219. }, onProgress, function (message) {
  2220. reject(new Error(message));
  2221. });
  2222. });
  2223. };
  2224. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2225. var _this = this;
  2226. scene.useRightHandedSystem = true;
  2227. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2228. // Load runtime extensios
  2229. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2230. // Create nodes
  2231. _this._createNodes(gltfRuntime);
  2232. // Load buffers, shaders, materials, etc.
  2233. _this._loadBuffersAsync(gltfRuntime, function () {
  2234. _this._loadShadersAsync(gltfRuntime, function () {
  2235. importMaterials(gltfRuntime);
  2236. postLoad(gltfRuntime);
  2237. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2238. onSuccess();
  2239. }
  2240. });
  2241. });
  2242. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2243. onSuccess();
  2244. }
  2245. }, onError);
  2246. }, onError);
  2247. };
  2248. /**
  2249. * Imports all objects from a loaded gltf file and adds them to the scene
  2250. * @param scene the scene the objects should be added to
  2251. * @param data gltf data containing information of the meshes in a loaded file
  2252. * @param rootUrl root url to load from
  2253. * @param onProgress event that fires when loading progress has occured
  2254. * @returns a promise which completes when objects have been loaded to the scene
  2255. */
  2256. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2257. var _this = this;
  2258. return new Promise(function (resolve, reject) {
  2259. _this._loadAsync(scene, data, rootUrl, function () {
  2260. resolve();
  2261. }, onProgress, function (message) {
  2262. reject(new Error(message));
  2263. });
  2264. });
  2265. };
  2266. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2267. var hasShaders = false;
  2268. var processShader = function (sha, shader) {
  2269. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2270. if (shaderString instanceof ArrayBuffer) {
  2271. return;
  2272. }
  2273. gltfRuntime.loadedShaderCount++;
  2274. if (shaderString) {
  2275. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2276. }
  2277. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2278. onload();
  2279. }
  2280. }, function () {
  2281. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2282. });
  2283. };
  2284. for (var sha in gltfRuntime.shaders) {
  2285. hasShaders = true;
  2286. var shader = gltfRuntime.shaders[sha];
  2287. if (shader) {
  2288. processShader.bind(this, sha, shader)();
  2289. }
  2290. else {
  2291. BABYLON.Tools.Error("No shader named: " + sha);
  2292. }
  2293. }
  2294. if (!hasShaders) {
  2295. onload();
  2296. }
  2297. };
  2298. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2299. var hasBuffers = false;
  2300. var processBuffer = function (buf, buffer) {
  2301. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2302. gltfRuntime.loadedBufferCount++;
  2303. if (bufferView) {
  2304. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2305. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2306. }
  2307. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2308. }
  2309. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2310. onLoad();
  2311. }
  2312. }, function () {
  2313. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2314. });
  2315. };
  2316. for (var buf in gltfRuntime.buffers) {
  2317. hasBuffers = true;
  2318. var buffer = gltfRuntime.buffers[buf];
  2319. if (buffer) {
  2320. processBuffer.bind(this, buf, buffer)();
  2321. }
  2322. else {
  2323. BABYLON.Tools.Error("No buffer named: " + buf);
  2324. }
  2325. }
  2326. if (!hasBuffers) {
  2327. onLoad();
  2328. }
  2329. };
  2330. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2331. var currentScene = gltfRuntime.currentScene;
  2332. if (currentScene) {
  2333. // Only one scene even if multiple scenes are defined
  2334. for (var i = 0; i < currentScene.nodes.length; i++) {
  2335. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2336. }
  2337. }
  2338. else {
  2339. // Load all scenes
  2340. for (var thing in gltfRuntime.scenes) {
  2341. currentScene = gltfRuntime.scenes[thing];
  2342. for (var i = 0; i < currentScene.nodes.length; i++) {
  2343. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2344. }
  2345. }
  2346. }
  2347. };
  2348. GLTFLoader.Extensions = {};
  2349. return GLTFLoader;
  2350. }());
  2351. GLTF1.GLTFLoader = GLTFLoader;
  2352. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2353. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2354. })(BABYLON || (BABYLON = {}));
  2355. //# sourceMappingURL=babylon.glTFLoader.js.map
  2356. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2357. var BABYLON;
  2358. (function (BABYLON) {
  2359. var GLTF1;
  2360. (function (GLTF1) {
  2361. /**
  2362. * Utils functions for GLTF
  2363. */
  2364. var GLTFUtils = /** @class */ (function () {
  2365. function GLTFUtils() {
  2366. }
  2367. /**
  2368. * Sets the given "parameter" matrix
  2369. * @param scene: the Scene object
  2370. * @param source: the source node where to pick the matrix
  2371. * @param parameter: the GLTF technique parameter
  2372. * @param uniformName: the name of the shader's uniform
  2373. * @param shaderMaterial: the shader material
  2374. */
  2375. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2376. var mat = null;
  2377. if (parameter.semantic === "MODEL") {
  2378. mat = source.getWorldMatrix();
  2379. }
  2380. else if (parameter.semantic === "PROJECTION") {
  2381. mat = scene.getProjectionMatrix();
  2382. }
  2383. else if (parameter.semantic === "VIEW") {
  2384. mat = scene.getViewMatrix();
  2385. }
  2386. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2387. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2388. }
  2389. else if (parameter.semantic === "MODELVIEW") {
  2390. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2391. }
  2392. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2393. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2394. }
  2395. else if (parameter.semantic === "MODELINVERSE") {
  2396. mat = source.getWorldMatrix().invert();
  2397. }
  2398. else if (parameter.semantic === "VIEWINVERSE") {
  2399. mat = scene.getViewMatrix().invert();
  2400. }
  2401. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2402. mat = scene.getProjectionMatrix().invert();
  2403. }
  2404. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2405. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2406. }
  2407. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2408. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2409. }
  2410. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2411. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2412. }
  2413. else {
  2414. debugger;
  2415. }
  2416. if (mat) {
  2417. switch (parameter.type) {
  2418. case GLTF1.EParameterType.FLOAT_MAT2:
  2419. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2420. break;
  2421. case GLTF1.EParameterType.FLOAT_MAT3:
  2422. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2423. break;
  2424. case GLTF1.EParameterType.FLOAT_MAT4:
  2425. shaderMaterial.setMatrix(uniformName, mat);
  2426. break;
  2427. default: break;
  2428. }
  2429. }
  2430. };
  2431. /**
  2432. * Sets the given "parameter" matrix
  2433. * @param shaderMaterial: the shader material
  2434. * @param uniform: the name of the shader's uniform
  2435. * @param value: the value of the uniform
  2436. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2437. */
  2438. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2439. switch (type) {
  2440. case GLTF1.EParameterType.FLOAT:
  2441. shaderMaterial.setFloat(uniform, value);
  2442. return true;
  2443. case GLTF1.EParameterType.FLOAT_VEC2:
  2444. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2445. return true;
  2446. case GLTF1.EParameterType.FLOAT_VEC3:
  2447. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2448. return true;
  2449. case GLTF1.EParameterType.FLOAT_VEC4:
  2450. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2451. return true;
  2452. default: return false;
  2453. }
  2454. };
  2455. /**
  2456. * Returns the wrap mode of the texture
  2457. * @param mode: the mode value
  2458. */
  2459. GLTFUtils.GetWrapMode = function (mode) {
  2460. switch (mode) {
  2461. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2462. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2463. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2464. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2465. }
  2466. };
  2467. /**
  2468. * Returns the byte stride giving an accessor
  2469. * @param accessor: the GLTF accessor objet
  2470. */
  2471. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2472. // Needs this function since "byteStride" isn't requiered in glTF format
  2473. var type = accessor.type;
  2474. switch (type) {
  2475. case "VEC2": return 2;
  2476. case "VEC3": return 3;
  2477. case "VEC4": return 4;
  2478. case "MAT2": return 4;
  2479. case "MAT3": return 9;
  2480. case "MAT4": return 16;
  2481. default: return 1;
  2482. }
  2483. };
  2484. /**
  2485. * Returns the texture filter mode giving a mode value
  2486. * @param mode: the filter mode value
  2487. */
  2488. GLTFUtils.GetTextureFilterMode = function (mode) {
  2489. switch (mode) {
  2490. case GLTF1.ETextureFilterType.LINEAR:
  2491. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2492. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2493. case GLTF1.ETextureFilterType.NEAREST:
  2494. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2495. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2496. }
  2497. };
  2498. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2499. var byteOffset = bufferView.byteOffset + byteOffset;
  2500. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2501. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2502. throw new Error("Buffer access is out of range");
  2503. }
  2504. var buffer = loadedBufferView.buffer;
  2505. byteOffset += loadedBufferView.byteOffset;
  2506. switch (componentType) {
  2507. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2508. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2509. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2510. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2511. default: return new Float32Array(buffer, byteOffset, byteLength);
  2512. }
  2513. };
  2514. /**
  2515. * Returns a buffer from its accessor
  2516. * @param gltfRuntime: the GLTF runtime
  2517. * @param accessor: the GLTF accessor
  2518. */
  2519. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2520. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2521. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2522. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2523. };
  2524. /**
  2525. * Decodes a buffer view into a string
  2526. * @param view: the buffer view
  2527. */
  2528. GLTFUtils.DecodeBufferToText = function (view) {
  2529. var result = "";
  2530. var length = view.byteLength;
  2531. for (var i = 0; i < length; ++i) {
  2532. result += String.fromCharCode(view[i]);
  2533. }
  2534. return result;
  2535. };
  2536. /**
  2537. * Returns the default material of gltf. Related to
  2538. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2539. * @param scene: the Babylon.js scene
  2540. */
  2541. GLTFUtils.GetDefaultMaterial = function (scene) {
  2542. if (!GLTFUtils._DefaultMaterial) {
  2543. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2544. "precision highp float;",
  2545. "",
  2546. "uniform mat4 worldView;",
  2547. "uniform mat4 projection;",
  2548. "",
  2549. "attribute vec3 position;",
  2550. "",
  2551. "void main(void)",
  2552. "{",
  2553. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2554. "}"
  2555. ].join("\n");
  2556. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2557. "precision highp float;",
  2558. "",
  2559. "uniform vec4 u_emission;",
  2560. "",
  2561. "void main(void)",
  2562. "{",
  2563. " gl_FragColor = u_emission;",
  2564. "}"
  2565. ].join("\n");
  2566. var shaderPath = {
  2567. vertex: "GLTFDefaultMaterial",
  2568. fragment: "GLTFDefaultMaterial"
  2569. };
  2570. var options = {
  2571. attributes: ["position"],
  2572. uniforms: ["worldView", "projection", "u_emission"],
  2573. samplers: new Array(),
  2574. needAlphaBlending: false
  2575. };
  2576. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2577. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2578. }
  2579. return GLTFUtils._DefaultMaterial;
  2580. };
  2581. // The GLTF default material
  2582. GLTFUtils._DefaultMaterial = null;
  2583. return GLTFUtils;
  2584. }());
  2585. GLTF1.GLTFUtils = GLTFUtils;
  2586. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2587. })(BABYLON || (BABYLON = {}));
  2588. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2589. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2590. var BABYLON;
  2591. (function (BABYLON) {
  2592. var GLTF1;
  2593. (function (GLTF1) {
  2594. var GLTFLoaderExtension = /** @class */ (function () {
  2595. function GLTFLoaderExtension(name) {
  2596. this._name = name;
  2597. }
  2598. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2599. get: function () {
  2600. return this._name;
  2601. },
  2602. enumerable: true,
  2603. configurable: true
  2604. });
  2605. /**
  2606. * Defines an override for loading the runtime
  2607. * Return true to stop further extensions from loading the runtime
  2608. */
  2609. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2610. return false;
  2611. };
  2612. /**
  2613. * Defines an onverride for creating gltf runtime
  2614. * Return true to stop further extensions from creating the runtime
  2615. */
  2616. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2617. return false;
  2618. };
  2619. /**
  2620. * Defines an override for loading buffers
  2621. * Return true to stop further extensions from loading this buffer
  2622. */
  2623. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2624. return false;
  2625. };
  2626. /**
  2627. * Defines an override for loading texture buffers
  2628. * Return true to stop further extensions from loading this texture data
  2629. */
  2630. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2631. return false;
  2632. };
  2633. /**
  2634. * Defines an override for creating textures
  2635. * Return true to stop further extensions from loading this texture
  2636. */
  2637. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2638. return false;
  2639. };
  2640. /**
  2641. * Defines an override for loading shader strings
  2642. * Return true to stop further extensions from loading this shader data
  2643. */
  2644. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2645. return false;
  2646. };
  2647. /**
  2648. * Defines an override for loading materials
  2649. * Return true to stop further extensions from loading this material
  2650. */
  2651. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2652. return false;
  2653. };
  2654. // ---------
  2655. // Utilities
  2656. // ---------
  2657. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2658. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2659. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2660. }, function () {
  2661. setTimeout(function () {
  2662. if (!onSuccess) {
  2663. return;
  2664. }
  2665. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2666. });
  2667. });
  2668. };
  2669. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2670. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2671. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2672. }, function () {
  2673. setTimeout(function () {
  2674. onSuccess();
  2675. });
  2676. });
  2677. };
  2678. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2679. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2680. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2681. }, function () {
  2682. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2683. });
  2684. };
  2685. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2686. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2687. if (buffer) {
  2688. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2689. }
  2690. }, onError);
  2691. };
  2692. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2693. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2694. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2695. }, function () {
  2696. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2697. });
  2698. };
  2699. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2700. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2701. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2702. }, function () {
  2703. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2704. });
  2705. };
  2706. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2707. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2708. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2709. }, function () {
  2710. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2711. });
  2712. };
  2713. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2714. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2715. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2716. }, function () {
  2717. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2718. });
  2719. };
  2720. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2721. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2722. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2723. if (func(loaderExtension)) {
  2724. return;
  2725. }
  2726. }
  2727. defaultFunc();
  2728. };
  2729. return GLTFLoaderExtension;
  2730. }());
  2731. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2732. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2733. })(BABYLON || (BABYLON = {}));
  2734. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2735. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2736. var __extends = (this && this.__extends) || (function () {
  2737. var extendStatics = function (d, b) {
  2738. extendStatics = Object.setPrototypeOf ||
  2739. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2740. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2741. return extendStatics(d, b);
  2742. }
  2743. return function (d, b) {
  2744. extendStatics(d, b);
  2745. function __() { this.constructor = d; }
  2746. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2747. };
  2748. })();
  2749. var BABYLON;
  2750. (function (BABYLON) {
  2751. var GLTF1;
  2752. (function (GLTF1) {
  2753. var BinaryExtensionBufferName = "binary_glTF";
  2754. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2755. __extends(GLTFBinaryExtension, _super);
  2756. function GLTFBinaryExtension() {
  2757. return _super.call(this, "KHR_binary_glTF") || this;
  2758. }
  2759. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2760. var extensionsUsed = data.json.extensionsUsed;
  2761. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2762. return false;
  2763. }
  2764. this._bin = data.bin;
  2765. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2766. return true;
  2767. };
  2768. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2769. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2770. return false;
  2771. }
  2772. if (id !== BinaryExtensionBufferName) {
  2773. return false;
  2774. }
  2775. onSuccess(this._bin);
  2776. return true;
  2777. };
  2778. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2779. var texture = gltfRuntime.textures[id];
  2780. var source = gltfRuntime.images[texture.source];
  2781. if (!source.extensions || !(this.name in source.extensions)) {
  2782. return false;
  2783. }
  2784. var sourceExt = source.extensions[this.name];
  2785. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2786. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2787. onSuccess(buffer);
  2788. return true;
  2789. };
  2790. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2791. var shader = gltfRuntime.shaders[id];
  2792. if (!shader.extensions || !(this.name in shader.extensions)) {
  2793. return false;
  2794. }
  2795. var binaryExtensionShader = shader.extensions[this.name];
  2796. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2797. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2798. setTimeout(function () {
  2799. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2800. onSuccess(shaderString);
  2801. });
  2802. return true;
  2803. };
  2804. return GLTFBinaryExtension;
  2805. }(GLTF1.GLTFLoaderExtension));
  2806. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2807. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2808. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2809. })(BABYLON || (BABYLON = {}));
  2810. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2811. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2812. var __extends = (this && this.__extends) || (function () {
  2813. var extendStatics = function (d, b) {
  2814. extendStatics = Object.setPrototypeOf ||
  2815. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2816. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2817. return extendStatics(d, b);
  2818. }
  2819. return function (d, b) {
  2820. extendStatics(d, b);
  2821. function __() { this.constructor = d; }
  2822. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2823. };
  2824. })();
  2825. var BABYLON;
  2826. (function (BABYLON) {
  2827. var GLTF1;
  2828. (function (GLTF1) {
  2829. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2830. __extends(GLTFMaterialsCommonExtension, _super);
  2831. function GLTFMaterialsCommonExtension() {
  2832. return _super.call(this, "KHR_materials_common") || this;
  2833. }
  2834. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2835. if (!gltfRuntime.extensions) {
  2836. return false;
  2837. }
  2838. var extension = gltfRuntime.extensions[this.name];
  2839. if (!extension) {
  2840. return false;
  2841. }
  2842. // Create lights
  2843. var lights = extension.lights;
  2844. if (lights) {
  2845. for (var thing in lights) {
  2846. var light = lights[thing];
  2847. switch (light.type) {
  2848. case "ambient":
  2849. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2850. var ambient = light.ambient;
  2851. if (ambient) {
  2852. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2853. }
  2854. break;
  2855. case "point":
  2856. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2857. var point = light.point;
  2858. if (point) {
  2859. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2860. }
  2861. break;
  2862. case "directional":
  2863. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2864. var directional = light.directional;
  2865. if (directional) {
  2866. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2867. }
  2868. break;
  2869. case "spot":
  2870. var spot = light.spot;
  2871. if (spot) {
  2872. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2873. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2874. }
  2875. break;
  2876. default:
  2877. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2878. break;
  2879. }
  2880. }
  2881. }
  2882. return false;
  2883. };
  2884. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2885. var material = gltfRuntime.materials[id];
  2886. if (!material || !material.extensions) {
  2887. return false;
  2888. }
  2889. var extension = material.extensions[this.name];
  2890. if (!extension) {
  2891. return false;
  2892. }
  2893. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2894. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2895. if (extension.technique === "CONSTANT") {
  2896. standardMaterial.disableLighting = true;
  2897. }
  2898. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2899. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2900. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2901. // Ambient
  2902. if (typeof extension.values.ambient === "string") {
  2903. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2904. }
  2905. else {
  2906. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2907. }
  2908. // Diffuse
  2909. if (typeof extension.values.diffuse === "string") {
  2910. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2911. }
  2912. else {
  2913. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2914. }
  2915. // Emission
  2916. if (typeof extension.values.emission === "string") {
  2917. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2918. }
  2919. else {
  2920. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2921. }
  2922. // Specular
  2923. if (typeof extension.values.specular === "string") {
  2924. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2925. }
  2926. else {
  2927. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2928. }
  2929. return true;
  2930. };
  2931. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2932. // Create buffer from texture url
  2933. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2934. // Create texture from buffer
  2935. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2936. }, onError);
  2937. };
  2938. return GLTFMaterialsCommonExtension;
  2939. }(GLTF1.GLTFLoaderExtension));
  2940. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2941. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2942. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2943. })(BABYLON || (BABYLON = {}));
  2944. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map