babylon.glTF1FileLoader.js 135 KB

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