babylon.glTF1FileLoader.js 138 KB

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