babylon.glTF1FileLoader.js 136 KB

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