babylon.glTF1FileLoader.js 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  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. if (a.major < b.major)
  653. return -1;
  654. if (a.minor > b.minor)
  655. return 1;
  656. if (a.minor < b.minor)
  657. return -1;
  658. return 0;
  659. };
  660. GLTFFileLoader._decodeBufferToText = function (buffer) {
  661. var result = "";
  662. var length = buffer.byteLength;
  663. for (var i = 0; i < length; i++) {
  664. result += String.fromCharCode(buffer[i]);
  665. }
  666. return result;
  667. };
  668. /** @hidden */
  669. GLTFFileLoader.prototype._logOpen = function (message) {
  670. this._log(message);
  671. this._logIndentLevel++;
  672. };
  673. /** @hidden */
  674. GLTFFileLoader.prototype._logClose = function () {
  675. --this._logIndentLevel;
  676. };
  677. GLTFFileLoader.prototype._logEnabled = function (message) {
  678. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  679. BABYLON.Tools.Log("" + spaces + message);
  680. };
  681. GLTFFileLoader.prototype._logDisabled = function (message) {
  682. };
  683. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  684. BABYLON.Tools.StartPerformanceCounter(counterName);
  685. };
  686. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  687. };
  688. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  689. BABYLON.Tools.EndPerformanceCounter(counterName);
  690. };
  691. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  692. };
  693. // ----------
  694. // V1 options
  695. // ----------
  696. /**
  697. * 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.
  698. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  699. * Defaults to true.
  700. * @hidden
  701. */
  702. GLTFFileLoader.IncrementalLoading = true;
  703. /**
  704. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  705. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  706. * @hidden
  707. */
  708. GLTFFileLoader.HomogeneousCoordinates = false;
  709. GLTFFileLoader._logSpaces = " ";
  710. return GLTFFileLoader;
  711. }());
  712. BABYLON.GLTFFileLoader = GLTFFileLoader;
  713. var BinaryReader = /** @class */ (function () {
  714. function BinaryReader(arrayBuffer) {
  715. this._arrayBuffer = arrayBuffer;
  716. this._dataView = new DataView(arrayBuffer);
  717. this._byteOffset = 0;
  718. }
  719. BinaryReader.prototype.getPosition = function () {
  720. return this._byteOffset;
  721. };
  722. BinaryReader.prototype.getLength = function () {
  723. return this._arrayBuffer.byteLength;
  724. };
  725. BinaryReader.prototype.readUint32 = function () {
  726. var value = this._dataView.getUint32(this._byteOffset, true);
  727. this._byteOffset += 4;
  728. return value;
  729. };
  730. BinaryReader.prototype.readUint8Array = function (length) {
  731. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  732. this._byteOffset += length;
  733. return value;
  734. };
  735. BinaryReader.prototype.skipBytes = function (length) {
  736. this._byteOffset += length;
  737. };
  738. return BinaryReader;
  739. }());
  740. if (BABYLON.SceneLoader) {
  741. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  742. }
  743. })(BABYLON || (BABYLON = {}));
  744. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  745. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  746. var BABYLON;
  747. (function (BABYLON) {
  748. var GLTF1;
  749. (function (GLTF1) {
  750. /**
  751. * Enums
  752. */
  753. var EComponentType;
  754. (function (EComponentType) {
  755. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  756. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  757. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  758. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  759. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  760. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  761. var EShaderType;
  762. (function (EShaderType) {
  763. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  764. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  765. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  766. var EParameterType;
  767. (function (EParameterType) {
  768. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  769. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  770. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  771. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  772. EParameterType[EParameterType["INT"] = 5124] = "INT";
  773. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  774. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  775. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  776. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  777. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  778. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  779. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  780. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  781. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  782. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  783. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  784. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  785. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  786. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  787. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  788. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  789. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  790. var ETextureWrapMode;
  791. (function (ETextureWrapMode) {
  792. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  793. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  794. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  795. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  796. var ETextureFilterType;
  797. (function (ETextureFilterType) {
  798. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  799. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  800. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  801. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  802. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  803. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  804. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  805. var ETextureFormat;
  806. (function (ETextureFormat) {
  807. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  808. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  809. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  810. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  811. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  812. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  813. var ECullingType;
  814. (function (ECullingType) {
  815. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  816. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  817. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  818. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  819. var EBlendingFunction;
  820. (function (EBlendingFunction) {
  821. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  822. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  823. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  824. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  825. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  826. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  827. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  828. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  829. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  830. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  831. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  832. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  833. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  834. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  835. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  836. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  837. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  838. })(BABYLON || (BABYLON = {}));
  839. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  840. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  841. var BABYLON;
  842. (function (BABYLON) {
  843. var GLTF1;
  844. (function (GLTF1) {
  845. /**
  846. * Tokenizer. Used for shaders compatibility
  847. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  848. */
  849. var ETokenType;
  850. (function (ETokenType) {
  851. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  852. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  853. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  854. })(ETokenType || (ETokenType = {}));
  855. var Tokenizer = /** @class */ (function () {
  856. function Tokenizer(toParse) {
  857. this._pos = 0;
  858. this.currentToken = ETokenType.UNKNOWN;
  859. this.currentIdentifier = "";
  860. this.currentString = "";
  861. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  862. this._toParse = toParse;
  863. this._maxPos = toParse.length;
  864. }
  865. Tokenizer.prototype.getNextToken = function () {
  866. if (this.isEnd())
  867. return ETokenType.END_OF_INPUT;
  868. this.currentString = this.read();
  869. this.currentToken = ETokenType.UNKNOWN;
  870. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  871. this.currentToken = ETokenType.IDENTIFIER;
  872. this.currentIdentifier = this.currentString;
  873. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  874. this.currentIdentifier += this.currentString;
  875. this.forward();
  876. }
  877. }
  878. return this.currentToken;
  879. };
  880. Tokenizer.prototype.peek = function () {
  881. return this._toParse[this._pos];
  882. };
  883. Tokenizer.prototype.read = function () {
  884. return this._toParse[this._pos++];
  885. };
  886. Tokenizer.prototype.forward = function () {
  887. this._pos++;
  888. };
  889. Tokenizer.prototype.isEnd = function () {
  890. return this._pos >= this._maxPos;
  891. };
  892. return Tokenizer;
  893. }());
  894. /**
  895. * Values
  896. */
  897. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  898. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  899. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  900. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  901. /**
  902. * Parse
  903. */
  904. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  905. for (var buf in parsedBuffers) {
  906. var parsedBuffer = parsedBuffers[buf];
  907. gltfRuntime.buffers[buf] = parsedBuffer;
  908. gltfRuntime.buffersCount++;
  909. }
  910. };
  911. var parseShaders = function (parsedShaders, gltfRuntime) {
  912. for (var sha in parsedShaders) {
  913. var parsedShader = parsedShaders[sha];
  914. gltfRuntime.shaders[sha] = parsedShader;
  915. gltfRuntime.shaderscount++;
  916. }
  917. };
  918. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  919. for (var object in parsedObjects) {
  920. var parsedObject = parsedObjects[object];
  921. gltfRuntime[runtimeProperty][object] = parsedObject;
  922. }
  923. };
  924. /**
  925. * Utils
  926. */
  927. var normalizeUVs = function (buffer) {
  928. if (!buffer) {
  929. return;
  930. }
  931. for (var i = 0; i < buffer.length / 2; i++) {
  932. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  933. }
  934. };
  935. var getAttribute = function (attributeParameter) {
  936. if (attributeParameter.semantic === "NORMAL") {
  937. return "normal";
  938. }
  939. else if (attributeParameter.semantic === "POSITION") {
  940. return "position";
  941. }
  942. else if (attributeParameter.semantic === "JOINT") {
  943. return "matricesIndices";
  944. }
  945. else if (attributeParameter.semantic === "WEIGHT") {
  946. return "matricesWeights";
  947. }
  948. else if (attributeParameter.semantic === "COLOR") {
  949. return "color";
  950. }
  951. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  952. var channel = Number(attributeParameter.semantic.split("_")[1]);
  953. return "uv" + (channel === 0 ? "" : channel + 1);
  954. }
  955. return null;
  956. };
  957. /**
  958. * Loads and creates animations
  959. */
  960. var loadAnimations = function (gltfRuntime) {
  961. for (var anim in gltfRuntime.animations) {
  962. var animation = gltfRuntime.animations[anim];
  963. if (!animation.channels || !animation.samplers) {
  964. continue;
  965. }
  966. var lastAnimation = null;
  967. for (var i = 0; i < animation.channels.length; i++) {
  968. // Get parameters and load buffers
  969. var channel = animation.channels[i];
  970. var sampler = animation.samplers[channel.sampler];
  971. if (!sampler) {
  972. continue;
  973. }
  974. var inputData = null;
  975. var outputData = null;
  976. if (animation.parameters) {
  977. inputData = animation.parameters[sampler.input];
  978. outputData = animation.parameters[sampler.output];
  979. }
  980. else {
  981. inputData = sampler.input;
  982. outputData = sampler.output;
  983. }
  984. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  985. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  986. var targetID = channel.target.id;
  987. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  988. if (targetNode === null) {
  989. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  990. }
  991. if (targetNode === null) {
  992. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  993. continue;
  994. }
  995. var isBone = targetNode instanceof BABYLON.Bone;
  996. // Get target path (position, rotation or scaling)
  997. var targetPath = channel.target.path;
  998. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  999. if (targetPathIndex !== -1) {
  1000. targetPath = babylonAnimationPaths[targetPathIndex];
  1001. }
  1002. // Determine animation type
  1003. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1004. if (!isBone) {
  1005. if (targetPath === "rotationQuaternion") {
  1006. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1007. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1008. }
  1009. else {
  1010. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1011. }
  1012. }
  1013. // Create animation and key frames
  1014. var babylonAnimation = null;
  1015. var keys = [];
  1016. var arrayOffset = 0;
  1017. var modifyKey = false;
  1018. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1019. babylonAnimation = lastAnimation;
  1020. modifyKey = true;
  1021. }
  1022. if (!modifyKey) {
  1023. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1024. }
  1025. // For each frame
  1026. for (var j = 0; j < bufferInput.length; j++) {
  1027. var value = null;
  1028. if (targetPath === "rotationQuaternion") { // VEC4
  1029. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1030. arrayOffset += 4;
  1031. }
  1032. else { // Position and scaling are VEC3
  1033. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1034. arrayOffset += 3;
  1035. }
  1036. if (isBone) {
  1037. var bone = targetNode;
  1038. var translation = BABYLON.Vector3.Zero();
  1039. var rotationQuaternion = new BABYLON.Quaternion();
  1040. var scaling = BABYLON.Vector3.Zero();
  1041. // Warning on decompose
  1042. var mat = bone.getBaseMatrix();
  1043. if (modifyKey && lastAnimation) {
  1044. mat = lastAnimation.getKeys()[j].value;
  1045. }
  1046. mat.decompose(scaling, rotationQuaternion, translation);
  1047. if (targetPath === "position") {
  1048. translation = value;
  1049. }
  1050. else if (targetPath === "rotationQuaternion") {
  1051. rotationQuaternion = value;
  1052. }
  1053. else {
  1054. scaling = value;
  1055. }
  1056. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1057. }
  1058. if (!modifyKey) {
  1059. keys.push({
  1060. frame: bufferInput[j],
  1061. value: value
  1062. });
  1063. }
  1064. else if (lastAnimation) {
  1065. lastAnimation.getKeys()[j].value = value;
  1066. }
  1067. }
  1068. // Finish
  1069. if (!modifyKey && babylonAnimation) {
  1070. babylonAnimation.setKeys(keys);
  1071. targetNode.animations.push(babylonAnimation);
  1072. }
  1073. lastAnimation = babylonAnimation;
  1074. gltfRuntime.scene.stopAnimation(targetNode);
  1075. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1076. }
  1077. }
  1078. };
  1079. /**
  1080. * Returns the bones transformation matrix
  1081. */
  1082. var configureBoneTransformation = function (node) {
  1083. var mat = null;
  1084. if (node.translation || node.rotation || node.scale) {
  1085. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1086. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1087. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1088. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1089. }
  1090. else {
  1091. mat = BABYLON.Matrix.FromArray(node.matrix);
  1092. }
  1093. return mat;
  1094. };
  1095. /**
  1096. * Returns the parent bone
  1097. */
  1098. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1099. // Try to find
  1100. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1101. if (newSkeleton.bones[i].name === jointName) {
  1102. return newSkeleton.bones[i];
  1103. }
  1104. }
  1105. // Not found, search in gltf nodes
  1106. var nodes = gltfRuntime.nodes;
  1107. for (var nde in nodes) {
  1108. var node = nodes[nde];
  1109. if (!node.jointName) {
  1110. continue;
  1111. }
  1112. var children = node.children;
  1113. for (var i = 0; i < children.length; i++) {
  1114. var child = gltfRuntime.nodes[children[i]];
  1115. if (!child.jointName) {
  1116. continue;
  1117. }
  1118. if (child.jointName === jointName) {
  1119. var mat = configureBoneTransformation(node);
  1120. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1121. bone.id = nde;
  1122. return bone;
  1123. }
  1124. }
  1125. }
  1126. return null;
  1127. };
  1128. /**
  1129. * Returns the appropriate root node
  1130. */
  1131. var getNodeToRoot = function (nodesToRoot, id) {
  1132. for (var i = 0; i < nodesToRoot.length; i++) {
  1133. var nodeToRoot = nodesToRoot[i];
  1134. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1135. var child = nodeToRoot.node.children[j];
  1136. if (child === id) {
  1137. return nodeToRoot.bone;
  1138. }
  1139. }
  1140. }
  1141. return null;
  1142. };
  1143. /**
  1144. * Returns the node with the joint name
  1145. */
  1146. var getJointNode = function (gltfRuntime, jointName) {
  1147. var nodes = gltfRuntime.nodes;
  1148. var node = nodes[jointName];
  1149. if (node) {
  1150. return {
  1151. node: node,
  1152. id: jointName
  1153. };
  1154. }
  1155. for (var nde in nodes) {
  1156. node = nodes[nde];
  1157. if (node.jointName === jointName) {
  1158. return {
  1159. node: node,
  1160. id: nde
  1161. };
  1162. }
  1163. }
  1164. return null;
  1165. };
  1166. /**
  1167. * Checks if a nodes is in joints
  1168. */
  1169. var nodeIsInJoints = function (skins, id) {
  1170. for (var i = 0; i < skins.jointNames.length; i++) {
  1171. if (skins.jointNames[i] === id) {
  1172. return true;
  1173. }
  1174. }
  1175. return false;
  1176. };
  1177. /**
  1178. * Fills the nodes to root for bones and builds hierarchy
  1179. */
  1180. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1181. // Creates nodes for root
  1182. for (var nde in gltfRuntime.nodes) {
  1183. var node = gltfRuntime.nodes[nde];
  1184. var id = nde;
  1185. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1186. continue;
  1187. }
  1188. // Create node to root bone
  1189. var mat = configureBoneTransformation(node);
  1190. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  1191. bone.id = id;
  1192. nodesToRoot.push({ bone: bone, node: node, id: id });
  1193. }
  1194. // Parenting
  1195. for (var i = 0; i < nodesToRoot.length; i++) {
  1196. var nodeToRoot = nodesToRoot[i];
  1197. var children = nodeToRoot.node.children;
  1198. for (var j = 0; j < children.length; j++) {
  1199. var child = null;
  1200. for (var k = 0; k < nodesToRoot.length; k++) {
  1201. if (nodesToRoot[k].id === children[j]) {
  1202. child = nodesToRoot[k];
  1203. break;
  1204. }
  1205. }
  1206. if (child) {
  1207. child.bone._parent = nodeToRoot.bone;
  1208. nodeToRoot.bone.children.push(child.bone);
  1209. }
  1210. }
  1211. }
  1212. };
  1213. /**
  1214. * Imports a skeleton
  1215. */
  1216. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1217. if (!newSkeleton) {
  1218. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1219. }
  1220. if (!skins.babylonSkeleton) {
  1221. return newSkeleton;
  1222. }
  1223. // Find the root bones
  1224. var nodesToRoot = [];
  1225. var nodesToRootToAdd = [];
  1226. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1227. newSkeleton.bones = [];
  1228. // Joints
  1229. for (var i = 0; i < skins.jointNames.length; i++) {
  1230. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1231. if (!jointNode) {
  1232. continue;
  1233. }
  1234. var node = jointNode.node;
  1235. if (!node) {
  1236. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1237. continue;
  1238. }
  1239. var id = jointNode.id;
  1240. // Optimize, if the bone already exists...
  1241. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1242. if (existingBone) {
  1243. newSkeleton.bones.push(existingBone);
  1244. continue;
  1245. }
  1246. // Search for parent bone
  1247. var foundBone = false;
  1248. var parentBone = null;
  1249. for (var j = 0; j < i; j++) {
  1250. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1251. if (!jointNode_1) {
  1252. continue;
  1253. }
  1254. var joint = jointNode_1.node;
  1255. if (!joint) {
  1256. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1257. continue;
  1258. }
  1259. var children = joint.children;
  1260. if (!children) {
  1261. continue;
  1262. }
  1263. foundBone = false;
  1264. for (var k = 0; k < children.length; k++) {
  1265. if (children[k] === id) {
  1266. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1267. foundBone = true;
  1268. break;
  1269. }
  1270. }
  1271. if (foundBone) {
  1272. break;
  1273. }
  1274. }
  1275. // Create bone
  1276. var mat = configureBoneTransformation(node);
  1277. if (!parentBone && nodesToRoot.length > 0) {
  1278. parentBone = getNodeToRoot(nodesToRoot, id);
  1279. if (parentBone) {
  1280. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1281. nodesToRootToAdd.push(parentBone);
  1282. }
  1283. }
  1284. }
  1285. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1286. bone.id = id;
  1287. }
  1288. // Polish
  1289. var bones = newSkeleton.bones;
  1290. newSkeleton.bones = [];
  1291. for (var i = 0; i < skins.jointNames.length; i++) {
  1292. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1293. if (!jointNode) {
  1294. continue;
  1295. }
  1296. for (var j = 0; j < bones.length; j++) {
  1297. if (bones[j].id === jointNode.id) {
  1298. newSkeleton.bones.push(bones[j]);
  1299. break;
  1300. }
  1301. }
  1302. }
  1303. newSkeleton.prepare();
  1304. // Finish
  1305. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1306. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1307. }
  1308. return newSkeleton;
  1309. };
  1310. /**
  1311. * Imports a mesh and its geometries
  1312. */
  1313. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1314. if (!newMesh) {
  1315. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1316. newMesh.id = id;
  1317. }
  1318. if (!node.babylonNode) {
  1319. return newMesh;
  1320. }
  1321. var subMaterials = [];
  1322. var vertexData = null;
  1323. var verticesStarts = new Array();
  1324. var verticesCounts = new Array();
  1325. var indexStarts = new Array();
  1326. var indexCounts = new Array();
  1327. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1328. var meshID = meshes[meshIndex];
  1329. var mesh = gltfRuntime.meshes[meshID];
  1330. if (!mesh) {
  1331. continue;
  1332. }
  1333. // Positions, normals and UVs
  1334. for (var i = 0; i < mesh.primitives.length; i++) {
  1335. // Temporary vertex data
  1336. var tempVertexData = new BABYLON.VertexData();
  1337. var primitive = mesh.primitives[i];
  1338. if (primitive.mode !== 4) {
  1339. // continue;
  1340. }
  1341. var attributes = primitive.attributes;
  1342. var accessor = null;
  1343. var buffer = null;
  1344. // Set positions, normal and uvs
  1345. for (var semantic in attributes) {
  1346. // Link accessor and buffer view
  1347. accessor = gltfRuntime.accessors[attributes[semantic]];
  1348. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1349. if (semantic === "NORMAL") {
  1350. tempVertexData.normals = new Float32Array(buffer.length);
  1351. tempVertexData.normals.set(buffer);
  1352. }
  1353. else if (semantic === "POSITION") {
  1354. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1355. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1356. for (var j = 0; j < buffer.length; j += 4) {
  1357. tempVertexData.positions[j] = buffer[j];
  1358. tempVertexData.positions[j + 1] = buffer[j + 1];
  1359. tempVertexData.positions[j + 2] = buffer[j + 2];
  1360. }
  1361. }
  1362. else {
  1363. tempVertexData.positions = new Float32Array(buffer.length);
  1364. tempVertexData.positions.set(buffer);
  1365. }
  1366. verticesCounts.push(tempVertexData.positions.length);
  1367. }
  1368. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1369. var channel = Number(semantic.split("_")[1]);
  1370. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1371. var uvs = new Float32Array(buffer.length);
  1372. uvs.set(buffer);
  1373. normalizeUVs(uvs);
  1374. tempVertexData.set(uvs, uvKind);
  1375. }
  1376. else if (semantic === "JOINT") {
  1377. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1378. tempVertexData.matricesIndices.set(buffer);
  1379. }
  1380. else if (semantic === "WEIGHT") {
  1381. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1382. tempVertexData.matricesWeights.set(buffer);
  1383. }
  1384. else if (semantic === "COLOR") {
  1385. tempVertexData.colors = new Float32Array(buffer.length);
  1386. tempVertexData.colors.set(buffer);
  1387. }
  1388. }
  1389. // Indices
  1390. accessor = gltfRuntime.accessors[primitive.indices];
  1391. if (accessor) {
  1392. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1393. tempVertexData.indices = new Int32Array(buffer.length);
  1394. tempVertexData.indices.set(buffer);
  1395. indexCounts.push(tempVertexData.indices.length);
  1396. }
  1397. else {
  1398. // Set indices on the fly
  1399. var indices = [];
  1400. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1401. indices.push(j);
  1402. }
  1403. tempVertexData.indices = new Int32Array(indices);
  1404. indexCounts.push(tempVertexData.indices.length);
  1405. }
  1406. if (!vertexData) {
  1407. vertexData = tempVertexData;
  1408. }
  1409. else {
  1410. vertexData.merge(tempVertexData);
  1411. }
  1412. // Sub material
  1413. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1414. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1415. // Update vertices start and index start
  1416. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1417. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1418. }
  1419. }
  1420. var material;
  1421. if (subMaterials.length > 1) {
  1422. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1423. material.subMaterials = subMaterials;
  1424. }
  1425. else {
  1426. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1427. }
  1428. if (subMaterials.length === 1) {
  1429. material = subMaterials[0];
  1430. }
  1431. if (!newMesh.material) {
  1432. newMesh.material = material;
  1433. }
  1434. // Apply geometry
  1435. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1436. newMesh.computeWorldMatrix(true);
  1437. // Apply submeshes
  1438. newMesh.subMeshes = [];
  1439. var index = 0;
  1440. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1441. var meshID = meshes[meshIndex];
  1442. var mesh = gltfRuntime.meshes[meshID];
  1443. if (!mesh) {
  1444. continue;
  1445. }
  1446. for (var i = 0; i < mesh.primitives.length; i++) {
  1447. if (mesh.primitives[i].mode !== 4) {
  1448. //continue;
  1449. }
  1450. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1451. index++;
  1452. }
  1453. }
  1454. // Finish
  1455. return newMesh;
  1456. };
  1457. /**
  1458. * Configure node transformation from position, rotation and scaling
  1459. */
  1460. var configureNode = function (newNode, position, rotation, scaling) {
  1461. if (newNode.position) {
  1462. newNode.position = position;
  1463. }
  1464. if (newNode.rotationQuaternion || newNode.rotation) {
  1465. newNode.rotationQuaternion = rotation;
  1466. }
  1467. if (newNode.scaling) {
  1468. newNode.scaling = scaling;
  1469. }
  1470. };
  1471. /**
  1472. * Configures node from transformation matrix
  1473. */
  1474. var configureNodeFromMatrix = function (newNode, node, parent) {
  1475. if (node.matrix) {
  1476. var position = new BABYLON.Vector3(0, 0, 0);
  1477. var rotation = new BABYLON.Quaternion();
  1478. var scaling = new BABYLON.Vector3(0, 0, 0);
  1479. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1480. mat.decompose(scaling, rotation, position);
  1481. configureNode(newNode, position, rotation, scaling);
  1482. }
  1483. else if (node.translation && node.rotation && node.scale) {
  1484. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1485. }
  1486. newNode.computeWorldMatrix(true);
  1487. };
  1488. /**
  1489. * Imports a node
  1490. */
  1491. var importNode = function (gltfRuntime, node, id, parent) {
  1492. var lastNode = null;
  1493. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1494. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1495. return null;
  1496. }
  1497. }
  1498. // Meshes
  1499. if (node.skin) {
  1500. if (node.meshes) {
  1501. var skin = gltfRuntime.skins[node.skin];
  1502. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1503. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1504. if (newMesh.skeleton === null) {
  1505. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1506. if (!skin.babylonSkeleton) {
  1507. skin.babylonSkeleton = newMesh.skeleton;
  1508. }
  1509. }
  1510. lastNode = newMesh;
  1511. }
  1512. }
  1513. else if (node.meshes) {
  1514. /**
  1515. * Improve meshes property
  1516. */
  1517. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1518. lastNode = newMesh;
  1519. }
  1520. // Lights
  1521. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1522. var light = gltfRuntime.lights[node.light];
  1523. if (light) {
  1524. if (light.type === "ambient") {
  1525. var ambienLight = light[light.type];
  1526. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1527. hemiLight.name = node.name || "";
  1528. if (ambienLight.color) {
  1529. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1530. }
  1531. lastNode = hemiLight;
  1532. }
  1533. else if (light.type === "directional") {
  1534. var directionalLight = light[light.type];
  1535. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1536. dirLight.name = node.name || "";
  1537. if (directionalLight.color) {
  1538. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1539. }
  1540. lastNode = dirLight;
  1541. }
  1542. else if (light.type === "point") {
  1543. var pointLight = light[light.type];
  1544. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1545. ptLight.name = node.name || "";
  1546. if (pointLight.color) {
  1547. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1548. }
  1549. lastNode = ptLight;
  1550. }
  1551. else if (light.type === "spot") {
  1552. var spotLight = light[light.type];
  1553. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1554. spLight.name = node.name || "";
  1555. if (spotLight.color) {
  1556. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1557. }
  1558. if (spotLight.fallOfAngle) {
  1559. spLight.angle = spotLight.fallOfAngle;
  1560. }
  1561. if (spotLight.fallOffExponent) {
  1562. spLight.exponent = spotLight.fallOffExponent;
  1563. }
  1564. lastNode = spLight;
  1565. }
  1566. }
  1567. }
  1568. // Cameras
  1569. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1570. var camera = gltfRuntime.cameras[node.camera];
  1571. if (camera) {
  1572. if (camera.type === "orthographic") {
  1573. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  1574. orthoCamera.name = node.name || "";
  1575. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1576. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1577. lastNode = orthoCamera;
  1578. }
  1579. else if (camera.type === "perspective") {
  1580. var perspectiveCamera = camera[camera.type];
  1581. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  1582. persCamera.name = node.name || "";
  1583. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1584. if (!perspectiveCamera.aspectRatio) {
  1585. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1586. }
  1587. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1588. persCamera.maxZ = perspectiveCamera.zfar;
  1589. persCamera.minZ = perspectiveCamera.znear;
  1590. }
  1591. lastNode = persCamera;
  1592. }
  1593. }
  1594. }
  1595. // Empty node
  1596. if (!node.jointName) {
  1597. if (node.babylonNode) {
  1598. return node.babylonNode;
  1599. }
  1600. else if (lastNode === null) {
  1601. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1602. node.babylonNode = dummy;
  1603. lastNode = dummy;
  1604. }
  1605. }
  1606. if (lastNode !== null) {
  1607. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1608. configureNodeFromMatrix(lastNode, node, parent);
  1609. }
  1610. else {
  1611. var translation = node.translation || [0, 0, 0];
  1612. var rotation = node.rotation || [0, 0, 0, 1];
  1613. var scale = node.scale || [1, 1, 1];
  1614. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1615. }
  1616. lastNode.updateCache(true);
  1617. node.babylonNode = lastNode;
  1618. }
  1619. return lastNode;
  1620. };
  1621. /**
  1622. * Traverses nodes and creates them
  1623. */
  1624. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1625. if (meshIncluded === void 0) { meshIncluded = false; }
  1626. var node = gltfRuntime.nodes[id];
  1627. var newNode = null;
  1628. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1629. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1630. meshIncluded = true;
  1631. }
  1632. else {
  1633. meshIncluded = false;
  1634. }
  1635. }
  1636. else {
  1637. meshIncluded = true;
  1638. }
  1639. if (!node.jointName && meshIncluded) {
  1640. newNode = importNode(gltfRuntime, node, id, parent);
  1641. if (newNode !== null) {
  1642. newNode.id = id;
  1643. newNode.parent = parent;
  1644. }
  1645. }
  1646. if (node.children) {
  1647. for (var i = 0; i < node.children.length; i++) {
  1648. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1649. }
  1650. }
  1651. };
  1652. /**
  1653. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1654. */
  1655. var postLoad = function (gltfRuntime) {
  1656. // Nodes
  1657. var currentScene = gltfRuntime.currentScene;
  1658. if (currentScene) {
  1659. for (var i = 0; i < currentScene.nodes.length; i++) {
  1660. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1661. }
  1662. }
  1663. else {
  1664. for (var thing in gltfRuntime.scenes) {
  1665. currentScene = gltfRuntime.scenes[thing];
  1666. for (var i = 0; i < currentScene.nodes.length; i++) {
  1667. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1668. }
  1669. }
  1670. }
  1671. // Set animations
  1672. loadAnimations(gltfRuntime);
  1673. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1674. var skeleton = gltfRuntime.scene.skeletons[i];
  1675. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1676. }
  1677. };
  1678. /**
  1679. * onBind shaderrs callback to set uniforms and matrices
  1680. */
  1681. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1682. var materialValues = material.values || technique.parameters;
  1683. for (var unif in unTreatedUniforms) {
  1684. var uniform = unTreatedUniforms[unif];
  1685. var type = uniform.type;
  1686. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1687. if (uniform.semantic && !uniform.source && !uniform.node) {
  1688. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1689. }
  1690. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1691. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1692. if (source === null) {
  1693. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1694. }
  1695. if (source === null) {
  1696. continue;
  1697. }
  1698. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1699. }
  1700. }
  1701. else {
  1702. var value = materialValues[technique.uniforms[unif]];
  1703. if (!value) {
  1704. continue;
  1705. }
  1706. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1707. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1708. if (texture === null || texture === undefined) {
  1709. continue;
  1710. }
  1711. shaderMaterial.getEffect().setTexture(unif, texture);
  1712. }
  1713. else {
  1714. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1715. }
  1716. }
  1717. }
  1718. onSuccess(shaderMaterial);
  1719. };
  1720. /**
  1721. * Prepare uniforms to send the only one time
  1722. * Loads the appropriate textures
  1723. */
  1724. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1725. var materialValues = material.values || technique.parameters;
  1726. var techniqueUniforms = technique.uniforms;
  1727. /**
  1728. * Prepare values here (not matrices)
  1729. */
  1730. for (var unif in unTreatedUniforms) {
  1731. var uniform = unTreatedUniforms[unif];
  1732. var type = uniform.type;
  1733. var value = materialValues[techniqueUniforms[unif]];
  1734. if (value === undefined) {
  1735. // In case the value is the same for all materials
  1736. value = uniform.value;
  1737. }
  1738. if (!value) {
  1739. continue;
  1740. }
  1741. var onLoadTexture = function (uniformName) {
  1742. return function (texture) {
  1743. if (uniform.value && uniformName) {
  1744. // Static uniform
  1745. shaderMaterial.setTexture(uniformName, texture);
  1746. delete unTreatedUniforms[uniformName];
  1747. }
  1748. };
  1749. };
  1750. // Texture (sampler2D)
  1751. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1752. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1753. }
  1754. // Others
  1755. else {
  1756. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1757. // Static uniform
  1758. delete unTreatedUniforms[unif];
  1759. }
  1760. }
  1761. }
  1762. };
  1763. /**
  1764. * Shader compilation failed
  1765. */
  1766. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1767. return function (effect, error) {
  1768. shaderMaterial.dispose(true);
  1769. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1770. };
  1771. };
  1772. /**
  1773. * Shader compilation success
  1774. */
  1775. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1776. return function (_) {
  1777. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1778. shaderMaterial.onBind = function (mesh) {
  1779. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1780. };
  1781. };
  1782. };
  1783. /**
  1784. * Returns the appropriate uniform if already handled by babylon
  1785. */
  1786. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1787. for (var unif in technique.uniforms) {
  1788. var uniform = technique.uniforms[unif];
  1789. var uniformParameter = technique.parameters[uniform];
  1790. if (tokenizer.currentIdentifier === unif) {
  1791. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1792. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1793. if (transformIndex !== -1) {
  1794. delete unTreatedUniforms[unif];
  1795. return babylonTransforms[transformIndex];
  1796. }
  1797. }
  1798. }
  1799. }
  1800. return tokenizer.currentIdentifier;
  1801. };
  1802. /**
  1803. * All shaders loaded. Create materials one by one
  1804. */
  1805. var importMaterials = function (gltfRuntime) {
  1806. // Create materials
  1807. for (var mat in gltfRuntime.materials) {
  1808. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1809. }
  1810. };
  1811. /**
  1812. * Implementation of the base glTF spec
  1813. */
  1814. var GLTFLoaderBase = /** @class */ (function () {
  1815. function GLTFLoaderBase() {
  1816. }
  1817. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1818. var gltfRuntime = {
  1819. extensions: {},
  1820. accessors: {},
  1821. buffers: {},
  1822. bufferViews: {},
  1823. meshes: {},
  1824. lights: {},
  1825. cameras: {},
  1826. nodes: {},
  1827. images: {},
  1828. textures: {},
  1829. shaders: {},
  1830. programs: {},
  1831. samplers: {},
  1832. techniques: {},
  1833. materials: {},
  1834. animations: {},
  1835. skins: {},
  1836. extensionsUsed: [],
  1837. scenes: {},
  1838. buffersCount: 0,
  1839. shaderscount: 0,
  1840. scene: scene,
  1841. rootUrl: rootUrl,
  1842. loadedBufferCount: 0,
  1843. loadedBufferViews: {},
  1844. loadedShaderCount: 0,
  1845. importOnlyMeshes: false,
  1846. dummyNodes: []
  1847. };
  1848. // Parse
  1849. if (parsedData.extensions) {
  1850. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1851. }
  1852. if (parsedData.extensionsUsed) {
  1853. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1854. }
  1855. if (parsedData.buffers) {
  1856. parseBuffers(parsedData.buffers, gltfRuntime);
  1857. }
  1858. if (parsedData.bufferViews) {
  1859. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1860. }
  1861. if (parsedData.accessors) {
  1862. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1863. }
  1864. if (parsedData.meshes) {
  1865. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1866. }
  1867. if (parsedData.lights) {
  1868. parseObject(parsedData.lights, "lights", gltfRuntime);
  1869. }
  1870. if (parsedData.cameras) {
  1871. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1872. }
  1873. if (parsedData.nodes) {
  1874. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1875. }
  1876. if (parsedData.images) {
  1877. parseObject(parsedData.images, "images", gltfRuntime);
  1878. }
  1879. if (parsedData.textures) {
  1880. parseObject(parsedData.textures, "textures", gltfRuntime);
  1881. }
  1882. if (parsedData.shaders) {
  1883. parseShaders(parsedData.shaders, gltfRuntime);
  1884. }
  1885. if (parsedData.programs) {
  1886. parseObject(parsedData.programs, "programs", gltfRuntime);
  1887. }
  1888. if (parsedData.samplers) {
  1889. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1890. }
  1891. if (parsedData.techniques) {
  1892. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1893. }
  1894. if (parsedData.materials) {
  1895. parseObject(parsedData.materials, "materials", gltfRuntime);
  1896. }
  1897. if (parsedData.animations) {
  1898. parseObject(parsedData.animations, "animations", gltfRuntime);
  1899. }
  1900. if (parsedData.skins) {
  1901. parseObject(parsedData.skins, "skins", gltfRuntime);
  1902. }
  1903. if (parsedData.scenes) {
  1904. gltfRuntime.scenes = parsedData.scenes;
  1905. }
  1906. if (parsedData.scene && parsedData.scenes) {
  1907. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1908. }
  1909. return gltfRuntime;
  1910. };
  1911. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1912. var buffer = gltfRuntime.buffers[id];
  1913. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1914. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1915. }
  1916. else {
  1917. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1918. if (request) {
  1919. onError(request.status + " " + request.statusText);
  1920. }
  1921. });
  1922. }
  1923. };
  1924. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1925. var texture = gltfRuntime.textures[id];
  1926. if (!texture || !texture.source) {
  1927. onError("");
  1928. return;
  1929. }
  1930. if (texture.babylonTexture) {
  1931. onSuccess(null);
  1932. return;
  1933. }
  1934. var source = gltfRuntime.images[texture.source];
  1935. if (BABYLON.Tools.IsBase64(source.uri)) {
  1936. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1937. }
  1938. else {
  1939. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1940. if (request) {
  1941. onError(request.status + " " + request.statusText);
  1942. }
  1943. });
  1944. }
  1945. };
  1946. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1947. var texture = gltfRuntime.textures[id];
  1948. if (texture.babylonTexture) {
  1949. onSuccess(texture.babylonTexture);
  1950. return;
  1951. }
  1952. var sampler = gltfRuntime.samplers[texture.sampler];
  1953. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1954. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1955. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1956. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1957. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1958. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1959. var blobURL = URL.createObjectURL(blob);
  1960. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1961. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1962. if (sampler.wrapS !== undefined) {
  1963. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1964. }
  1965. if (sampler.wrapT !== undefined) {
  1966. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1967. }
  1968. newTexture.name = id;
  1969. texture.babylonTexture = newTexture;
  1970. onSuccess(newTexture);
  1971. };
  1972. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1973. var shader = gltfRuntime.shaders[id];
  1974. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1975. var shaderString = atob(shader.uri.split(",")[1]);
  1976. if (onSuccess) {
  1977. onSuccess(shaderString);
  1978. }
  1979. }
  1980. else {
  1981. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1982. if (request && onError) {
  1983. onError(request.status + " " + request.statusText);
  1984. }
  1985. });
  1986. }
  1987. };
  1988. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1989. var material = gltfRuntime.materials[id];
  1990. if (!material.technique) {
  1991. if (onError) {
  1992. onError("No technique found.");
  1993. }
  1994. return;
  1995. }
  1996. var technique = gltfRuntime.techniques[material.technique];
  1997. if (!technique) {
  1998. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1999. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2000. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2001. onSuccess(defaultMaterial);
  2002. return;
  2003. }
  2004. var program = gltfRuntime.programs[technique.program];
  2005. var states = technique.states;
  2006. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2007. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2008. var newVertexShader = "";
  2009. var newPixelShader = "";
  2010. var vertexTokenizer = new Tokenizer(vertexShader);
  2011. var pixelTokenizer = new Tokenizer(pixelShader);
  2012. var unTreatedUniforms = {};
  2013. var uniforms = [];
  2014. var attributes = [];
  2015. var samplers = [];
  2016. // Fill uniform, sampler2D and attributes
  2017. for (var unif in technique.uniforms) {
  2018. var uniform = technique.uniforms[unif];
  2019. var uniformParameter = technique.parameters[uniform];
  2020. unTreatedUniforms[unif] = uniformParameter;
  2021. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2022. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2023. if (transformIndex !== -1) {
  2024. uniforms.push(babylonTransforms[transformIndex]);
  2025. delete unTreatedUniforms[unif];
  2026. }
  2027. else {
  2028. uniforms.push(unif);
  2029. }
  2030. }
  2031. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2032. samplers.push(unif);
  2033. }
  2034. else {
  2035. uniforms.push(unif);
  2036. }
  2037. }
  2038. for (var attr in technique.attributes) {
  2039. var attribute = technique.attributes[attr];
  2040. var attributeParameter = technique.parameters[attribute];
  2041. if (attributeParameter.semantic) {
  2042. var name_1 = getAttribute(attributeParameter);
  2043. if (name_1) {
  2044. attributes.push(name_1);
  2045. }
  2046. }
  2047. }
  2048. // Configure vertex shader
  2049. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2050. var tokenType = vertexTokenizer.currentToken;
  2051. if (tokenType !== ETokenType.IDENTIFIER) {
  2052. newVertexShader += vertexTokenizer.currentString;
  2053. continue;
  2054. }
  2055. var foundAttribute = false;
  2056. for (var attr in technique.attributes) {
  2057. var attribute = technique.attributes[attr];
  2058. var attributeParameter = technique.parameters[attribute];
  2059. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2060. newVertexShader += getAttribute(attributeParameter);
  2061. foundAttribute = true;
  2062. break;
  2063. }
  2064. }
  2065. if (foundAttribute) {
  2066. continue;
  2067. }
  2068. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2069. }
  2070. // Configure pixel shader
  2071. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2072. var tokenType = pixelTokenizer.currentToken;
  2073. if (tokenType !== ETokenType.IDENTIFIER) {
  2074. newPixelShader += pixelTokenizer.currentString;
  2075. continue;
  2076. }
  2077. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2078. }
  2079. // Create shader material
  2080. var shaderPath = {
  2081. vertex: program.vertexShader + id,
  2082. fragment: program.fragmentShader + id
  2083. };
  2084. var options = {
  2085. attributes: attributes,
  2086. uniforms: uniforms,
  2087. samplers: samplers,
  2088. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2089. };
  2090. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2091. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2092. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2093. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2094. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2095. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2096. if (states && states.functions) {
  2097. var functions = states.functions;
  2098. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2099. shaderMaterial.backFaceCulling = false;
  2100. }
  2101. var blendFunc = functions.blendFuncSeparate;
  2102. if (blendFunc) {
  2103. 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) {
  2104. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2105. }
  2106. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2107. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2108. }
  2109. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2110. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2111. }
  2112. 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) {
  2113. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2114. }
  2115. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2117. }
  2118. 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) {
  2119. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2120. }
  2121. }
  2122. }
  2123. };
  2124. return GLTFLoaderBase;
  2125. }());
  2126. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2127. /**
  2128. * glTF V1 Loader
  2129. */
  2130. var GLTFLoader = /** @class */ (function () {
  2131. function GLTFLoader() {
  2132. this.state = null;
  2133. }
  2134. GLTFLoader.RegisterExtension = function (extension) {
  2135. if (GLTFLoader.Extensions[extension.name]) {
  2136. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2137. return;
  2138. }
  2139. GLTFLoader.Extensions[extension.name] = extension;
  2140. };
  2141. GLTFLoader.prototype.dispose = function () {
  2142. // do nothing
  2143. };
  2144. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2145. var _this = this;
  2146. scene.useRightHandedSystem = true;
  2147. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2148. gltfRuntime.importOnlyMeshes = true;
  2149. if (meshesNames === "") {
  2150. gltfRuntime.importMeshesNames = [];
  2151. }
  2152. else if (typeof meshesNames === "string") {
  2153. gltfRuntime.importMeshesNames = [meshesNames];
  2154. }
  2155. else if (meshesNames && !(meshesNames instanceof Array)) {
  2156. gltfRuntime.importMeshesNames = [meshesNames];
  2157. }
  2158. else {
  2159. gltfRuntime.importMeshesNames = [];
  2160. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2161. }
  2162. // Create nodes
  2163. _this._createNodes(gltfRuntime);
  2164. var meshes = new Array();
  2165. var skeletons = new Array();
  2166. // Fill arrays of meshes and skeletons
  2167. for (var nde in gltfRuntime.nodes) {
  2168. var node = gltfRuntime.nodes[nde];
  2169. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2170. meshes.push(node.babylonNode);
  2171. }
  2172. }
  2173. for (var skl in gltfRuntime.skins) {
  2174. var skin = gltfRuntime.skins[skl];
  2175. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2176. skeletons.push(skin.babylonSkeleton);
  2177. }
  2178. }
  2179. // Load buffers, shaders, materials, etc.
  2180. _this._loadBuffersAsync(gltfRuntime, function () {
  2181. _this._loadShadersAsync(gltfRuntime, function () {
  2182. importMaterials(gltfRuntime);
  2183. postLoad(gltfRuntime);
  2184. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2185. onSuccess(meshes, skeletons);
  2186. }
  2187. });
  2188. }, onProgress);
  2189. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2190. onSuccess(meshes, skeletons);
  2191. }
  2192. }, onError);
  2193. return true;
  2194. };
  2195. /**
  2196. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2197. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2198. * @param scene the scene the meshes should be added to
  2199. * @param data gltf data containing information of the meshes in a loaded file
  2200. * @param rootUrl root url to load from
  2201. * @param onProgress event that fires when loading progress has occured
  2202. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2203. */
  2204. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2205. var _this = this;
  2206. return new Promise(function (resolve, reject) {
  2207. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  2208. resolve({
  2209. meshes: meshes,
  2210. particleSystems: [],
  2211. skeletons: skeletons,
  2212. animationGroups: []
  2213. });
  2214. }, onProgress, function (message) {
  2215. reject(new Error(message));
  2216. });
  2217. });
  2218. };
  2219. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2220. var _this = this;
  2221. scene.useRightHandedSystem = true;
  2222. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2223. // Load runtime extensios
  2224. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2225. // Create nodes
  2226. _this._createNodes(gltfRuntime);
  2227. // Load buffers, shaders, materials, etc.
  2228. _this._loadBuffersAsync(gltfRuntime, function () {
  2229. _this._loadShadersAsync(gltfRuntime, function () {
  2230. importMaterials(gltfRuntime);
  2231. postLoad(gltfRuntime);
  2232. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2233. onSuccess();
  2234. }
  2235. });
  2236. });
  2237. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2238. onSuccess();
  2239. }
  2240. }, onError);
  2241. }, onError);
  2242. };
  2243. /**
  2244. * Imports all objects from a loaded gltf file and adds them to the scene
  2245. * @param scene the scene the objects should be added to
  2246. * @param data gltf data containing information of the meshes in a loaded file
  2247. * @param rootUrl root url to load from
  2248. * @param onProgress event that fires when loading progress has occured
  2249. * @returns a promise which completes when objects have been loaded to the scene
  2250. */
  2251. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2252. var _this = this;
  2253. return new Promise(function (resolve, reject) {
  2254. _this._loadAsync(scene, data, rootUrl, function () {
  2255. resolve();
  2256. }, onProgress, function (message) {
  2257. reject(new Error(message));
  2258. });
  2259. });
  2260. };
  2261. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2262. var hasShaders = false;
  2263. var processShader = function (sha, shader) {
  2264. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2265. if (shaderString instanceof ArrayBuffer) {
  2266. return;
  2267. }
  2268. gltfRuntime.loadedShaderCount++;
  2269. if (shaderString) {
  2270. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2271. }
  2272. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2273. onload();
  2274. }
  2275. }, function () {
  2276. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2277. });
  2278. };
  2279. for (var sha in gltfRuntime.shaders) {
  2280. hasShaders = true;
  2281. var shader = gltfRuntime.shaders[sha];
  2282. if (shader) {
  2283. processShader.bind(this, sha, shader)();
  2284. }
  2285. else {
  2286. BABYLON.Tools.Error("No shader named: " + sha);
  2287. }
  2288. }
  2289. if (!hasShaders) {
  2290. onload();
  2291. }
  2292. };
  2293. ;
  2294. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2295. var hasBuffers = false;
  2296. var processBuffer = function (buf, buffer) {
  2297. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2298. gltfRuntime.loadedBufferCount++;
  2299. if (bufferView) {
  2300. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2301. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2302. }
  2303. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2304. }
  2305. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2306. onLoad();
  2307. }
  2308. }, function () {
  2309. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2310. });
  2311. };
  2312. for (var buf in gltfRuntime.buffers) {
  2313. hasBuffers = true;
  2314. var buffer = gltfRuntime.buffers[buf];
  2315. if (buffer) {
  2316. processBuffer.bind(this, buf, buffer)();
  2317. }
  2318. else {
  2319. BABYLON.Tools.Error("No buffer named: " + buf);
  2320. }
  2321. }
  2322. if (!hasBuffers) {
  2323. onLoad();
  2324. }
  2325. };
  2326. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2327. var currentScene = gltfRuntime.currentScene;
  2328. if (currentScene) {
  2329. // Only one scene even if multiple scenes are defined
  2330. for (var i = 0; i < currentScene.nodes.length; i++) {
  2331. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2332. }
  2333. }
  2334. else {
  2335. // Load all scenes
  2336. for (var thing in gltfRuntime.scenes) {
  2337. currentScene = gltfRuntime.scenes[thing];
  2338. for (var i = 0; i < currentScene.nodes.length; i++) {
  2339. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2340. }
  2341. }
  2342. }
  2343. };
  2344. GLTFLoader.Extensions = {};
  2345. return GLTFLoader;
  2346. }());
  2347. GLTF1.GLTFLoader = GLTFLoader;
  2348. ;
  2349. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2350. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2351. })(BABYLON || (BABYLON = {}));
  2352. //# sourceMappingURL=babylon.glTFLoader.js.map
  2353. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2354. var BABYLON;
  2355. (function (BABYLON) {
  2356. var GLTF1;
  2357. (function (GLTF1) {
  2358. /**
  2359. * Utils functions for GLTF
  2360. */
  2361. var GLTFUtils = /** @class */ (function () {
  2362. function GLTFUtils() {
  2363. }
  2364. /**
  2365. * Sets the given "parameter" matrix
  2366. * @param scene: the {BABYLON.Scene} object
  2367. * @param source: the source node where to pick the matrix
  2368. * @param parameter: the GLTF technique parameter
  2369. * @param uniformName: the name of the shader's uniform
  2370. * @param shaderMaterial: the shader material
  2371. */
  2372. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2373. var mat = null;
  2374. if (parameter.semantic === "MODEL") {
  2375. mat = source.getWorldMatrix();
  2376. }
  2377. else if (parameter.semantic === "PROJECTION") {
  2378. mat = scene.getProjectionMatrix();
  2379. }
  2380. else if (parameter.semantic === "VIEW") {
  2381. mat = scene.getViewMatrix();
  2382. }
  2383. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2384. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2385. }
  2386. else if (parameter.semantic === "MODELVIEW") {
  2387. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2388. }
  2389. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2390. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2391. }
  2392. else if (parameter.semantic === "MODELINVERSE") {
  2393. mat = source.getWorldMatrix().invert();
  2394. }
  2395. else if (parameter.semantic === "VIEWINVERSE") {
  2396. mat = scene.getViewMatrix().invert();
  2397. }
  2398. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2399. mat = scene.getProjectionMatrix().invert();
  2400. }
  2401. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2402. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2403. }
  2404. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2405. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2406. }
  2407. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2408. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2409. }
  2410. else {
  2411. debugger;
  2412. }
  2413. if (mat) {
  2414. switch (parameter.type) {
  2415. case GLTF1.EParameterType.FLOAT_MAT2:
  2416. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2417. break;
  2418. case GLTF1.EParameterType.FLOAT_MAT3:
  2419. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2420. break;
  2421. case GLTF1.EParameterType.FLOAT_MAT4:
  2422. shaderMaterial.setMatrix(uniformName, mat);
  2423. break;
  2424. default: break;
  2425. }
  2426. }
  2427. };
  2428. /**
  2429. * Sets the given "parameter" matrix
  2430. * @param shaderMaterial: the shader material
  2431. * @param uniform: the name of the shader's uniform
  2432. * @param value: the value of the uniform
  2433. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2434. */
  2435. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2436. switch (type) {
  2437. case GLTF1.EParameterType.FLOAT:
  2438. shaderMaterial.setFloat(uniform, value);
  2439. return true;
  2440. case GLTF1.EParameterType.FLOAT_VEC2:
  2441. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2442. return true;
  2443. case GLTF1.EParameterType.FLOAT_VEC3:
  2444. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2445. return true;
  2446. case GLTF1.EParameterType.FLOAT_VEC4:
  2447. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2448. return true;
  2449. default: return false;
  2450. }
  2451. };
  2452. /**
  2453. * Returns the wrap mode of the texture
  2454. * @param mode: the mode value
  2455. */
  2456. GLTFUtils.GetWrapMode = function (mode) {
  2457. switch (mode) {
  2458. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2459. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2460. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2461. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2462. }
  2463. };
  2464. /**
  2465. * Returns the byte stride giving an accessor
  2466. * @param accessor: the GLTF accessor objet
  2467. */
  2468. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2469. // Needs this function since "byteStride" isn't requiered in glTF format
  2470. var type = accessor.type;
  2471. switch (type) {
  2472. case "VEC2": return 2;
  2473. case "VEC3": return 3;
  2474. case "VEC4": return 4;
  2475. case "MAT2": return 4;
  2476. case "MAT3": return 9;
  2477. case "MAT4": return 16;
  2478. default: return 1;
  2479. }
  2480. };
  2481. /**
  2482. * Returns the texture filter mode giving a mode value
  2483. * @param mode: the filter mode value
  2484. */
  2485. GLTFUtils.GetTextureFilterMode = function (mode) {
  2486. switch (mode) {
  2487. case GLTF1.ETextureFilterType.LINEAR:
  2488. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2489. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2490. case GLTF1.ETextureFilterType.NEAREST:
  2491. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2492. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2493. }
  2494. };
  2495. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2496. var byteOffset = bufferView.byteOffset + byteOffset;
  2497. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2498. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2499. throw new Error("Buffer access is out of range");
  2500. }
  2501. var buffer = loadedBufferView.buffer;
  2502. byteOffset += loadedBufferView.byteOffset;
  2503. switch (componentType) {
  2504. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2505. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2506. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2507. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2508. default: return new Float32Array(buffer, byteOffset, byteLength);
  2509. }
  2510. };
  2511. /**
  2512. * Returns a buffer from its accessor
  2513. * @param gltfRuntime: the GLTF runtime
  2514. * @param accessor: the GLTF accessor
  2515. */
  2516. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2517. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2518. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2519. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2520. };
  2521. /**
  2522. * Decodes a buffer view into a string
  2523. * @param view: the buffer view
  2524. */
  2525. GLTFUtils.DecodeBufferToText = function (view) {
  2526. var result = "";
  2527. var length = view.byteLength;
  2528. for (var i = 0; i < length; ++i) {
  2529. result += String.fromCharCode(view[i]);
  2530. }
  2531. return result;
  2532. };
  2533. /**
  2534. * Returns the default material of gltf. Related to
  2535. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2536. * @param scene: the Babylon.js scene
  2537. */
  2538. GLTFUtils.GetDefaultMaterial = function (scene) {
  2539. if (!GLTFUtils._DefaultMaterial) {
  2540. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2541. "precision highp float;",
  2542. "",
  2543. "uniform mat4 worldView;",
  2544. "uniform mat4 projection;",
  2545. "",
  2546. "attribute vec3 position;",
  2547. "",
  2548. "void main(void)",
  2549. "{",
  2550. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2551. "}"
  2552. ].join("\n");
  2553. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2554. "precision highp float;",
  2555. "",
  2556. "uniform vec4 u_emission;",
  2557. "",
  2558. "void main(void)",
  2559. "{",
  2560. " gl_FragColor = u_emission;",
  2561. "}"
  2562. ].join("\n");
  2563. var shaderPath = {
  2564. vertex: "GLTFDefaultMaterial",
  2565. fragment: "GLTFDefaultMaterial"
  2566. };
  2567. var options = {
  2568. attributes: ["position"],
  2569. uniforms: ["worldView", "projection", "u_emission"],
  2570. samplers: new Array(),
  2571. needAlphaBlending: false
  2572. };
  2573. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2574. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2575. }
  2576. return GLTFUtils._DefaultMaterial;
  2577. };
  2578. // The GLTF default material
  2579. GLTFUtils._DefaultMaterial = null;
  2580. return GLTFUtils;
  2581. }());
  2582. GLTF1.GLTFUtils = GLTFUtils;
  2583. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2584. })(BABYLON || (BABYLON = {}));
  2585. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2586. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2587. var BABYLON;
  2588. (function (BABYLON) {
  2589. var GLTF1;
  2590. (function (GLTF1) {
  2591. var GLTFLoaderExtension = /** @class */ (function () {
  2592. function GLTFLoaderExtension(name) {
  2593. this._name = name;
  2594. }
  2595. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2596. get: function () {
  2597. return this._name;
  2598. },
  2599. enumerable: true,
  2600. configurable: true
  2601. });
  2602. /**
  2603. * Defines an override for loading the runtime
  2604. * Return true to stop further extensions from loading the runtime
  2605. */
  2606. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2607. return false;
  2608. };
  2609. /**
  2610. * Defines an onverride for creating gltf runtime
  2611. * Return true to stop further extensions from creating the runtime
  2612. */
  2613. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2614. return false;
  2615. };
  2616. /**
  2617. * Defines an override for loading buffers
  2618. * Return true to stop further extensions from loading this buffer
  2619. */
  2620. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2621. return false;
  2622. };
  2623. /**
  2624. * Defines an override for loading texture buffers
  2625. * Return true to stop further extensions from loading this texture data
  2626. */
  2627. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2628. return false;
  2629. };
  2630. /**
  2631. * Defines an override for creating textures
  2632. * Return true to stop further extensions from loading this texture
  2633. */
  2634. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2635. return false;
  2636. };
  2637. /**
  2638. * Defines an override for loading shader strings
  2639. * Return true to stop further extensions from loading this shader data
  2640. */
  2641. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2642. return false;
  2643. };
  2644. /**
  2645. * Defines an override for loading materials
  2646. * Return true to stop further extensions from loading this material
  2647. */
  2648. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2649. return false;
  2650. };
  2651. // ---------
  2652. // Utilities
  2653. // ---------
  2654. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2655. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2656. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2657. }, function () {
  2658. setTimeout(function () {
  2659. if (!onSuccess) {
  2660. return;
  2661. }
  2662. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2663. });
  2664. });
  2665. };
  2666. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2667. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2668. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2669. }, function () {
  2670. setTimeout(function () {
  2671. onSuccess();
  2672. });
  2673. });
  2674. };
  2675. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2676. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2677. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2678. }, function () {
  2679. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2680. });
  2681. };
  2682. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2683. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2684. if (buffer) {
  2685. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2686. }
  2687. }, onError);
  2688. };
  2689. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2690. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2691. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2692. }, function () {
  2693. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2694. });
  2695. };
  2696. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2697. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2698. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2699. }, function () {
  2700. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2701. });
  2702. };
  2703. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2704. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2705. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2706. }, function () {
  2707. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2708. });
  2709. };
  2710. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2711. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2712. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2713. }, function () {
  2714. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2715. });
  2716. };
  2717. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2718. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2719. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2720. if (func(loaderExtension)) {
  2721. return;
  2722. }
  2723. }
  2724. defaultFunc();
  2725. };
  2726. return GLTFLoaderExtension;
  2727. }());
  2728. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2729. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2730. })(BABYLON || (BABYLON = {}));
  2731. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2732. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2733. var __extends = (this && this.__extends) || (function () {
  2734. var extendStatics = function (d, b) {
  2735. extendStatics = Object.setPrototypeOf ||
  2736. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2737. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2738. return extendStatics(d, b);
  2739. }
  2740. return function (d, b) {
  2741. extendStatics(d, b);
  2742. function __() { this.constructor = d; }
  2743. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2744. };
  2745. })();
  2746. var BABYLON;
  2747. (function (BABYLON) {
  2748. var GLTF1;
  2749. (function (GLTF1) {
  2750. var BinaryExtensionBufferName = "binary_glTF";
  2751. ;
  2752. ;
  2753. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2754. __extends(GLTFBinaryExtension, _super);
  2755. function GLTFBinaryExtension() {
  2756. return _super.call(this, "KHR_binary_glTF") || this;
  2757. }
  2758. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2759. var extensionsUsed = data.json.extensionsUsed;
  2760. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2761. return false;
  2762. }
  2763. this._bin = data.bin;
  2764. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2765. return true;
  2766. };
  2767. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2768. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2769. return false;
  2770. }
  2771. if (id !== BinaryExtensionBufferName) {
  2772. return false;
  2773. }
  2774. onSuccess(this._bin);
  2775. return true;
  2776. };
  2777. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2778. var texture = gltfRuntime.textures[id];
  2779. var source = gltfRuntime.images[texture.source];
  2780. if (!source.extensions || !(this.name in source.extensions)) {
  2781. return false;
  2782. }
  2783. var sourceExt = source.extensions[this.name];
  2784. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2785. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2786. onSuccess(buffer);
  2787. return true;
  2788. };
  2789. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2790. var shader = gltfRuntime.shaders[id];
  2791. if (!shader.extensions || !(this.name in shader.extensions)) {
  2792. return false;
  2793. }
  2794. var binaryExtensionShader = shader.extensions[this.name];
  2795. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2796. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2797. setTimeout(function () {
  2798. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2799. onSuccess(shaderString);
  2800. });
  2801. return true;
  2802. };
  2803. return GLTFBinaryExtension;
  2804. }(GLTF1.GLTFLoaderExtension));
  2805. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2806. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2807. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2808. })(BABYLON || (BABYLON = {}));
  2809. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2810. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2811. var __extends = (this && this.__extends) || (function () {
  2812. var extendStatics = function (d, b) {
  2813. extendStatics = Object.setPrototypeOf ||
  2814. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2815. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2816. return extendStatics(d, b);
  2817. }
  2818. return function (d, b) {
  2819. extendStatics(d, b);
  2820. function __() { this.constructor = d; }
  2821. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2822. };
  2823. })();
  2824. var BABYLON;
  2825. (function (BABYLON) {
  2826. var GLTF1;
  2827. (function (GLTF1) {
  2828. ;
  2829. ;
  2830. ;
  2831. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2832. __extends(GLTFMaterialsCommonExtension, _super);
  2833. function GLTFMaterialsCommonExtension() {
  2834. return _super.call(this, "KHR_materials_common") || this;
  2835. }
  2836. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2837. if (!gltfRuntime.extensions)
  2838. return false;
  2839. var extension = gltfRuntime.extensions[this.name];
  2840. if (!extension)
  2841. return false;
  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. var extension = material.extensions[this.name];
  2889. if (!extension)
  2890. return false;
  2891. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2892. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2893. if (extension.technique === "CONSTANT") {
  2894. standardMaterial.disableLighting = true;
  2895. }
  2896. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2897. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2898. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2899. // Ambient
  2900. if (typeof extension.values.ambient === "string") {
  2901. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2902. }
  2903. else {
  2904. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2905. }
  2906. // Diffuse
  2907. if (typeof extension.values.diffuse === "string") {
  2908. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2909. }
  2910. else {
  2911. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2912. }
  2913. // Emission
  2914. if (typeof extension.values.emission === "string") {
  2915. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2916. }
  2917. else {
  2918. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2919. }
  2920. // Specular
  2921. if (typeof extension.values.specular === "string") {
  2922. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2923. }
  2924. else {
  2925. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2926. }
  2927. return true;
  2928. };
  2929. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2930. // Create buffer from texture url
  2931. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2932. // Create texture from buffer
  2933. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2934. }, onError);
  2935. };
  2936. return GLTFMaterialsCommonExtension;
  2937. }(GLTF1.GLTFLoaderExtension));
  2938. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2939. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2940. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2941. })(BABYLON || (BABYLON = {}));
  2942. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map