babylon.glTF2FileLoader.js 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. /// <reference path="../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * Mode that determines the coordinate system to use.
  7. */
  8. var GLTFLoaderCoordinateSystemMode;
  9. (function (GLTFLoaderCoordinateSystemMode) {
  10. /**
  11. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  14. /**
  15. * Sets the useRightHandedSystem flag on the scene.
  16. */
  17. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  18. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  19. /**
  20. * Mode that determines what animations will start.
  21. */
  22. var GLTFLoaderAnimationStartMode;
  23. (function (GLTFLoaderAnimationStartMode) {
  24. /**
  25. * No animation will start.
  26. */
  27. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  28. /**
  29. * The first animation will start.
  30. */
  31. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  32. /**
  33. * All animations will start.
  34. */
  35. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  36. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  37. /**
  38. * Loader state.
  39. */
  40. var GLTFLoaderState;
  41. (function (GLTFLoaderState) {
  42. /**
  43. * The asset is loading.
  44. */
  45. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  46. /**
  47. * The asset is ready for rendering.
  48. */
  49. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  50. /**
  51. * The asset is completely loaded.
  52. */
  53. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  54. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  55. /**
  56. * File loader for loading glTF files into a scene.
  57. */
  58. var GLTFFileLoader = /** @class */ (function () {
  59. function GLTFFileLoader() {
  60. // --------------
  61. // Common options
  62. // --------------
  63. /**
  64. * Raised when the asset has been parsed
  65. */
  66. this.onParsedObservable = new BABYLON.Observable();
  67. // ----------
  68. // V2 options
  69. // ----------
  70. /**
  71. * The coordinate system mode. Defaults to AUTO.
  72. */
  73. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  74. /**
  75. * The animation start mode. Defaults to FIRST.
  76. */
  77. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  78. /**
  79. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  80. */
  81. this.compileMaterials = false;
  82. /**
  83. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  84. */
  85. this.useClipPlane = false;
  86. /**
  87. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  88. */
  89. this.compileShadowGenerators = false;
  90. /**
  91. * Defines if the Alpha blended materials are only applied as coverage.
  92. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  93. * If true, no extra effects are applied to transparent pixels.
  94. */
  95. this.transparencyAsCoverage = false;
  96. /**
  97. * Function called before loading a url referenced by the asset.
  98. */
  99. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  100. /**
  101. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102. */
  103. this.onMeshLoadedObservable = new BABYLON.Observable();
  104. /**
  105. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106. */
  107. this.onTextureLoadedObservable = new BABYLON.Observable();
  108. /**
  109. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  110. */
  111. this.onMaterialLoadedObservable = new BABYLON.Observable();
  112. /**
  113. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  114. */
  115. this.onCameraLoadedObservable = new BABYLON.Observable();
  116. /**
  117. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  118. * For assets with LODs, raised when all of the LODs are complete.
  119. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  120. */
  121. this.onCompleteObservable = new BABYLON.Observable();
  122. /**
  123. * Observable raised when an error occurs.
  124. */
  125. this.onErrorObservable = new BABYLON.Observable();
  126. /**
  127. * Observable raised after the loader is disposed.
  128. */
  129. this.onDisposeObservable = new BABYLON.Observable();
  130. /**
  131. * Observable raised after a loader extension is created.
  132. * Set additional options for a loader extension in this event.
  133. */
  134. this.onExtensionLoadedObservable = new BABYLON.Observable();
  135. /**
  136. * Defines if the loader should validate the asset.
  137. */
  138. this.validate = false;
  139. /**
  140. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  141. */
  142. this.onValidatedObservable = new BABYLON.Observable();
  143. this._loader = null;
  144. /**
  145. * Name of the loader ("gltf")
  146. */
  147. this.name = "gltf";
  148. /**
  149. * Supported file extensions of the loader (.gltf, .glb)
  150. */
  151. this.extensions = {
  152. ".gltf": { isBinary: false },
  153. ".glb": { isBinary: true }
  154. };
  155. this._logIndentLevel = 0;
  156. this._loggingEnabled = false;
  157. /** @hidden */
  158. this._log = this._logDisabled;
  159. this._capturePerformanceCounters = false;
  160. /** @hidden */
  161. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  162. /** @hidden */
  163. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  164. }
  165. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  166. /**
  167. * Raised when the asset has been parsed
  168. */
  169. set: function (callback) {
  170. if (this._onParsedObserver) {
  171. this.onParsedObservable.remove(this._onParsedObserver);
  172. }
  173. this._onParsedObserver = this.onParsedObservable.add(callback);
  174. },
  175. enumerable: true,
  176. configurable: true
  177. });
  178. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  179. /**
  180. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  181. */
  182. set: function (callback) {
  183. if (this._onMeshLoadedObserver) {
  184. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  185. }
  186. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  187. },
  188. enumerable: true,
  189. configurable: true
  190. });
  191. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  192. /**
  193. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  194. */
  195. set: function (callback) {
  196. if (this._onTextureLoadedObserver) {
  197. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  198. }
  199. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  200. },
  201. enumerable: true,
  202. configurable: true
  203. });
  204. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  205. /**
  206. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  207. */
  208. set: function (callback) {
  209. if (this._onMaterialLoadedObserver) {
  210. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  211. }
  212. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  213. },
  214. enumerable: true,
  215. configurable: true
  216. });
  217. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  218. /**
  219. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  220. */
  221. set: function (callback) {
  222. if (this._onCameraLoadedObserver) {
  223. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  224. }
  225. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  226. },
  227. enumerable: true,
  228. configurable: true
  229. });
  230. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  231. /**
  232. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  233. * For assets with LODs, raised when all of the LODs are complete.
  234. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  235. */
  236. set: function (callback) {
  237. if (this._onCompleteObserver) {
  238. this.onCompleteObservable.remove(this._onCompleteObserver);
  239. }
  240. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  241. },
  242. enumerable: true,
  243. configurable: true
  244. });
  245. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  246. /**
  247. * Callback raised when an error occurs.
  248. */
  249. set: function (callback) {
  250. if (this._onErrorObserver) {
  251. this.onErrorObservable.remove(this._onErrorObserver);
  252. }
  253. this._onErrorObserver = this.onErrorObservable.add(callback);
  254. },
  255. enumerable: true,
  256. configurable: true
  257. });
  258. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  259. /**
  260. * Callback raised after the loader is disposed.
  261. */
  262. set: function (callback) {
  263. if (this._onDisposeObserver) {
  264. this.onDisposeObservable.remove(this._onDisposeObserver);
  265. }
  266. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  267. },
  268. enumerable: true,
  269. configurable: true
  270. });
  271. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  272. /**
  273. * Callback raised after a loader extension is created.
  274. */
  275. set: function (callback) {
  276. if (this._onExtensionLoadedObserver) {
  277. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  278. }
  279. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  280. },
  281. enumerable: true,
  282. configurable: true
  283. });
  284. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  285. /**
  286. * Defines if the loader logging is enabled.
  287. */
  288. get: function () {
  289. return this._loggingEnabled;
  290. },
  291. set: function (value) {
  292. if (this._loggingEnabled === value) {
  293. return;
  294. }
  295. this._loggingEnabled = value;
  296. if (this._loggingEnabled) {
  297. this._log = this._logEnabled;
  298. }
  299. else {
  300. this._log = this._logDisabled;
  301. }
  302. },
  303. enumerable: true,
  304. configurable: true
  305. });
  306. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  307. /**
  308. * Defines if the loader should capture performance counters.
  309. */
  310. get: function () {
  311. return this._capturePerformanceCounters;
  312. },
  313. set: function (value) {
  314. if (this._capturePerformanceCounters === value) {
  315. return;
  316. }
  317. this._capturePerformanceCounters = value;
  318. if (this._capturePerformanceCounters) {
  319. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  320. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  321. }
  322. else {
  323. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  324. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  325. }
  326. },
  327. enumerable: true,
  328. configurable: true
  329. });
  330. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  331. /**
  332. * Callback raised after a loader extension is created.
  333. */
  334. set: function (callback) {
  335. if (this._onValidatedObserver) {
  336. this.onValidatedObservable.remove(this._onValidatedObserver);
  337. }
  338. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  339. },
  340. enumerable: true,
  341. configurable: true
  342. });
  343. /**
  344. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  345. */
  346. GLTFFileLoader.prototype.dispose = function () {
  347. if (this._loader) {
  348. this._loader.dispose();
  349. this._loader = null;
  350. }
  351. this._clear();
  352. this.onDisposeObservable.notifyObservers(undefined);
  353. this.onDisposeObservable.clear();
  354. };
  355. /** @hidden */
  356. GLTFFileLoader.prototype._clear = function () {
  357. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  358. this.onMeshLoadedObservable.clear();
  359. this.onTextureLoadedObservable.clear();
  360. this.onMaterialLoadedObservable.clear();
  361. this.onCameraLoadedObservable.clear();
  362. this.onCompleteObservable.clear();
  363. this.onExtensionLoadedObservable.clear();
  364. };
  365. /**
  366. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  367. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  368. * @param scene the scene the meshes should be added to
  369. * @param data the glTF data to load
  370. * @param rootUrl root url to load from
  371. * @param onProgress event that fires when loading progress has occured
  372. * @param fileName Defines the name of the file to load
  373. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  374. */
  375. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  376. var _this = this;
  377. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  378. _this._log("Loading " + (fileName || ""));
  379. _this._loader = _this._getLoader(loaderData);
  380. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  381. });
  382. };
  383. /**
  384. * Imports all objects from the loaded glTF data and adds them to the scene
  385. * @param scene the scene the objects should be added to
  386. * @param data the glTF data to load
  387. * @param rootUrl root url to load from
  388. * @param onProgress event that fires when loading progress has occured
  389. * @param fileName Defines the name of the file to load
  390. * @returns a promise which completes when objects have been loaded to the scene
  391. */
  392. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  393. var _this = this;
  394. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  395. _this._log("Loading " + (fileName || ""));
  396. _this._loader = _this._getLoader(loaderData);
  397. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  398. });
  399. };
  400. /**
  401. * Load into an asset container.
  402. * @param scene The scene to load into
  403. * @param data The data to import
  404. * @param rootUrl The root url for scene and resources
  405. * @param onProgress The callback when the load progresses
  406. * @param fileName Defines the name of the file to load
  407. * @returns The loaded asset container
  408. */
  409. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  410. var _this = this;
  411. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  412. _this._log("Loading " + (fileName || ""));
  413. _this._loader = _this._getLoader(loaderData);
  414. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  415. var container = new BABYLON.AssetContainer(scene);
  416. Array.prototype.push.apply(container.meshes, result.meshes);
  417. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  418. Array.prototype.push.apply(container.skeletons, result.skeletons);
  419. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  420. container.removeAllFromScene();
  421. return container;
  422. });
  423. });
  424. };
  425. /**
  426. * If the data string can be loaded directly.
  427. * @param data string contianing the file data
  428. * @returns if the data can be loaded directly
  429. */
  430. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  431. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  432. };
  433. /**
  434. * Instantiates a glTF file loader plugin.
  435. * @returns the created plugin
  436. */
  437. GLTFFileLoader.prototype.createPlugin = function () {
  438. return new GLTFFileLoader();
  439. };
  440. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  441. /**
  442. * The loader state or null if the loader is not active.
  443. */
  444. get: function () {
  445. return this._loader ? this._loader.state : null;
  446. },
  447. enumerable: true,
  448. configurable: true
  449. });
  450. /**
  451. * Returns a promise that resolves when the asset is completely loaded.
  452. * @returns a promise that resolves when the asset is completely loaded.
  453. */
  454. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  455. var _this = this;
  456. return new Promise(function (resolve, reject) {
  457. _this.onCompleteObservable.addOnce(function () {
  458. resolve();
  459. });
  460. _this.onErrorObservable.addOnce(function (reason) {
  461. reject(reason);
  462. });
  463. });
  464. };
  465. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  466. var _this = this;
  467. return Promise.resolve().then(function () {
  468. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  469. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  470. _this._startPerformanceCounter("Parse JSON");
  471. _this._log("JSON length: " + unpacked.json.length);
  472. var loaderData = {
  473. json: JSON.parse(unpacked.json),
  474. bin: unpacked.bin
  475. };
  476. _this._endPerformanceCounter("Parse JSON");
  477. _this.onParsedObservable.notifyObservers(loaderData);
  478. _this.onParsedObservable.clear();
  479. return loaderData;
  480. });
  481. });
  482. };
  483. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  484. var _this = this;
  485. if (!this.validate || typeof GLTFValidator === "undefined") {
  486. return Promise.resolve();
  487. }
  488. this._startPerformanceCounter("Validate JSON");
  489. var options = {
  490. externalResourceFunction: function (uri) {
  491. return _this.preprocessUrlAsync(rootUrl + uri)
  492. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  493. .then(function (data) { return new Uint8Array(data); });
  494. }
  495. };
  496. if (fileName && fileName.substr(0, 5) !== "data:") {
  497. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  498. }
  499. return GLTFValidator.validateString(json, options).then(function (result) {
  500. _this._endPerformanceCounter("Validate JSON");
  501. _this.onValidatedObservable.notifyObservers(result);
  502. _this.onValidatedObservable.clear();
  503. }, function (reason) {
  504. _this._endPerformanceCounter("Validate JSON");
  505. BABYLON.Tools.Warn("Failed to validate: " + reason);
  506. _this.onValidatedObservable.clear();
  507. });
  508. };
  509. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  510. var asset = loaderData.json.asset || {};
  511. this._log("Asset version: " + asset.version);
  512. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  513. asset.generator && this._log("Asset generator: " + asset.generator);
  514. var version = GLTFFileLoader._parseVersion(asset.version);
  515. if (!version) {
  516. throw new Error("Invalid version: " + asset.version);
  517. }
  518. if (asset.minVersion !== undefined) {
  519. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  520. if (!minVersion) {
  521. throw new Error("Invalid minimum version: " + asset.minVersion);
  522. }
  523. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  524. throw new Error("Incompatible minimum version: " + asset.minVersion);
  525. }
  526. }
  527. var createLoaders = {
  528. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  529. 2: GLTFFileLoader._CreateGLTFLoaderV2
  530. };
  531. var createLoader = createLoaders[version.major];
  532. if (!createLoader) {
  533. throw new Error("Unsupported version: " + asset.version);
  534. }
  535. return createLoader(this);
  536. };
  537. GLTFFileLoader.prototype._unpackBinary = function (data) {
  538. this._startPerformanceCounter("Unpack binary");
  539. this._log("Binary length: " + data.byteLength);
  540. var Binary = {
  541. Magic: 0x46546C67
  542. };
  543. var binaryReader = new BinaryReader(data);
  544. var magic = binaryReader.readUint32();
  545. if (magic !== Binary.Magic) {
  546. throw new Error("Unexpected magic: " + magic);
  547. }
  548. var version = binaryReader.readUint32();
  549. if (this.loggingEnabled) {
  550. this._log("Binary version: " + version);
  551. }
  552. var unpacked;
  553. switch (version) {
  554. case 1: {
  555. unpacked = this._unpackBinaryV1(binaryReader);
  556. break;
  557. }
  558. case 2: {
  559. unpacked = this._unpackBinaryV2(binaryReader);
  560. break;
  561. }
  562. default: {
  563. throw new Error("Unsupported version: " + version);
  564. }
  565. }
  566. this._endPerformanceCounter("Unpack binary");
  567. return unpacked;
  568. };
  569. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  570. var ContentFormat = {
  571. JSON: 0
  572. };
  573. var length = binaryReader.readUint32();
  574. if (length != binaryReader.getLength()) {
  575. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  576. }
  577. var contentLength = binaryReader.readUint32();
  578. var contentFormat = binaryReader.readUint32();
  579. var content;
  580. switch (contentFormat) {
  581. case ContentFormat.JSON: {
  582. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  583. break;
  584. }
  585. default: {
  586. throw new Error("Unexpected content format: " + contentFormat);
  587. }
  588. }
  589. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  590. var body = binaryReader.readUint8Array(bytesRemaining);
  591. return {
  592. json: content,
  593. bin: body
  594. };
  595. };
  596. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  597. var ChunkFormat = {
  598. JSON: 0x4E4F534A,
  599. BIN: 0x004E4942
  600. };
  601. var length = binaryReader.readUint32();
  602. if (length !== binaryReader.getLength()) {
  603. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  604. }
  605. // JSON chunk
  606. var chunkLength = binaryReader.readUint32();
  607. var chunkFormat = binaryReader.readUint32();
  608. if (chunkFormat !== ChunkFormat.JSON) {
  609. throw new Error("First chunk format is not JSON");
  610. }
  611. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  612. // Look for BIN chunk
  613. var bin = null;
  614. while (binaryReader.getPosition() < binaryReader.getLength()) {
  615. var chunkLength_1 = binaryReader.readUint32();
  616. var chunkFormat_1 = binaryReader.readUint32();
  617. switch (chunkFormat_1) {
  618. case ChunkFormat.JSON: {
  619. throw new Error("Unexpected JSON chunk");
  620. }
  621. case ChunkFormat.BIN: {
  622. bin = binaryReader.readUint8Array(chunkLength_1);
  623. break;
  624. }
  625. default: {
  626. // ignore unrecognized chunkFormat
  627. binaryReader.skipBytes(chunkLength_1);
  628. break;
  629. }
  630. }
  631. }
  632. return {
  633. json: json,
  634. bin: bin
  635. };
  636. };
  637. GLTFFileLoader._parseVersion = function (version) {
  638. if (version === "1.0" || version === "1.0.1") {
  639. return {
  640. major: 1,
  641. minor: 0
  642. };
  643. }
  644. var match = (version + "").match(/^(\d+)\.(\d+)/);
  645. if (!match) {
  646. return null;
  647. }
  648. return {
  649. major: parseInt(match[1]),
  650. minor: parseInt(match[2])
  651. };
  652. };
  653. GLTFFileLoader._compareVersion = function (a, b) {
  654. if (a.major > b.major) {
  655. return 1;
  656. }
  657. if (a.major < b.major) {
  658. return -1;
  659. }
  660. if (a.minor > b.minor) {
  661. return 1;
  662. }
  663. if (a.minor < b.minor) {
  664. return -1;
  665. }
  666. return 0;
  667. };
  668. GLTFFileLoader._decodeBufferToText = function (buffer) {
  669. var result = "";
  670. var length = buffer.byteLength;
  671. for (var i = 0; i < length; i++) {
  672. result += String.fromCharCode(buffer[i]);
  673. }
  674. return result;
  675. };
  676. /** @hidden */
  677. GLTFFileLoader.prototype._logOpen = function (message) {
  678. this._log(message);
  679. this._logIndentLevel++;
  680. };
  681. /** @hidden */
  682. GLTFFileLoader.prototype._logClose = function () {
  683. --this._logIndentLevel;
  684. };
  685. GLTFFileLoader.prototype._logEnabled = function (message) {
  686. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  687. BABYLON.Tools.Log("" + spaces + message);
  688. };
  689. GLTFFileLoader.prototype._logDisabled = function (message) {
  690. };
  691. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  692. BABYLON.Tools.StartPerformanceCounter(counterName);
  693. };
  694. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  695. };
  696. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  697. BABYLON.Tools.EndPerformanceCounter(counterName);
  698. };
  699. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  700. };
  701. // ----------
  702. // V1 options
  703. // ----------
  704. /**
  705. * 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.
  706. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  707. * Defaults to true.
  708. * @hidden
  709. */
  710. GLTFFileLoader.IncrementalLoading = true;
  711. /**
  712. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  713. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  714. * @hidden
  715. */
  716. GLTFFileLoader.HomogeneousCoordinates = false;
  717. GLTFFileLoader._logSpaces = " ";
  718. return GLTFFileLoader;
  719. }());
  720. BABYLON.GLTFFileLoader = GLTFFileLoader;
  721. var BinaryReader = /** @class */ (function () {
  722. function BinaryReader(arrayBuffer) {
  723. this._arrayBuffer = arrayBuffer;
  724. this._dataView = new DataView(arrayBuffer);
  725. this._byteOffset = 0;
  726. }
  727. BinaryReader.prototype.getPosition = function () {
  728. return this._byteOffset;
  729. };
  730. BinaryReader.prototype.getLength = function () {
  731. return this._arrayBuffer.byteLength;
  732. };
  733. BinaryReader.prototype.readUint32 = function () {
  734. var value = this._dataView.getUint32(this._byteOffset, true);
  735. this._byteOffset += 4;
  736. return value;
  737. };
  738. BinaryReader.prototype.readUint8Array = function (length) {
  739. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  740. this._byteOffset += length;
  741. return value;
  742. };
  743. BinaryReader.prototype.skipBytes = function (length) {
  744. this._byteOffset += length;
  745. };
  746. return BinaryReader;
  747. }());
  748. if (BABYLON.SceneLoader) {
  749. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  750. }
  751. })(BABYLON || (BABYLON = {}));
  752. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  753. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  754. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  755. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  756. /**
  757. * Defines the module for importing and exporting glTF 2.0 assets
  758. */
  759. var BABYLON;
  760. (function (BABYLON) {
  761. var GLTF2;
  762. (function (GLTF2) {
  763. /**
  764. * Helper class for working with arrays when loading the glTF asset
  765. */
  766. var ArrayItem = /** @class */ (function () {
  767. function ArrayItem() {
  768. }
  769. /**
  770. * Gets an item from the given array.
  771. * @param context The context when loading the asset
  772. * @param array The array to get the item from
  773. * @param index The index to the array
  774. * @returns The array item
  775. */
  776. ArrayItem.Get = function (context, array, index) {
  777. if (!array || index == undefined || !array[index]) {
  778. throw new Error(context + ": Failed to find index (" + index + ")");
  779. }
  780. return array[index];
  781. };
  782. /**
  783. * Assign an `index` field to each item of the given array.
  784. * @param array The array of items
  785. */
  786. ArrayItem.Assign = function (array) {
  787. if (array) {
  788. for (var index = 0; index < array.length; index++) {
  789. array[index].index = index;
  790. }
  791. }
  792. };
  793. return ArrayItem;
  794. }());
  795. GLTF2.ArrayItem = ArrayItem;
  796. /**
  797. * The glTF 2.0 loader
  798. */
  799. var GLTFLoader = /** @class */ (function () {
  800. /** @hidden */
  801. function GLTFLoader(parent) {
  802. /** @hidden */
  803. this._completePromises = new Array();
  804. this._disposed = false;
  805. this._state = null;
  806. this._extensions = {};
  807. this._defaultBabylonMaterialData = {};
  808. this._requests = new Array();
  809. this._parent = parent;
  810. }
  811. /**
  812. * Registers a loader extension.
  813. * @param name The name of the loader extension.
  814. * @param factory The factory function that creates the loader extension.
  815. */
  816. GLTFLoader.RegisterExtension = function (name, factory) {
  817. if (GLTFLoader.UnregisterExtension(name)) {
  818. BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
  819. }
  820. GLTFLoader._ExtensionFactories[name] = factory;
  821. // Keep the order of registration so that extensions registered first are called first.
  822. GLTFLoader._ExtensionNames.push(name);
  823. };
  824. /**
  825. * Unregisters a loader extension.
  826. * @param name The name of the loader extenion.
  827. * @returns A boolean indicating whether the extension has been unregistered
  828. */
  829. GLTFLoader.UnregisterExtension = function (name) {
  830. if (!GLTFLoader._ExtensionFactories[name]) {
  831. return false;
  832. }
  833. delete GLTFLoader._ExtensionFactories[name];
  834. var index = GLTFLoader._ExtensionNames.indexOf(name);
  835. if (index !== -1) {
  836. GLTFLoader._ExtensionNames.splice(index, 1);
  837. }
  838. return true;
  839. };
  840. Object.defineProperty(GLTFLoader.prototype, "state", {
  841. /**
  842. * Gets the loader state.
  843. */
  844. get: function () {
  845. return this._state;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. /** @hidden */
  851. GLTFLoader.prototype.dispose = function () {
  852. if (this._disposed) {
  853. return;
  854. }
  855. this._disposed = true;
  856. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  857. var request = _a[_i];
  858. request.abort();
  859. }
  860. this._requests.length = 0;
  861. delete this.gltf;
  862. delete this.babylonScene;
  863. this._completePromises.length = 0;
  864. for (var name_1 in this._extensions) {
  865. var extension = this._extensions[name_1];
  866. if (extension.dispose) {
  867. this._extensions[name_1].dispose();
  868. }
  869. }
  870. this._extensions = {};
  871. delete this._rootBabylonMesh;
  872. delete this._progressCallback;
  873. this._parent._clear();
  874. };
  875. /** @hidden */
  876. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  877. var _this = this;
  878. return Promise.resolve().then(function () {
  879. _this.babylonScene = scene;
  880. _this._rootUrl = rootUrl;
  881. _this._fileName = fileName || "scene";
  882. _this._progressCallback = onProgress;
  883. _this._loadData(data);
  884. var nodes = null;
  885. if (meshesNames) {
  886. var nodeMap_1 = {};
  887. if (_this.gltf.nodes) {
  888. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  889. var node = _a[_i];
  890. if (node.name) {
  891. nodeMap_1[node.name] = node.index;
  892. }
  893. }
  894. }
  895. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  896. nodes = names.map(function (name) {
  897. var node = nodeMap_1[name];
  898. if (node === undefined) {
  899. throw new Error("Failed to find node '" + name + "'");
  900. }
  901. return node;
  902. });
  903. }
  904. return _this._loadAsync(nodes, function () {
  905. return {
  906. meshes: _this._getMeshes(),
  907. particleSystems: [],
  908. skeletons: _this._getSkeletons(),
  909. animationGroups: _this._getAnimationGroups()
  910. };
  911. });
  912. });
  913. };
  914. /** @hidden */
  915. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  916. var _this = this;
  917. return Promise.resolve().then(function () {
  918. _this.babylonScene = scene;
  919. _this._rootUrl = rootUrl;
  920. _this._fileName = fileName || "scene";
  921. _this._progressCallback = onProgress;
  922. _this._loadData(data);
  923. return _this._loadAsync(null, function () { return undefined; });
  924. });
  925. };
  926. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  927. var _this = this;
  928. return Promise.resolve().then(function () {
  929. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  930. _this._loadExtensions();
  931. _this._checkExtensions();
  932. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  933. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  934. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  935. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  936. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  937. _this._extensionsOnLoading();
  938. var promises = new Array();
  939. if (nodes) {
  940. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  941. }
  942. else {
  943. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  944. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  945. }
  946. if (_this._parent.compileMaterials) {
  947. promises.push(_this._compileMaterialsAsync());
  948. }
  949. if (_this._parent.compileShadowGenerators) {
  950. promises.push(_this._compileShadowGeneratorsAsync());
  951. }
  952. var resultPromise = Promise.all(promises).then(function () {
  953. if (_this._rootBabylonMesh) {
  954. _this._rootBabylonMesh.setEnabled(true);
  955. }
  956. _this._setState(BABYLON.GLTFLoaderState.READY);
  957. _this._extensionsOnReady();
  958. _this._startAnimations();
  959. return resultFunc();
  960. });
  961. resultPromise.then(function () {
  962. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  963. BABYLON.Tools.SetImmediate(function () {
  964. if (!_this._disposed) {
  965. Promise.all(_this._completePromises).then(function () {
  966. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  967. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  968. _this._parent.onCompleteObservable.notifyObservers(undefined);
  969. _this._parent.onCompleteObservable.clear();
  970. _this.dispose();
  971. }, function (error) {
  972. _this._parent.onErrorObservable.notifyObservers(error);
  973. _this._parent.onErrorObservable.clear();
  974. _this.dispose();
  975. });
  976. }
  977. });
  978. });
  979. return resultPromise;
  980. }, function (error) {
  981. if (!_this._disposed) {
  982. _this._parent.onErrorObservable.notifyObservers(error);
  983. _this._parent.onErrorObservable.clear();
  984. _this.dispose();
  985. }
  986. throw error;
  987. });
  988. };
  989. GLTFLoader.prototype._loadData = function (data) {
  990. this.gltf = data.json;
  991. this._setupData();
  992. if (data.bin) {
  993. var buffers = this.gltf.buffers;
  994. if (buffers && buffers[0] && !buffers[0].uri) {
  995. var binaryBuffer = buffers[0];
  996. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  997. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  998. }
  999. binaryBuffer._data = Promise.resolve(data.bin);
  1000. }
  1001. else {
  1002. BABYLON.Tools.Warn("Unexpected BIN chunk");
  1003. }
  1004. }
  1005. };
  1006. GLTFLoader.prototype._setupData = function () {
  1007. ArrayItem.Assign(this.gltf.accessors);
  1008. ArrayItem.Assign(this.gltf.animations);
  1009. ArrayItem.Assign(this.gltf.buffers);
  1010. ArrayItem.Assign(this.gltf.bufferViews);
  1011. ArrayItem.Assign(this.gltf.cameras);
  1012. ArrayItem.Assign(this.gltf.images);
  1013. ArrayItem.Assign(this.gltf.materials);
  1014. ArrayItem.Assign(this.gltf.meshes);
  1015. ArrayItem.Assign(this.gltf.nodes);
  1016. ArrayItem.Assign(this.gltf.samplers);
  1017. ArrayItem.Assign(this.gltf.scenes);
  1018. ArrayItem.Assign(this.gltf.skins);
  1019. ArrayItem.Assign(this.gltf.textures);
  1020. if (this.gltf.nodes) {
  1021. var nodeParents = {};
  1022. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  1023. var node = _a[_i];
  1024. if (node.children) {
  1025. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  1026. var index = _c[_b];
  1027. nodeParents[index] = node.index;
  1028. }
  1029. }
  1030. }
  1031. var rootNode = this._createRootNode();
  1032. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  1033. var node = _e[_d];
  1034. var parentIndex = nodeParents[node.index];
  1035. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  1036. }
  1037. }
  1038. };
  1039. GLTFLoader.prototype._loadExtensions = function () {
  1040. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  1041. var name_2 = _a[_i];
  1042. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  1043. this._extensions[name_2] = extension;
  1044. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  1045. }
  1046. this._parent.onExtensionLoadedObservable.clear();
  1047. };
  1048. GLTFLoader.prototype._checkExtensions = function () {
  1049. if (this.gltf.extensionsRequired) {
  1050. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  1051. var name_3 = _a[_i];
  1052. var extension = this._extensions[name_3];
  1053. if (!extension || !extension.enabled) {
  1054. throw new Error("Require extension " + name_3 + " is not available");
  1055. }
  1056. }
  1057. }
  1058. };
  1059. GLTFLoader.prototype._setState = function (state) {
  1060. this._state = state;
  1061. this.log(BABYLON.GLTFLoaderState[this._state]);
  1062. };
  1063. GLTFLoader.prototype._createRootNode = function () {
  1064. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
  1065. this._rootBabylonMesh.setEnabled(false);
  1066. var rootNode = {
  1067. _babylonTransformNode: this._rootBabylonMesh,
  1068. index: -1
  1069. };
  1070. switch (this._parent.coordinateSystemMode) {
  1071. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  1072. if (!this.babylonScene.useRightHandedSystem) {
  1073. rootNode.rotation = [0, 1, 0, 0];
  1074. rootNode.scale = [1, 1, -1];
  1075. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  1076. }
  1077. break;
  1078. }
  1079. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  1080. this.babylonScene.useRightHandedSystem = true;
  1081. break;
  1082. }
  1083. default: {
  1084. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  1085. }
  1086. }
  1087. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  1088. return rootNode;
  1089. };
  1090. /**
  1091. * Loads a glTF scene.
  1092. * @param context The context when loading the asset
  1093. * @param scene The glTF scene property
  1094. * @returns A promise that resolves when the load is complete
  1095. */
  1096. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  1097. var _this = this;
  1098. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  1099. if (extensionPromise) {
  1100. return extensionPromise;
  1101. }
  1102. var promises = new Array();
  1103. this.logOpen(context + " " + (scene.name || ""));
  1104. if (scene.nodes) {
  1105. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  1106. var index = _a[_i];
  1107. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  1108. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  1109. babylonMesh.parent = _this._rootBabylonMesh;
  1110. }));
  1111. }
  1112. }
  1113. promises.push(this._loadAnimationsAsync());
  1114. this.logClose();
  1115. return Promise.all(promises).then(function () { });
  1116. };
  1117. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  1118. if (node._primitiveBabylonMeshes) {
  1119. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1120. var babylonMesh = _a[_i];
  1121. callback(babylonMesh);
  1122. }
  1123. }
  1124. else if (node._babylonTransformNode instanceof BABYLON.AbstractMesh) {
  1125. callback(node._babylonTransformNode);
  1126. }
  1127. };
  1128. GLTFLoader.prototype._getMeshes = function () {
  1129. var meshes = new Array();
  1130. // Root mesh is always first.
  1131. meshes.push(this._rootBabylonMesh);
  1132. var nodes = this.gltf.nodes;
  1133. if (nodes) {
  1134. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1135. var node = nodes_1[_i];
  1136. this._forEachPrimitive(node, function (babylonMesh) {
  1137. meshes.push(babylonMesh);
  1138. });
  1139. }
  1140. }
  1141. return meshes;
  1142. };
  1143. GLTFLoader.prototype._getSkeletons = function () {
  1144. var skeletons = new Array();
  1145. var skins = this.gltf.skins;
  1146. if (skins) {
  1147. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1148. var skin = skins_1[_i];
  1149. if (skin._data) {
  1150. skeletons.push(skin._data.babylonSkeleton);
  1151. }
  1152. }
  1153. }
  1154. return skeletons;
  1155. };
  1156. GLTFLoader.prototype._getAnimationGroups = function () {
  1157. var animationGroups = new Array();
  1158. var animations = this.gltf.animations;
  1159. if (animations) {
  1160. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1161. var animation = animations_1[_i];
  1162. if (animation._babylonAnimationGroup) {
  1163. animationGroups.push(animation._babylonAnimationGroup);
  1164. }
  1165. }
  1166. }
  1167. return animationGroups;
  1168. };
  1169. GLTFLoader.prototype._startAnimations = function () {
  1170. switch (this._parent.animationStartMode) {
  1171. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  1172. // do nothing
  1173. break;
  1174. }
  1175. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  1176. var babylonAnimationGroups = this._getAnimationGroups();
  1177. if (babylonAnimationGroups.length !== 0) {
  1178. babylonAnimationGroups[0].start(true);
  1179. }
  1180. break;
  1181. }
  1182. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  1183. var babylonAnimationGroups = this._getAnimationGroups();
  1184. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1185. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1186. babylonAnimationGroup.start(true);
  1187. }
  1188. break;
  1189. }
  1190. default: {
  1191. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1192. return;
  1193. }
  1194. }
  1195. };
  1196. /**
  1197. * Loads a glTF node.
  1198. * @param context The context when loading the asset
  1199. * @param node The glTF node property
  1200. * @param assign A function called synchronously after parsing the glTF properties
  1201. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  1202. */
  1203. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  1204. var _this = this;
  1205. if (assign === void 0) { assign = function () { }; }
  1206. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  1207. if (extensionPromise) {
  1208. return extensionPromise;
  1209. }
  1210. if (node._babylonTransformNode) {
  1211. throw new Error(context + ": Invalid recursive node hierarchy");
  1212. }
  1213. var promises = new Array();
  1214. this.logOpen(context + " " + (node.name || ""));
  1215. var loadNode = function (babylonTransformNode) {
  1216. GLTFLoader._LoadTransform(node, babylonTransformNode);
  1217. if (node.camera != undefined) {
  1218. var camera = ArrayItem.Get(context + "/camera", _this.gltf.cameras, node.camera);
  1219. promises.push(_this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  1220. babylonCamera.parent = babylonTransformNode;
  1221. }));
  1222. }
  1223. if (node.children) {
  1224. var _loop_1 = function (index) {
  1225. var childNode = ArrayItem.Get(context + "/children/" + index, _this.gltf.nodes, index);
  1226. promises.push(_this.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  1227. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1228. if (childNode.skin != undefined) {
  1229. childBabylonMesh.parent = _this._rootBabylonMesh;
  1230. return;
  1231. }
  1232. childBabylonMesh.parent = babylonTransformNode;
  1233. }));
  1234. };
  1235. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1236. var index = _a[_i];
  1237. _loop_1(index);
  1238. }
  1239. }
  1240. assign(babylonTransformNode);
  1241. };
  1242. if (node.mesh == undefined) {
  1243. var nodeName = node.name || "node" + node.index;
  1244. node._babylonTransformNode = new BABYLON.TransformNode(nodeName, this.babylonScene);
  1245. loadNode(node._babylonTransformNode);
  1246. }
  1247. else {
  1248. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  1249. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, loadNode));
  1250. }
  1251. this.logClose();
  1252. return Promise.all(promises).then(function () {
  1253. _this._forEachPrimitive(node, function (babylonMesh) {
  1254. babylonMesh.refreshBoundingInfo(true);
  1255. });
  1256. return node._babylonTransformNode;
  1257. });
  1258. };
  1259. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, assign) {
  1260. var primitives = mesh.primitives;
  1261. if (!primitives || !primitives.length) {
  1262. throw new Error(context + ": Primitives are missing");
  1263. }
  1264. if (primitives[0].index == undefined) {
  1265. ArrayItem.Assign(primitives);
  1266. }
  1267. var promises = new Array();
  1268. this.logOpen(context + " " + (mesh.name || ""));
  1269. var name = node.name || "node" + node.index;
  1270. if (primitives.length === 1) {
  1271. var primitive = mesh.primitives[0];
  1272. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name, node, mesh, primitive, function (babylonMesh) {
  1273. node._babylonTransformNode = babylonMesh;
  1274. }));
  1275. }
  1276. else {
  1277. var babylonTransformNode_1 = new BABYLON.TransformNode(name, this.babylonScene);
  1278. node._babylonTransformNode = babylonTransformNode_1;
  1279. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1280. var primitive = primitives_1[_i];
  1281. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name + "_primitive" + primitive.index, node, mesh, primitive, function (babylonMesh) {
  1282. babylonMesh.parent = babylonTransformNode_1;
  1283. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  1284. node._primitiveBabylonMeshes.push(babylonMesh);
  1285. }));
  1286. }
  1287. }
  1288. if (node.skin != undefined) {
  1289. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  1290. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  1291. }
  1292. assign(node._babylonTransformNode);
  1293. this.logClose();
  1294. return Promise.all(promises).then(function () {
  1295. return node._babylonTransformNode;
  1296. });
  1297. };
  1298. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) {
  1299. var _this = this;
  1300. this.logOpen("" + context);
  1301. var canInstance = (node.skin == undefined && !mesh.primitives[0].targets);
  1302. var babylonAbstractMesh;
  1303. var promise;
  1304. var instanceData = primitive._instanceData;
  1305. if (canInstance && instanceData) {
  1306. babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name);
  1307. promise = instanceData.promise;
  1308. }
  1309. else {
  1310. var promises = new Array();
  1311. var babylonMesh_1 = new BABYLON.Mesh(name, this.babylonScene);
  1312. this._createMorphTargets(context, node, mesh, primitive, babylonMesh_1);
  1313. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh_1).then(function (babylonGeometry) {
  1314. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh_1, babylonGeometry).then(function () {
  1315. babylonGeometry.applyToMesh(babylonMesh_1);
  1316. });
  1317. }));
  1318. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1319. if (primitive.material == undefined) {
  1320. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  1321. if (!babylonMaterial) {
  1322. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  1323. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1324. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  1325. }
  1326. babylonMesh_1.material = babylonMaterial;
  1327. }
  1328. else {
  1329. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  1330. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh_1, babylonDrawMode, function (babylonMaterial) {
  1331. babylonMesh_1.material = babylonMaterial;
  1332. }));
  1333. }
  1334. promise = Promise.all(promises);
  1335. if (canInstance) {
  1336. primitive._instanceData = {
  1337. babylonSourceMesh: babylonMesh_1,
  1338. promise: promise
  1339. };
  1340. }
  1341. babylonAbstractMesh = babylonMesh_1;
  1342. }
  1343. this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);
  1344. assign(babylonAbstractMesh);
  1345. this.logClose();
  1346. return promise.then(function () {
  1347. return babylonAbstractMesh;
  1348. });
  1349. };
  1350. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1351. var _this = this;
  1352. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  1353. if (extensionPromise) {
  1354. return extensionPromise;
  1355. }
  1356. var attributes = primitive.attributes;
  1357. if (!attributes) {
  1358. throw new Error(context + ": Attributes are missing");
  1359. }
  1360. var promises = new Array();
  1361. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
  1362. if (primitive.indices == undefined) {
  1363. babylonMesh.isUnIndexed = true;
  1364. }
  1365. else {
  1366. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  1367. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1368. babylonGeometry.setIndices(data);
  1369. }));
  1370. }
  1371. var loadAttribute = function (attribute, kind, callback) {
  1372. if (attributes[attribute] == undefined) {
  1373. return;
  1374. }
  1375. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1376. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1377. babylonMesh._delayInfo.push(kind);
  1378. }
  1379. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1380. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  1381. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1382. }));
  1383. if (callback) {
  1384. callback(accessor);
  1385. }
  1386. };
  1387. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1388. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1389. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1390. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1391. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1392. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1393. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1394. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1395. if (accessor.type === "VEC4" /* VEC4 */) {
  1396. babylonMesh.hasVertexAlpha = true;
  1397. }
  1398. });
  1399. return Promise.all(promises).then(function () {
  1400. return babylonGeometry;
  1401. });
  1402. };
  1403. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1404. if (!primitive.targets) {
  1405. return;
  1406. }
  1407. if (node._numMorphTargets == undefined) {
  1408. node._numMorphTargets = primitive.targets.length;
  1409. }
  1410. else if (primitive.targets.length !== node._numMorphTargets) {
  1411. throw new Error(context + ": Primitives do not have the same number of targets");
  1412. }
  1413. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1414. for (var index = 0; index < primitive.targets.length; index++) {
  1415. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1416. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1417. // TODO: tell the target whether it has positions, normals, tangents
  1418. }
  1419. };
  1420. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1421. if (!primitive.targets) {
  1422. return Promise.resolve();
  1423. }
  1424. var promises = new Array();
  1425. var morphTargetManager = babylonMesh.morphTargetManager;
  1426. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1427. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1428. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1429. }
  1430. return Promise.all(promises).then(function () { });
  1431. };
  1432. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1433. var _this = this;
  1434. var promises = new Array();
  1435. var loadAttribute = function (attribute, kind, setData) {
  1436. if (attributes[attribute] == undefined) {
  1437. return;
  1438. }
  1439. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1440. if (!babylonVertexBuffer) {
  1441. return;
  1442. }
  1443. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1444. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1445. setData(babylonVertexBuffer, data);
  1446. }));
  1447. };
  1448. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1449. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1450. data[index] += value;
  1451. });
  1452. babylonMorphTarget.setPositions(data);
  1453. });
  1454. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1455. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1456. data[index] += value;
  1457. });
  1458. babylonMorphTarget.setNormals(data);
  1459. });
  1460. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1461. var dataIndex = 0;
  1462. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1463. // Tangent data for morph targets is stored as xyz delta.
  1464. // The vertexData.tangent is stored as xyzw.
  1465. // So we need to skip every fourth vertexData.tangent.
  1466. if (((index + 1) % 4) !== 0) {
  1467. data[dataIndex++] += value;
  1468. }
  1469. });
  1470. babylonMorphTarget.setTangents(data);
  1471. });
  1472. return Promise.all(promises).then(function () { });
  1473. };
  1474. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1475. // Ignore the TRS of skinned nodes.
  1476. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1477. if (node.skin != undefined) {
  1478. return;
  1479. }
  1480. var position = BABYLON.Vector3.Zero();
  1481. var rotation = BABYLON.Quaternion.Identity();
  1482. var scaling = BABYLON.Vector3.One();
  1483. if (node.matrix) {
  1484. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1485. matrix.decompose(scaling, rotation, position);
  1486. }
  1487. else {
  1488. if (node.translation) {
  1489. position = BABYLON.Vector3.FromArray(node.translation);
  1490. }
  1491. if (node.rotation) {
  1492. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1493. }
  1494. if (node.scale) {
  1495. scaling = BABYLON.Vector3.FromArray(node.scale);
  1496. }
  1497. }
  1498. babylonNode.position = position;
  1499. babylonNode.rotationQuaternion = rotation;
  1500. babylonNode.scaling = scaling;
  1501. };
  1502. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  1503. var _this = this;
  1504. var assignSkeleton = function (skeleton) {
  1505. _this._forEachPrimitive(node, function (babylonMesh) {
  1506. babylonMesh.skeleton = skeleton;
  1507. });
  1508. };
  1509. if (skin._data) {
  1510. var data_1 = skin._data;
  1511. return data_1.promise.then(function () {
  1512. assignSkeleton(data_1.babylonSkeleton);
  1513. });
  1514. }
  1515. var skeletonId = "skeleton" + skin.index;
  1516. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  1517. this._loadBones(context, skin, babylonSkeleton);
  1518. assignSkeleton(babylonSkeleton);
  1519. var promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1520. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1521. });
  1522. skin._data = {
  1523. babylonSkeleton: babylonSkeleton,
  1524. promise: promise
  1525. };
  1526. return promise;
  1527. };
  1528. GLTFLoader.prototype._loadBones = function (context, skin, babylonSkeleton) {
  1529. var babylonBones = {};
  1530. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1531. var index = _a[_i];
  1532. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  1533. this._loadBone(node, skin, babylonSkeleton, babylonBones);
  1534. }
  1535. };
  1536. GLTFLoader.prototype._loadBone = function (node, skin, babylonSkeleton, babylonBones) {
  1537. var babylonBone = babylonBones[node.index];
  1538. if (babylonBone) {
  1539. return babylonBone;
  1540. }
  1541. var babylonParentBone = null;
  1542. if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) {
  1543. babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);
  1544. }
  1545. var boneIndex = skin.joints.indexOf(node.index);
  1546. babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1547. babylonBones[node.index] = babylonBone;
  1548. node._babylonBones = node._babylonBones || [];
  1549. node._babylonBones.push(babylonBone);
  1550. return babylonBone;
  1551. };
  1552. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1553. if (skin.inverseBindMatrices == undefined) {
  1554. return Promise.resolve(null);
  1555. }
  1556. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  1557. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  1558. };
  1559. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1560. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1561. var babylonBone = _a[_i];
  1562. var baseMatrix = BABYLON.Matrix.Identity();
  1563. var boneIndex = babylonBone._index;
  1564. if (inverseBindMatricesData && boneIndex !== -1) {
  1565. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  1566. baseMatrix.invertToRef(baseMatrix);
  1567. }
  1568. var babylonParentBone = babylonBone.getParent();
  1569. if (babylonParentBone) {
  1570. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1571. }
  1572. babylonBone.updateMatrix(baseMatrix, false, false);
  1573. babylonBone._updateDifferenceMatrix(undefined, false);
  1574. }
  1575. };
  1576. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1577. return node.matrix ?
  1578. BABYLON.Matrix.FromArray(node.matrix) :
  1579. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1580. };
  1581. /**
  1582. * Loads a glTF camera.
  1583. * @param context The context when loading the asset
  1584. * @param camera The glTF camera property
  1585. * @param assign A function called synchronously after parsing the glTF properties
  1586. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  1587. */
  1588. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  1589. if (assign === void 0) { assign = function () { }; }
  1590. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  1591. if (extensionPromise) {
  1592. return extensionPromise;
  1593. }
  1594. var promises = new Array();
  1595. this.logOpen(context + " " + (camera.name || ""));
  1596. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
  1597. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  1598. switch (camera.type) {
  1599. case "perspective" /* PERSPECTIVE */: {
  1600. var perspective = camera.perspective;
  1601. if (!perspective) {
  1602. throw new Error(context + ": Camera perspective properties are missing");
  1603. }
  1604. babylonCamera.fov = perspective.yfov;
  1605. babylonCamera.minZ = perspective.znear;
  1606. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  1607. break;
  1608. }
  1609. case "orthographic" /* ORTHOGRAPHIC */: {
  1610. if (!camera.orthographic) {
  1611. throw new Error(context + ": Camera orthographic properties are missing");
  1612. }
  1613. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1614. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1615. babylonCamera.orthoRight = camera.orthographic.xmag;
  1616. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1617. babylonCamera.orthoTop = camera.orthographic.ymag;
  1618. babylonCamera.minZ = camera.orthographic.znear;
  1619. babylonCamera.maxZ = camera.orthographic.zfar;
  1620. break;
  1621. }
  1622. default: {
  1623. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  1624. }
  1625. }
  1626. assign(babylonCamera);
  1627. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1628. return Promise.all(promises).then(function () {
  1629. return babylonCamera;
  1630. });
  1631. };
  1632. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1633. var animations = this.gltf.animations;
  1634. if (!animations) {
  1635. return Promise.resolve();
  1636. }
  1637. var promises = new Array();
  1638. for (var index = 0; index < animations.length; index++) {
  1639. var animation = animations[index];
  1640. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  1641. }
  1642. return Promise.all(promises).then(function () { });
  1643. };
  1644. /**
  1645. * Loads a glTF animation.
  1646. * @param context The context when loading the asset
  1647. * @param animation The glTF animation property
  1648. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  1649. */
  1650. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  1651. var promise = this._extensionsLoadAnimationAsync(context, animation);
  1652. if (promise) {
  1653. return promise;
  1654. }
  1655. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  1656. animation._babylonAnimationGroup = babylonAnimationGroup;
  1657. var promises = new Array();
  1658. ArrayItem.Assign(animation.channels);
  1659. ArrayItem.Assign(animation.samplers);
  1660. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1661. var channel = _a[_i];
  1662. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  1663. }
  1664. return Promise.all(promises).then(function () {
  1665. babylonAnimationGroup.normalize(0);
  1666. return babylonAnimationGroup;
  1667. });
  1668. };
  1669. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1670. var _this = this;
  1671. if (channel.target.node == undefined) {
  1672. return Promise.resolve();
  1673. }
  1674. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  1675. // Ignore animations that have no animation targets.
  1676. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  1677. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonTransformNode)) {
  1678. return Promise.resolve();
  1679. }
  1680. // Ignore animations targeting TRS of skinned nodes.
  1681. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1682. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  1683. return Promise.resolve();
  1684. }
  1685. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  1686. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1687. var targetPath;
  1688. var animationType;
  1689. switch (channel.target.path) {
  1690. case "translation" /* TRANSLATION */: {
  1691. targetPath = "position";
  1692. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1693. break;
  1694. }
  1695. case "rotation" /* ROTATION */: {
  1696. targetPath = "rotationQuaternion";
  1697. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1698. break;
  1699. }
  1700. case "scale" /* SCALE */: {
  1701. targetPath = "scaling";
  1702. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1703. break;
  1704. }
  1705. case "weights" /* WEIGHTS */: {
  1706. targetPath = "influence";
  1707. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1708. break;
  1709. }
  1710. default: {
  1711. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  1712. }
  1713. }
  1714. var outputBufferOffset = 0;
  1715. var getNextOutputValue;
  1716. switch (targetPath) {
  1717. case "position": {
  1718. getNextOutputValue = function () {
  1719. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1720. outputBufferOffset += 3;
  1721. return value;
  1722. };
  1723. break;
  1724. }
  1725. case "rotationQuaternion": {
  1726. getNextOutputValue = function () {
  1727. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1728. outputBufferOffset += 4;
  1729. return value;
  1730. };
  1731. break;
  1732. }
  1733. case "scaling": {
  1734. getNextOutputValue = function () {
  1735. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1736. outputBufferOffset += 3;
  1737. return value;
  1738. };
  1739. break;
  1740. }
  1741. case "influence": {
  1742. getNextOutputValue = function () {
  1743. var value = new Array(targetNode._numMorphTargets);
  1744. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1745. value[i] = data.output[outputBufferOffset++];
  1746. }
  1747. return value;
  1748. };
  1749. break;
  1750. }
  1751. }
  1752. var getNextKey;
  1753. switch (data.interpolation) {
  1754. case "STEP" /* STEP */: {
  1755. getNextKey = function (frameIndex) { return ({
  1756. frame: data.input[frameIndex],
  1757. value: getNextOutputValue(),
  1758. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1759. }); };
  1760. break;
  1761. }
  1762. case "LINEAR" /* LINEAR */: {
  1763. getNextKey = function (frameIndex) { return ({
  1764. frame: data.input[frameIndex],
  1765. value: getNextOutputValue()
  1766. }); };
  1767. break;
  1768. }
  1769. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1770. getNextKey = function (frameIndex) { return ({
  1771. frame: data.input[frameIndex],
  1772. inTangent: getNextOutputValue(),
  1773. value: getNextOutputValue(),
  1774. outTangent: getNextOutputValue()
  1775. }); };
  1776. break;
  1777. }
  1778. }
  1779. var keys = new Array(data.input.length);
  1780. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1781. keys[frameIndex] = getNextKey(frameIndex);
  1782. }
  1783. if (targetPath === "influence") {
  1784. var _loop_2 = function (targetIndex) {
  1785. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1786. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1787. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1788. frame: key.frame,
  1789. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1790. value: key.value[targetIndex],
  1791. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1792. }); }));
  1793. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1794. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1795. var babylonAnimationClone = babylonAnimation.clone();
  1796. morphTarget.animations.push(babylonAnimationClone);
  1797. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1798. });
  1799. };
  1800. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1801. _loop_2(targetIndex);
  1802. }
  1803. }
  1804. else {
  1805. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1806. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1807. babylonAnimation.setKeys(keys);
  1808. var babylonTransformNode = targetNode._babylonTransformNode;
  1809. var babylonBones = targetNode._babylonBones;
  1810. if (babylonBones) {
  1811. var babylonAnimationTargets = [babylonTransformNode].concat(babylonBones);
  1812. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  1813. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  1814. babylonAnimationTarget.animations.push(babylonAnimation);
  1815. }
  1816. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  1817. }
  1818. else {
  1819. babylonTransformNode.animations.push(babylonAnimation);
  1820. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTransformNode);
  1821. }
  1822. }
  1823. });
  1824. };
  1825. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1826. if (sampler._data) {
  1827. return sampler._data;
  1828. }
  1829. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1830. switch (interpolation) {
  1831. case "STEP" /* STEP */:
  1832. case "LINEAR" /* LINEAR */:
  1833. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1834. break;
  1835. }
  1836. default: {
  1837. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  1838. }
  1839. }
  1840. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  1841. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  1842. sampler._data = Promise.all([
  1843. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  1844. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  1845. ]).then(function (_a) {
  1846. var inputData = _a[0], outputData = _a[1];
  1847. return {
  1848. input: inputData,
  1849. interpolation: interpolation,
  1850. output: outputData,
  1851. };
  1852. });
  1853. return sampler._data;
  1854. };
  1855. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1856. if (buffer._data) {
  1857. return buffer._data;
  1858. }
  1859. if (!buffer.uri) {
  1860. throw new Error(context + "/uri: Value is missing");
  1861. }
  1862. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  1863. return buffer._data;
  1864. };
  1865. /**
  1866. * Loads a glTF buffer view.
  1867. * @param context The context when loading the asset
  1868. * @param bufferView The glTF buffer view property
  1869. * @returns A promise that resolves with the loaded data when the load is complete
  1870. */
  1871. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  1872. if (bufferView._data) {
  1873. return bufferView._data;
  1874. }
  1875. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  1876. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  1877. try {
  1878. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1879. }
  1880. catch (e) {
  1881. throw new Error(context + ": " + e.message);
  1882. }
  1883. });
  1884. return bufferView._data;
  1885. };
  1886. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  1887. if (accessor.type !== "SCALAR" /* SCALAR */) {
  1888. throw new Error(context + "/type: Invalid value " + accessor.type);
  1889. }
  1890. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  1891. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  1892. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  1893. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  1894. }
  1895. if (accessor._data) {
  1896. return accessor._data;
  1897. }
  1898. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1899. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1900. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1901. });
  1902. return accessor._data;
  1903. };
  1904. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  1905. // TODO: support normalized and stride
  1906. var _this = this;
  1907. if (accessor.componentType !== 5126 /* FLOAT */) {
  1908. throw new Error("Invalid component type " + accessor.componentType);
  1909. }
  1910. if (accessor._data) {
  1911. return accessor._data;
  1912. }
  1913. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1914. var length = numComponents * accessor.count;
  1915. if (accessor.bufferView == undefined) {
  1916. accessor._data = Promise.resolve(new Float32Array(length));
  1917. }
  1918. else {
  1919. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1920. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1921. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1922. });
  1923. }
  1924. if (accessor.sparse) {
  1925. var sparse_1 = accessor.sparse;
  1926. accessor._data = accessor._data.then(function (data) {
  1927. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  1928. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  1929. return Promise.all([
  1930. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  1931. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  1932. ]).then(function (_a) {
  1933. var indicesData = _a[0], valuesData = _a[1];
  1934. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  1935. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  1936. var valuesIndex = 0;
  1937. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1938. var dataIndex = indices[indicesIndex] * numComponents;
  1939. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1940. data[dataIndex++] = values[valuesIndex++];
  1941. }
  1942. }
  1943. return data;
  1944. });
  1945. });
  1946. }
  1947. return accessor._data;
  1948. };
  1949. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  1950. var _this = this;
  1951. if (bufferView._babylonBuffer) {
  1952. return bufferView._babylonBuffer;
  1953. }
  1954. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1955. return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
  1956. });
  1957. return bufferView._babylonBuffer;
  1958. };
  1959. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1960. var _this = this;
  1961. if (accessor._babylonVertexBuffer) {
  1962. return accessor._babylonVertexBuffer;
  1963. }
  1964. if (accessor.sparse) {
  1965. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1966. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1967. });
  1968. }
  1969. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1970. else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1971. BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1972. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1973. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1974. });
  1975. }
  1976. else {
  1977. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1978. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  1979. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1980. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1981. });
  1982. }
  1983. return accessor._babylonVertexBuffer;
  1984. };
  1985. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  1986. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  1987. throw new Error(context + ": Material type not supported");
  1988. }
  1989. var promises = new Array();
  1990. if (properties) {
  1991. if (properties.baseColorFactor) {
  1992. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1993. babylonMaterial.alpha = properties.baseColorFactor[3];
  1994. }
  1995. else {
  1996. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1997. }
  1998. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1999. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  2000. if (properties.baseColorTexture) {
  2001. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2002. babylonMaterial.albedoTexture = texture;
  2003. }));
  2004. }
  2005. if (properties.metallicRoughnessTexture) {
  2006. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  2007. babylonMaterial.metallicTexture = texture;
  2008. }));
  2009. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  2010. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  2011. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  2012. }
  2013. }
  2014. return Promise.all(promises).then(function () { });
  2015. };
  2016. /** @hidden */
  2017. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2018. if (assign === void 0) { assign = function () { }; }
  2019. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  2020. if (extensionPromise) {
  2021. return extensionPromise;
  2022. }
  2023. material._data = material._data || {};
  2024. var babylonData = material._data[babylonDrawMode];
  2025. if (!babylonData) {
  2026. this.logOpen(context + " " + (material.name || ""));
  2027. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  2028. babylonData = {
  2029. babylonMaterial: babylonMaterial,
  2030. babylonMeshes: [],
  2031. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  2032. };
  2033. material._data[babylonDrawMode] = babylonData;
  2034. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2035. this.logClose();
  2036. }
  2037. babylonData.babylonMeshes.push(babylonMesh);
  2038. babylonMesh.onDisposeObservable.addOnce(function () {
  2039. var index = babylonData.babylonMeshes.indexOf(babylonMesh);
  2040. if (index !== -1) {
  2041. babylonData.babylonMeshes.splice(index, 1);
  2042. }
  2043. });
  2044. assign(babylonData.babylonMaterial);
  2045. return babylonData.promise.then(function () {
  2046. return babylonData.babylonMaterial;
  2047. });
  2048. };
  2049. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  2050. var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
  2051. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  2052. babylonMaterial.fillMode = babylonDrawMode;
  2053. babylonMaterial.enableSpecularAntiAliasing = true;
  2054. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  2055. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  2056. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  2057. babylonMaterial.metallic = 1;
  2058. babylonMaterial.roughness = 1;
  2059. return babylonMaterial;
  2060. };
  2061. /**
  2062. * Creates a Babylon material from a glTF material.
  2063. * @param context The context when loading the asset
  2064. * @param material The glTF material property
  2065. * @param babylonDrawMode The draw mode for the Babylon material
  2066. * @returns The Babylon material
  2067. */
  2068. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  2069. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  2070. if (extensionPromise) {
  2071. return extensionPromise;
  2072. }
  2073. var name = material.name || "material" + material.index;
  2074. return this._createDefaultMaterial(name, babylonDrawMode);
  2075. };
  2076. /**
  2077. * Loads properties from a glTF material into a Babylon material.
  2078. * @param context The context when loading the asset
  2079. * @param material The glTF material property
  2080. * @param babylonMaterial The Babylon material
  2081. * @returns A promise that resolves when the load is complete
  2082. */
  2083. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2084. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  2085. if (extensionPromise) {
  2086. return extensionPromise;
  2087. }
  2088. var promises = new Array();
  2089. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2090. if (material.pbrMetallicRoughness) {
  2091. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  2092. }
  2093. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2094. return Promise.all(promises).then(function () { });
  2095. };
  2096. /**
  2097. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  2098. * @param context The context when loading the asset
  2099. * @param material The glTF material property
  2100. * @param babylonMaterial The Babylon material
  2101. * @returns A promise that resolves when the load is complete
  2102. */
  2103. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  2104. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2105. throw new Error(context + ": Material type not supported");
  2106. }
  2107. var promises = new Array();
  2108. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  2109. if (material.doubleSided) {
  2110. babylonMaterial.backFaceCulling = false;
  2111. babylonMaterial.twoSidedLighting = true;
  2112. }
  2113. if (material.normalTexture) {
  2114. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  2115. babylonMaterial.bumpTexture = texture;
  2116. }));
  2117. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  2118. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  2119. if (material.normalTexture.scale != undefined) {
  2120. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  2121. }
  2122. }
  2123. if (material.occlusionTexture) {
  2124. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  2125. babylonMaterial.ambientTexture = texture;
  2126. }));
  2127. babylonMaterial.useAmbientInGrayScale = true;
  2128. if (material.occlusionTexture.strength != undefined) {
  2129. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  2130. }
  2131. }
  2132. if (material.emissiveTexture) {
  2133. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  2134. babylonMaterial.emissiveTexture = texture;
  2135. }));
  2136. }
  2137. return Promise.all(promises).then(function () { });
  2138. };
  2139. /**
  2140. * Loads the alpha properties from a glTF material into a Babylon material.
  2141. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  2142. * @param context The context when loading the asset
  2143. * @param material The glTF material property
  2144. * @param babylonMaterial The Babylon material
  2145. */
  2146. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  2147. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2148. throw new Error(context + ": Material type not supported");
  2149. }
  2150. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  2151. switch (alphaMode) {
  2152. case "OPAQUE" /* OPAQUE */: {
  2153. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  2154. break;
  2155. }
  2156. case "MASK" /* MASK */: {
  2157. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  2158. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  2159. if (babylonMaterial.albedoTexture) {
  2160. babylonMaterial.albedoTexture.hasAlpha = true;
  2161. }
  2162. break;
  2163. }
  2164. case "BLEND" /* BLEND */: {
  2165. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  2166. if (babylonMaterial.albedoTexture) {
  2167. babylonMaterial.albedoTexture.hasAlpha = true;
  2168. babylonMaterial.useAlphaFromAlbedoTexture = true;
  2169. }
  2170. break;
  2171. }
  2172. default: {
  2173. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  2174. }
  2175. }
  2176. };
  2177. /**
  2178. * Loads a glTF texture info.
  2179. * @param context The context when loading the asset
  2180. * @param textureInfo The glTF texture info property
  2181. * @param assign A function called synchronously after parsing the glTF properties
  2182. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  2183. */
  2184. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2185. if (assign === void 0) { assign = function () { }; }
  2186. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  2187. if (extensionPromise) {
  2188. return extensionPromise;
  2189. }
  2190. this.logOpen("" + context);
  2191. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  2192. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  2193. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  2194. assign(babylonTexture);
  2195. });
  2196. this.logClose();
  2197. return promise;
  2198. };
  2199. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  2200. var _this = this;
  2201. if (assign === void 0) { assign = function () { }; }
  2202. var promises = new Array();
  2203. this.logOpen(context + " " + (texture.name || ""));
  2204. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  2205. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  2206. var deferred = new BABYLON.Deferred();
  2207. var babylonTexture = new BABYLON.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  2208. if (!_this._disposed) {
  2209. deferred.resolve();
  2210. }
  2211. }, function (message, exception) {
  2212. if (!_this._disposed) {
  2213. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  2214. }
  2215. });
  2216. promises.push(deferred.promise);
  2217. babylonTexture.name = texture.name || "texture" + texture.index;
  2218. babylonTexture.wrapU = samplerData.wrapU;
  2219. babylonTexture.wrapV = samplerData.wrapV;
  2220. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  2221. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  2222. var name = image.uri || _this._fileName + "#image" + image.index;
  2223. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  2224. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  2225. }));
  2226. assign(babylonTexture);
  2227. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  2228. this.logClose();
  2229. return Promise.all(promises).then(function () {
  2230. return babylonTexture;
  2231. });
  2232. };
  2233. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  2234. if (!sampler._data) {
  2235. sampler._data = {
  2236. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  2237. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  2238. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  2239. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  2240. };
  2241. }
  2242. return sampler._data;
  2243. };
  2244. /**
  2245. * Loads a glTF image.
  2246. * @param context The context when loading the asset
  2247. * @param image The glTF image property
  2248. * @returns A promise that resolves with the loaded data when the load is complete
  2249. */
  2250. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  2251. if (!image._data) {
  2252. this.logOpen(context + " " + (image.name || ""));
  2253. if (image.uri) {
  2254. image._data = this.loadUriAsync(context + "/uri", image.uri);
  2255. }
  2256. else {
  2257. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  2258. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  2259. }
  2260. this.logClose();
  2261. }
  2262. return image._data;
  2263. };
  2264. /**
  2265. * Loads a glTF uri.
  2266. * @param context The context when loading the asset
  2267. * @param uri The base64 or relative uri
  2268. * @returns A promise that resolves with the loaded data when the load is complete
  2269. */
  2270. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  2271. var _this = this;
  2272. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  2273. if (extensionPromise) {
  2274. return extensionPromise;
  2275. }
  2276. if (!GLTFLoader._ValidateUri(uri)) {
  2277. throw new Error(context + ": '" + uri + "' is invalid");
  2278. }
  2279. if (BABYLON.Tools.IsBase64(uri)) {
  2280. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  2281. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  2282. return Promise.resolve(data);
  2283. }
  2284. this.log("Loading " + uri);
  2285. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  2286. return new Promise(function (resolve, reject) {
  2287. if (!_this._disposed) {
  2288. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  2289. if (!_this._disposed) {
  2290. var data = new Uint8Array(fileData);
  2291. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  2292. resolve(data);
  2293. }
  2294. }, function (event) {
  2295. if (!_this._disposed) {
  2296. if (request_1) {
  2297. request_1._lengthComputable = event.lengthComputable;
  2298. request_1._loaded = event.loaded;
  2299. request_1._total = event.total;
  2300. }
  2301. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  2302. try {
  2303. _this._onProgress();
  2304. }
  2305. catch (e) {
  2306. reject(e);
  2307. }
  2308. }
  2309. }
  2310. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  2311. if (!_this._disposed) {
  2312. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2313. }
  2314. });
  2315. _this._requests.push(request_1);
  2316. }
  2317. });
  2318. });
  2319. };
  2320. GLTFLoader.prototype._onProgress = function () {
  2321. if (!this._progressCallback) {
  2322. return;
  2323. }
  2324. var lengthComputable = true;
  2325. var loaded = 0;
  2326. var total = 0;
  2327. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2328. var request = _a[_i];
  2329. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2330. return;
  2331. }
  2332. lengthComputable = lengthComputable && request._lengthComputable;
  2333. loaded += request._loaded;
  2334. total += request._total;
  2335. }
  2336. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2337. };
  2338. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  2339. // Set defaults if undefined
  2340. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2341. switch (mode) {
  2342. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2343. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2344. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2345. default:
  2346. BABYLON.Tools.Warn(context + ": Invalid value (" + mode + ")");
  2347. return BABYLON.Texture.WRAP_ADDRESSMODE;
  2348. }
  2349. };
  2350. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  2351. // Set defaults if undefined
  2352. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  2353. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  2354. if (magFilter === 9729 /* LINEAR */) {
  2355. switch (minFilter) {
  2356. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  2357. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  2358. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  2359. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  2360. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  2361. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2362. default:
  2363. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2364. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2365. }
  2366. }
  2367. else {
  2368. if (magFilter !== 9728 /* NEAREST */) {
  2369. BABYLON.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  2370. }
  2371. switch (minFilter) {
  2372. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  2373. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  2374. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2375. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  2376. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  2377. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  2378. default:
  2379. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2380. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2381. }
  2382. }
  2383. };
  2384. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2385. var buffer = bufferView.buffer;
  2386. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2387. try {
  2388. switch (componentType) {
  2389. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2390. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2391. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2392. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2393. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2394. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2395. default: throw new Error("Invalid component type " + componentType);
  2396. }
  2397. }
  2398. catch (e) {
  2399. throw new Error(context + ": " + e);
  2400. }
  2401. };
  2402. GLTFLoader._GetNumComponents = function (context, type) {
  2403. switch (type) {
  2404. case "SCALAR": return 1;
  2405. case "VEC2": return 2;
  2406. case "VEC3": return 3;
  2407. case "VEC4": return 4;
  2408. case "MAT2": return 4;
  2409. case "MAT3": return 9;
  2410. case "MAT4": return 16;
  2411. }
  2412. throw new Error(context + ": Invalid type (" + type + ")");
  2413. };
  2414. GLTFLoader._ValidateUri = function (uri) {
  2415. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2416. };
  2417. GLTFLoader._GetDrawMode = function (context, mode) {
  2418. if (mode == undefined) {
  2419. mode = 4 /* TRIANGLES */;
  2420. }
  2421. switch (mode) {
  2422. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  2423. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  2424. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  2425. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  2426. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  2427. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  2428. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  2429. }
  2430. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2431. };
  2432. GLTFLoader.prototype._compileMaterialsAsync = function () {
  2433. var _this = this;
  2434. this._parent._startPerformanceCounter("Compile materials");
  2435. var promises = new Array();
  2436. if (this.gltf.materials) {
  2437. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  2438. var material = _a[_i];
  2439. if (material._data) {
  2440. for (var babylonDrawMode in material._data) {
  2441. var babylonData = material._data[babylonDrawMode];
  2442. for (var _b = 0, _c = babylonData.babylonMeshes; _b < _c.length; _b++) {
  2443. var babylonMesh = _c[_b];
  2444. // Ensure nonUniformScaling is set if necessary.
  2445. babylonMesh.computeWorldMatrix(true);
  2446. var babylonMaterial = babylonData.babylonMaterial;
  2447. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2448. if (this._parent.useClipPlane) {
  2449. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2450. }
  2451. }
  2452. }
  2453. }
  2454. }
  2455. }
  2456. return Promise.all(promises).then(function () {
  2457. _this._parent._endPerformanceCounter("Compile materials");
  2458. });
  2459. };
  2460. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  2461. var _this = this;
  2462. this._parent._startPerformanceCounter("Compile shadow generators");
  2463. var promises = new Array();
  2464. var lights = this.babylonScene.lights;
  2465. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2466. var light = lights_1[_i];
  2467. var generator = light.getShadowGenerator();
  2468. if (generator) {
  2469. promises.push(generator.forceCompilationAsync());
  2470. }
  2471. }
  2472. return Promise.all(promises).then(function () {
  2473. _this._parent._endPerformanceCounter("Compile shadow generators");
  2474. });
  2475. };
  2476. GLTFLoader.prototype._forEachExtensions = function (action) {
  2477. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2478. var name_4 = _a[_i];
  2479. var extension = this._extensions[name_4];
  2480. if (extension.enabled) {
  2481. action(extension);
  2482. }
  2483. }
  2484. };
  2485. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  2486. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2487. var name_5 = _a[_i];
  2488. var extension = this._extensions[name_5];
  2489. if (extension.enabled) {
  2490. var loaderProperty = property;
  2491. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  2492. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  2493. if (!activeLoaderExtensions[name_5]) {
  2494. activeLoaderExtensions[name_5] = true;
  2495. try {
  2496. var result = actionAsync(extension);
  2497. if (result) {
  2498. return result;
  2499. }
  2500. }
  2501. finally {
  2502. delete activeLoaderExtensions[name_5];
  2503. }
  2504. }
  2505. }
  2506. }
  2507. return null;
  2508. };
  2509. GLTFLoader.prototype._extensionsOnLoading = function () {
  2510. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  2511. };
  2512. GLTFLoader.prototype._extensionsOnReady = function () {
  2513. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  2514. };
  2515. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  2516. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  2517. };
  2518. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  2519. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  2520. };
  2521. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  2522. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  2523. };
  2524. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  2525. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2526. };
  2527. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2528. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2529. };
  2530. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  2531. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  2532. };
  2533. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2534. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2535. };
  2536. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  2537. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  2538. };
  2539. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  2540. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  2541. };
  2542. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  2543. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  2544. };
  2545. /**
  2546. * Helper method called by a loader extension to load an glTF extension.
  2547. * @param context The context when loading the asset
  2548. * @param property The glTF property to load the extension from
  2549. * @param extensionName The name of the extension to load
  2550. * @param actionAsync The action to run
  2551. * @returns The promise returned by actionAsync or null if the extension does not exist
  2552. */
  2553. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  2554. if (!property.extensions) {
  2555. return null;
  2556. }
  2557. var extensions = property.extensions;
  2558. var extension = extensions[extensionName];
  2559. if (!extension) {
  2560. return null;
  2561. }
  2562. return actionAsync(context + "/extensions/" + extensionName, extension);
  2563. };
  2564. /**
  2565. * Helper method called by a loader extension to load a glTF extra.
  2566. * @param context The context when loading the asset
  2567. * @param property The glTF property to load the extra from
  2568. * @param extensionName The name of the extension to load
  2569. * @param actionAsync The action to run
  2570. * @returns The promise returned by actionAsync or null if the extra does not exist
  2571. */
  2572. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  2573. if (!property.extras) {
  2574. return null;
  2575. }
  2576. var extras = property.extras;
  2577. var extra = extras[extensionName];
  2578. if (!extra) {
  2579. return null;
  2580. }
  2581. return actionAsync(context + "/extras/" + extensionName, extra);
  2582. };
  2583. /**
  2584. * Increments the indentation level and logs a message.
  2585. * @param message The message to log
  2586. */
  2587. GLTFLoader.prototype.logOpen = function (message) {
  2588. this._parent._logOpen(message);
  2589. };
  2590. /**
  2591. * Decrements the indentation level.
  2592. */
  2593. GLTFLoader.prototype.logClose = function () {
  2594. this._parent._logClose();
  2595. };
  2596. /**
  2597. * Logs a message
  2598. * @param message The message to log
  2599. */
  2600. GLTFLoader.prototype.log = function (message) {
  2601. this._parent._log(message);
  2602. };
  2603. /**
  2604. * Starts a performance counter.
  2605. * @param counterName The name of the performance counter
  2606. */
  2607. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  2608. this._parent._startPerformanceCounter(counterName);
  2609. };
  2610. /**
  2611. * Ends a performance counter.
  2612. * @param counterName The name of the performance counter
  2613. */
  2614. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  2615. this._parent._endPerformanceCounter(counterName);
  2616. };
  2617. GLTFLoader._DefaultSampler = { index: -1 };
  2618. GLTFLoader._ExtensionNames = new Array();
  2619. GLTFLoader._ExtensionFactories = {};
  2620. return GLTFLoader;
  2621. }());
  2622. GLTF2.GLTFLoader = GLTFLoader;
  2623. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  2624. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2625. })(BABYLON || (BABYLON = {}));
  2626. //# sourceMappingURL=babylon.glTFLoader.js.map
  2627. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2628. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2629. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2630. var BABYLON;
  2631. (function (BABYLON) {
  2632. var GLTF2;
  2633. (function (GLTF2) {
  2634. var Loader;
  2635. (function (Loader) {
  2636. var Extensions;
  2637. (function (Extensions) {
  2638. var NAME = "MSFT_lod";
  2639. /**
  2640. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  2641. */
  2642. var MSFT_lod = /** @class */ (function () {
  2643. /** @hidden */
  2644. function MSFT_lod(loader) {
  2645. /** The name of this extension. */
  2646. this.name = NAME;
  2647. /** Defines whether this extension is enabled. */
  2648. this.enabled = true;
  2649. /**
  2650. * Maximum number of LODs to load, starting from the lowest LOD.
  2651. */
  2652. this.maxLODsToLoad = Number.MAX_VALUE;
  2653. /**
  2654. * Observable raised when all node LODs of one level are loaded.
  2655. * The event data is the index of the loaded LOD starting from zero.
  2656. * Dispose the loader to cancel the loading of the next level of LODs.
  2657. */
  2658. this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  2659. /**
  2660. * Observable raised when all material LODs of one level are loaded.
  2661. * The event data is the index of the loaded LOD starting from zero.
  2662. * Dispose the loader to cancel the loading of the next level of LODs.
  2663. */
  2664. this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  2665. this._nodeIndexLOD = null;
  2666. this._nodeSignalLODs = new Array();
  2667. this._nodePromiseLODs = new Array();
  2668. this._materialIndexLOD = null;
  2669. this._materialSignalLODs = new Array();
  2670. this._materialPromiseLODs = new Array();
  2671. this._loader = loader;
  2672. }
  2673. /** @hidden */
  2674. MSFT_lod.prototype.dispose = function () {
  2675. delete this._loader;
  2676. this._nodeIndexLOD = null;
  2677. this._nodeSignalLODs.length = 0;
  2678. this._nodePromiseLODs.length = 0;
  2679. this._materialIndexLOD = null;
  2680. this._materialSignalLODs.length = 0;
  2681. this._materialPromiseLODs.length = 0;
  2682. this.onMaterialLODsLoadedObservable.clear();
  2683. this.onNodeLODsLoadedObservable.clear();
  2684. };
  2685. /** @hidden */
  2686. MSFT_lod.prototype.onReady = function () {
  2687. var _this = this;
  2688. var _loop_1 = function (indexLOD) {
  2689. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  2690. if (indexLOD !== 0) {
  2691. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  2692. }
  2693. _this._loader.log("Loaded node LOD " + indexLOD);
  2694. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  2695. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  2696. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  2697. if (_this._nodeSignalLODs[indexLOD]) {
  2698. _this._nodeSignalLODs[indexLOD].resolve();
  2699. }
  2700. }
  2701. });
  2702. this_1._loader._completePromises.push(promise);
  2703. };
  2704. var this_1 = this;
  2705. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  2706. _loop_1(indexLOD);
  2707. }
  2708. var _loop_2 = function (indexLOD) {
  2709. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  2710. if (indexLOD !== 0) {
  2711. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  2712. }
  2713. _this._loader.log("Loaded material LOD " + indexLOD);
  2714. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  2715. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  2716. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  2717. if (_this._materialSignalLODs[indexLOD]) {
  2718. _this._materialSignalLODs[indexLOD].resolve();
  2719. }
  2720. }
  2721. });
  2722. this_2._loader._completePromises.push(promise);
  2723. };
  2724. var this_2 = this;
  2725. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  2726. _loop_2(indexLOD);
  2727. }
  2728. };
  2729. /** @hidden */
  2730. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  2731. var _this = this;
  2732. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  2733. var firstPromise;
  2734. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  2735. _this._loader.logOpen("" + extensionContext);
  2736. var _loop_3 = function (indexLOD) {
  2737. var nodeLOD = nodeLODs[indexLOD];
  2738. if (indexLOD !== 0) {
  2739. _this._nodeIndexLOD = indexLOD;
  2740. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  2741. }
  2742. var assign_1 = function (babylonTransformNode) { babylonTransformNode.setEnabled(false); };
  2743. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD, assign_1).then(function (babylonMesh) {
  2744. if (indexLOD !== 0) {
  2745. // TODO: should not rely on _babylonMesh
  2746. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2747. if (previousNodeLOD._babylonTransformNode) {
  2748. previousNodeLOD._babylonTransformNode.dispose();
  2749. delete previousNodeLOD._babylonTransformNode;
  2750. _this._disposeUnusedMaterials();
  2751. }
  2752. }
  2753. babylonMesh.setEnabled(true);
  2754. return babylonMesh;
  2755. });
  2756. if (indexLOD === 0) {
  2757. firstPromise = promise;
  2758. }
  2759. else {
  2760. _this._nodeIndexLOD = null;
  2761. }
  2762. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  2763. _this._nodePromiseLODs[indexLOD].push(promise);
  2764. };
  2765. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2766. _loop_3(indexLOD);
  2767. }
  2768. _this._loader.logClose();
  2769. return firstPromise;
  2770. });
  2771. };
  2772. /** @hidden */
  2773. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2774. var _this = this;
  2775. // Don't load material LODs if already loading a node LOD.
  2776. if (this._nodeIndexLOD) {
  2777. return null;
  2778. }
  2779. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  2780. var firstPromise;
  2781. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  2782. _this._loader.logOpen("" + extensionContext);
  2783. var _loop_4 = function (indexLOD) {
  2784. var materialLOD = materialLODs[indexLOD];
  2785. if (indexLOD !== 0) {
  2786. _this._materialIndexLOD = indexLOD;
  2787. }
  2788. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  2789. if (indexLOD === 0) {
  2790. assign(babylonMaterial);
  2791. }
  2792. }).then(function (babylonMaterial) {
  2793. if (indexLOD !== 0) {
  2794. assign(babylonMaterial);
  2795. // TODO: should not rely on _data
  2796. var previousDataLOD = materialLODs[indexLOD - 1]._data;
  2797. if (previousDataLOD[babylonDrawMode]) {
  2798. previousDataLOD[babylonDrawMode].babylonMaterial.dispose();
  2799. delete previousDataLOD[babylonDrawMode];
  2800. }
  2801. }
  2802. return babylonMaterial;
  2803. });
  2804. if (indexLOD === 0) {
  2805. firstPromise = promise;
  2806. }
  2807. else {
  2808. _this._materialIndexLOD = null;
  2809. }
  2810. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  2811. _this._materialPromiseLODs[indexLOD].push(promise);
  2812. };
  2813. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2814. _loop_4(indexLOD);
  2815. }
  2816. _this._loader.logClose();
  2817. return firstPromise;
  2818. });
  2819. };
  2820. /** @hidden */
  2821. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2822. var _this = this;
  2823. // Defer the loading of uris if loading a material or node LOD.
  2824. if (this._materialIndexLOD !== null) {
  2825. this._loader.log("deferred");
  2826. var previousIndexLOD = this._materialIndexLOD - 1;
  2827. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2828. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  2829. return _this._loader.loadUriAsync(context, uri);
  2830. });
  2831. }
  2832. else if (this._nodeIndexLOD !== null) {
  2833. this._loader.log("deferred");
  2834. var previousIndexLOD = this._nodeIndexLOD - 1;
  2835. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2836. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  2837. return _this._loader.loadUriAsync(context, uri);
  2838. });
  2839. }
  2840. return null;
  2841. };
  2842. /**
  2843. * Gets an array of LOD properties from lowest to highest.
  2844. */
  2845. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2846. if (this.maxLODsToLoad <= 0) {
  2847. throw new Error("maxLODsToLoad must be greater than zero");
  2848. }
  2849. var properties = new Array();
  2850. for (var i = ids.length - 1; i >= 0; i--) {
  2851. properties.push(GLTF2.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  2852. if (properties.length === this.maxLODsToLoad) {
  2853. return properties;
  2854. }
  2855. }
  2856. properties.push(property);
  2857. return properties;
  2858. };
  2859. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  2860. // TODO: should not rely on _data
  2861. var materials = this._loader.gltf.materials;
  2862. if (materials) {
  2863. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  2864. var material = materials_1[_i];
  2865. if (material._data) {
  2866. for (var drawMode in material._data) {
  2867. var data = material._data[drawMode];
  2868. if (data.babylonMeshes.length === 0) {
  2869. data.babylonMaterial.dispose(false, true);
  2870. delete material._data[drawMode];
  2871. }
  2872. }
  2873. }
  2874. }
  2875. }
  2876. };
  2877. return MSFT_lod;
  2878. }());
  2879. Extensions.MSFT_lod = MSFT_lod;
  2880. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  2881. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2882. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2883. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2884. })(BABYLON || (BABYLON = {}));
  2885. //# sourceMappingURL=MSFT_lod.js.map
  2886. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2887. var BABYLON;
  2888. (function (BABYLON) {
  2889. var GLTF2;
  2890. (function (GLTF2) {
  2891. var Loader;
  2892. (function (Loader) {
  2893. var Extensions;
  2894. (function (Extensions) {
  2895. var NAME = "MSFT_minecraftMesh";
  2896. /** @hidden */
  2897. var MSFT_minecraftMesh = /** @class */ (function () {
  2898. function MSFT_minecraftMesh(loader) {
  2899. this.name = NAME;
  2900. this.enabled = true;
  2901. this._loader = loader;
  2902. }
  2903. MSFT_minecraftMesh.prototype.dispose = function () {
  2904. delete this._loader;
  2905. };
  2906. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2907. var _this = this;
  2908. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  2909. if (extra) {
  2910. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2911. throw new Error(extraContext + ": Material type not supported");
  2912. }
  2913. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2914. if (babylonMaterial.needAlphaBlending()) {
  2915. babylonMaterial.forceDepthWrite = true;
  2916. babylonMaterial.separateCullingPass = true;
  2917. }
  2918. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  2919. babylonMaterial.twoSidedLighting = true;
  2920. return promise;
  2921. }
  2922. return null;
  2923. });
  2924. };
  2925. return MSFT_minecraftMesh;
  2926. }());
  2927. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  2928. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  2929. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2930. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2931. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2932. })(BABYLON || (BABYLON = {}));
  2933. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  2934. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2935. var BABYLON;
  2936. (function (BABYLON) {
  2937. var GLTF2;
  2938. (function (GLTF2) {
  2939. var Loader;
  2940. (function (Loader) {
  2941. var Extensions;
  2942. (function (Extensions) {
  2943. var NAME = "MSFT_sRGBFactors";
  2944. /** @hidden */
  2945. var MSFT_sRGBFactors = /** @class */ (function () {
  2946. function MSFT_sRGBFactors(loader) {
  2947. this.name = NAME;
  2948. this.enabled = true;
  2949. this._loader = loader;
  2950. }
  2951. MSFT_sRGBFactors.prototype.dispose = function () {
  2952. delete this._loader;
  2953. };
  2954. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2955. var _this = this;
  2956. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  2957. if (extra) {
  2958. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2959. throw new Error(extraContext + ": Material type not supported");
  2960. }
  2961. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2962. if (!babylonMaterial.albedoTexture) {
  2963. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  2964. }
  2965. if (!babylonMaterial.reflectivityTexture) {
  2966. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  2967. }
  2968. return promise;
  2969. }
  2970. return null;
  2971. });
  2972. };
  2973. return MSFT_sRGBFactors;
  2974. }());
  2975. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  2976. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  2977. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  2978. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  2979. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2980. })(BABYLON || (BABYLON = {}));
  2981. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  2982. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2983. var BABYLON;
  2984. (function (BABYLON) {
  2985. var GLTF2;
  2986. (function (GLTF2) {
  2987. var Loader;
  2988. (function (Loader) {
  2989. var Extensions;
  2990. (function (Extensions) {
  2991. var NAME = "MSFT_audio_emitter";
  2992. /**
  2993. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  2994. */
  2995. var MSFT_audio_emitter = /** @class */ (function () {
  2996. /** @hidden */
  2997. function MSFT_audio_emitter(loader) {
  2998. /** The name of this extension. */
  2999. this.name = NAME;
  3000. /** Defines whether this extension is enabled. */
  3001. this.enabled = true;
  3002. this._loader = loader;
  3003. }
  3004. /** @hidden */
  3005. MSFT_audio_emitter.prototype.dispose = function () {
  3006. delete this._loader;
  3007. delete this._clips;
  3008. delete this._emitters;
  3009. };
  3010. /** @hidden */
  3011. MSFT_audio_emitter.prototype.onLoading = function () {
  3012. var extensions = this._loader.gltf.extensions;
  3013. if (extensions && extensions[this.name]) {
  3014. var extension = extensions[this.name];
  3015. this._clips = extension.clips;
  3016. this._emitters = extension.emitters;
  3017. GLTF2.ArrayItem.Assign(this._clips);
  3018. GLTF2.ArrayItem.Assign(this._emitters);
  3019. }
  3020. };
  3021. /** @hidden */
  3022. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  3023. var _this = this;
  3024. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3025. var promises = new Array();
  3026. promises.push(_this._loader.loadSceneAsync(context, scene));
  3027. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3028. var emitterIndex = _a[_i];
  3029. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3030. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  3031. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3032. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  3033. }
  3034. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  3035. }
  3036. return Promise.all(promises).then(function () { });
  3037. });
  3038. };
  3039. /** @hidden */
  3040. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  3041. var _this = this;
  3042. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3043. var promises = new Array();
  3044. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  3045. var _loop_1 = function (emitterIndex) {
  3046. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3047. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  3048. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  3049. var sound = _a[_i];
  3050. sound.attachToMesh(babylonMesh);
  3051. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3052. sound.setLocalDirectionToMesh(BABYLON.Vector3.Forward());
  3053. sound.setDirectionalCone(2 * BABYLON.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  3054. }
  3055. }
  3056. }));
  3057. };
  3058. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3059. var emitterIndex = _a[_i];
  3060. _loop_1(emitterIndex);
  3061. }
  3062. assign(babylonMesh);
  3063. }).then(function (babylonMesh) {
  3064. return Promise.all(promises).then(function () {
  3065. return babylonMesh;
  3066. });
  3067. });
  3068. });
  3069. };
  3070. /** @hidden */
  3071. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  3072. var _this = this;
  3073. return GLTF2.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  3074. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  3075. var promises = new Array();
  3076. GLTF2.ArrayItem.Assign(extension.events);
  3077. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  3078. var event_1 = _a[_i];
  3079. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  3080. }
  3081. return Promise.all(promises).then(function () {
  3082. return babylonAnimationGroup;
  3083. });
  3084. });
  3085. });
  3086. };
  3087. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  3088. if (clip._objectURL) {
  3089. return clip._objectURL;
  3090. }
  3091. var promise;
  3092. if (clip.uri) {
  3093. promise = this._loader.loadUriAsync(context, clip.uri);
  3094. }
  3095. else {
  3096. var bufferView = GLTF2.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  3097. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  3098. }
  3099. clip._objectURL = promise.then(function (data) {
  3100. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  3101. });
  3102. return clip._objectURL;
  3103. };
  3104. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  3105. var _this = this;
  3106. emitter._babylonSounds = emitter._babylonSounds || [];
  3107. if (!emitter._babylonData) {
  3108. var clipPromises = new Array();
  3109. var name_1 = emitter.name || "emitter" + emitter.index;
  3110. var options_1 = {
  3111. loop: false,
  3112. autoplay: false,
  3113. volume: emitter.volume == undefined ? 1 : emitter.volume,
  3114. };
  3115. var _loop_2 = function (i) {
  3116. var clipContext = "#/extensions/" + this_1.name + "/clips";
  3117. var clip = GLTF2.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  3118. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  3119. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  3120. sound.refDistance = emitter.refDistance || 1;
  3121. sound.maxDistance = emitter.maxDistance || 256;
  3122. sound.rolloffFactor = emitter.rolloffFactor || 1;
  3123. sound.distanceModel = emitter.distanceModel || 'exponential';
  3124. sound._positionInEmitterSpace = true;
  3125. }));
  3126. };
  3127. var this_1 = this;
  3128. for (var i = 0; i < emitter.clips.length; i++) {
  3129. _loop_2(i);
  3130. }
  3131. var promise = Promise.all(clipPromises).then(function () {
  3132. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  3133. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  3134. if (emitter.innerAngle) {
  3135. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  3136. }
  3137. if (emitter.outerAngle) {
  3138. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  3139. }
  3140. if (emitter.volume) {
  3141. weightedSound.volume = emitter.volume;
  3142. }
  3143. emitter._babylonData.sound = weightedSound;
  3144. });
  3145. emitter._babylonData = {
  3146. loaded: promise
  3147. };
  3148. }
  3149. return emitter._babylonData.loaded;
  3150. };
  3151. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  3152. switch (action) {
  3153. case "play" /* play */: {
  3154. return function (currentFrame) {
  3155. var frameOffset = (startOffset || 0) + (currentFrame - time);
  3156. sound.play(frameOffset);
  3157. };
  3158. }
  3159. case "stop" /* stop */: {
  3160. return function (currentFrame) {
  3161. sound.stop();
  3162. };
  3163. }
  3164. case "pause" /* pause */: {
  3165. return function (currentFrame) {
  3166. sound.pause();
  3167. };
  3168. }
  3169. default: {
  3170. throw new Error(context + ": Unsupported action " + action);
  3171. }
  3172. }
  3173. };
  3174. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  3175. var _this = this;
  3176. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  3177. return Promise.resolve();
  3178. }
  3179. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  3180. var emitterIndex = event.emitter;
  3181. var emitter = GLTF2.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  3182. return this._loadEmitterAsync(context, emitter).then(function () {
  3183. var sound = emitter._babylonData.sound;
  3184. if (sound) {
  3185. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  3186. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  3187. // Make sure all started audio stops when this animation is terminated.
  3188. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  3189. sound.stop();
  3190. });
  3191. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  3192. sound.pause();
  3193. });
  3194. }
  3195. });
  3196. };
  3197. return MSFT_audio_emitter;
  3198. }());
  3199. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  3200. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  3201. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3202. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3203. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3204. })(BABYLON || (BABYLON = {}));
  3205. //# sourceMappingURL=MSFT_audio_emitter.js.map
  3206. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3207. var BABYLON;
  3208. (function (BABYLON) {
  3209. var GLTF2;
  3210. (function (GLTF2) {
  3211. var Loader;
  3212. (function (Loader) {
  3213. var Extensions;
  3214. (function (Extensions) {
  3215. var NAME = "KHR_draco_mesh_compression";
  3216. /**
  3217. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3218. */
  3219. var KHR_draco_mesh_compression = /** @class */ (function () {
  3220. /** @hidden */
  3221. function KHR_draco_mesh_compression(loader) {
  3222. /** The name of this extension. */
  3223. this.name = NAME;
  3224. /** Defines whether this extension is enabled. */
  3225. this.enabled = BABYLON.DracoCompression.DecoderAvailable;
  3226. this._loader = loader;
  3227. }
  3228. /** @hidden */
  3229. KHR_draco_mesh_compression.prototype.dispose = function () {
  3230. if (this._dracoCompression) {
  3231. this._dracoCompression.dispose();
  3232. delete this._dracoCompression;
  3233. }
  3234. delete this._loader;
  3235. };
  3236. /** @hidden */
  3237. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3238. var _this = this;
  3239. return GLTF2.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  3240. if (primitive.mode != undefined) {
  3241. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3242. primitive.mode !== 4 /* TRIANGLES */) {
  3243. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3244. }
  3245. // TODO: handle triangle strips
  3246. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3247. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3248. }
  3249. }
  3250. var attributes = {};
  3251. var loadAttribute = function (name, kind) {
  3252. var uniqueId = extension.attributes[name];
  3253. if (uniqueId == undefined) {
  3254. return;
  3255. }
  3256. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3257. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3258. babylonMesh._delayInfo.push(kind);
  3259. }
  3260. attributes[kind] = uniqueId;
  3261. };
  3262. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3263. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3264. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3265. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3266. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3267. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3268. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3269. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3270. var bufferView = GLTF2.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  3271. if (!bufferView._dracoBabylonGeometry) {
  3272. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  3273. if (!_this._dracoCompression) {
  3274. _this._dracoCompression = new BABYLON.DracoCompression();
  3275. }
  3276. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3277. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader.babylonScene);
  3278. babylonVertexData.applyToGeometry(babylonGeometry);
  3279. return babylonGeometry;
  3280. }).catch(function (error) {
  3281. throw new Error(context + ": " + error.message);
  3282. });
  3283. });
  3284. }
  3285. return bufferView._dracoBabylonGeometry;
  3286. });
  3287. };
  3288. return KHR_draco_mesh_compression;
  3289. }());
  3290. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3291. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3292. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3293. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3294. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3295. })(BABYLON || (BABYLON = {}));
  3296. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  3297. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3298. var BABYLON;
  3299. (function (BABYLON) {
  3300. var GLTF2;
  3301. (function (GLTF2) {
  3302. var Loader;
  3303. (function (Loader) {
  3304. var Extensions;
  3305. (function (Extensions) {
  3306. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3307. /**
  3308. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3309. */
  3310. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  3311. /** @hidden */
  3312. function KHR_materials_pbrSpecularGlossiness(loader) {
  3313. /** The name of this extension. */
  3314. this.name = NAME;
  3315. /** Defines whether this extension is enabled. */
  3316. this.enabled = true;
  3317. this._loader = loader;
  3318. }
  3319. /** @hidden */
  3320. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  3321. delete this._loader;
  3322. };
  3323. /** @hidden */
  3324. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3325. var _this = this;
  3326. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  3327. var promises = new Array();
  3328. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3329. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  3330. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3331. return Promise.all(promises).then(function () { });
  3332. });
  3333. };
  3334. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  3335. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3336. throw new Error(context + ": Material type not supported");
  3337. }
  3338. var promises = new Array();
  3339. babylonMaterial.metallic = null;
  3340. babylonMaterial.roughness = null;
  3341. if (properties.diffuseFactor) {
  3342. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  3343. babylonMaterial.alpha = properties.diffuseFactor[3];
  3344. }
  3345. else {
  3346. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3347. }
  3348. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  3349. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  3350. if (properties.diffuseTexture) {
  3351. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  3352. babylonMaterial.albedoTexture = texture;
  3353. return Promise.resolve();
  3354. }));
  3355. }
  3356. if (properties.specularGlossinessTexture) {
  3357. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  3358. babylonMaterial.reflectivityTexture = texture;
  3359. return Promise.resolve();
  3360. }));
  3361. babylonMaterial.reflectivityTexture.hasAlpha = true;
  3362. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3363. }
  3364. return Promise.all(promises).then(function () { });
  3365. };
  3366. return KHR_materials_pbrSpecularGlossiness;
  3367. }());
  3368. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  3369. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  3370. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3371. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3372. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3373. })(BABYLON || (BABYLON = {}));
  3374. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  3375. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3376. var BABYLON;
  3377. (function (BABYLON) {
  3378. var GLTF2;
  3379. (function (GLTF2) {
  3380. var Loader;
  3381. (function (Loader) {
  3382. var Extensions;
  3383. (function (Extensions) {
  3384. var NAME = "KHR_materials_unlit";
  3385. /**
  3386. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  3387. */
  3388. var KHR_materials_unlit = /** @class */ (function () {
  3389. /** @hidden */
  3390. function KHR_materials_unlit(loader) {
  3391. /** The name of this extension. */
  3392. this.name = NAME;
  3393. /** Defines whether this extension is enabled. */
  3394. this.enabled = true;
  3395. this._loader = loader;
  3396. }
  3397. /** @hidden */
  3398. KHR_materials_unlit.prototype.dispose = function () {
  3399. delete this._loader;
  3400. };
  3401. /** @hidden */
  3402. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3403. var _this = this;
  3404. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  3405. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  3406. });
  3407. };
  3408. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  3409. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3410. throw new Error(context + ": Material type not supported");
  3411. }
  3412. var promises = new Array();
  3413. babylonMaterial.unlit = true;
  3414. var properties = material.pbrMetallicRoughness;
  3415. if (properties) {
  3416. if (properties.baseColorFactor) {
  3417. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3418. babylonMaterial.alpha = properties.baseColorFactor[3];
  3419. }
  3420. else {
  3421. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3422. }
  3423. if (properties.baseColorTexture) {
  3424. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3425. babylonMaterial.albedoTexture = texture;
  3426. return Promise.resolve();
  3427. }));
  3428. }
  3429. }
  3430. if (material.doubleSided) {
  3431. babylonMaterial.backFaceCulling = false;
  3432. babylonMaterial.twoSidedLighting = true;
  3433. }
  3434. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3435. return Promise.all(promises).then(function () { });
  3436. };
  3437. return KHR_materials_unlit;
  3438. }());
  3439. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  3440. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  3441. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3442. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3443. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3444. })(BABYLON || (BABYLON = {}));
  3445. //# sourceMappingURL=KHR_materials_unlit.js.map
  3446. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3447. var BABYLON;
  3448. (function (BABYLON) {
  3449. var GLTF2;
  3450. (function (GLTF2) {
  3451. var Loader;
  3452. (function (Loader) {
  3453. var Extensions;
  3454. (function (Extensions) {
  3455. var NAME = "KHR_lights_punctual";
  3456. var LightType;
  3457. (function (LightType) {
  3458. LightType["DIRECTIONAL"] = "directional";
  3459. LightType["POINT"] = "point";
  3460. LightType["SPOT"] = "spot";
  3461. })(LightType || (LightType = {}));
  3462. /**
  3463. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  3464. */
  3465. var KHR_lights = /** @class */ (function () {
  3466. /** @hidden */
  3467. function KHR_lights(loader) {
  3468. /** The name of this extension. */
  3469. this.name = NAME;
  3470. /** Defines whether this extension is enabled. */
  3471. this.enabled = true;
  3472. this._loader = loader;
  3473. }
  3474. /** @hidden */
  3475. KHR_lights.prototype.dispose = function () {
  3476. delete this._loader;
  3477. delete this._lights;
  3478. };
  3479. /** @hidden */
  3480. KHR_lights.prototype.onLoading = function () {
  3481. var extensions = this._loader.gltf.extensions;
  3482. if (extensions && extensions[this.name]) {
  3483. var extension = extensions[this.name];
  3484. this._lights = extension.lights;
  3485. }
  3486. };
  3487. /** @hidden */
  3488. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  3489. var _this = this;
  3490. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3491. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  3492. var babylonLight;
  3493. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3494. var name = light.name || babylonMesh.name;
  3495. switch (light.type) {
  3496. case LightType.DIRECTIONAL: {
  3497. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Backward(), _this._loader.babylonScene);
  3498. break;
  3499. }
  3500. case LightType.POINT: {
  3501. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader.babylonScene);
  3502. break;
  3503. }
  3504. case LightType.SPOT: {
  3505. var babylonSpotLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  3506. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  3507. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  3508. babylonLight = babylonSpotLight;
  3509. break;
  3510. }
  3511. default: {
  3512. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3513. }
  3514. }
  3515. babylonLight.falloffType = BABYLON.Light.FALLOFF_GLTF;
  3516. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  3517. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3518. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  3519. babylonLight.parent = babylonMesh;
  3520. assign(babylonMesh);
  3521. });
  3522. });
  3523. };
  3524. return KHR_lights;
  3525. }());
  3526. Extensions.KHR_lights = KHR_lights;
  3527. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  3528. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3529. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3530. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3531. })(BABYLON || (BABYLON = {}));
  3532. //# sourceMappingURL=KHR_lights_punctual.js.map
  3533. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3534. var BABYLON;
  3535. (function (BABYLON) {
  3536. var GLTF2;
  3537. (function (GLTF2) {
  3538. var Loader;
  3539. (function (Loader) {
  3540. var Extensions;
  3541. (function (Extensions) {
  3542. var NAME = "KHR_texture_transform";
  3543. /**
  3544. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  3545. */
  3546. var KHR_texture_transform = /** @class */ (function () {
  3547. /** @hidden */
  3548. function KHR_texture_transform(loader) {
  3549. /** The name of this extension. */
  3550. this.name = NAME;
  3551. /** Defines whether this extension is enabled. */
  3552. this.enabled = true;
  3553. this._loader = loader;
  3554. }
  3555. /** @hidden */
  3556. KHR_texture_transform.prototype.dispose = function () {
  3557. delete this._loader;
  3558. };
  3559. /** @hidden */
  3560. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  3561. var _this = this;
  3562. return GLTF2.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  3563. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3564. if (!(babylonTexture instanceof BABYLON.Texture)) {
  3565. throw new Error(extensionContext + ": Texture type not supported");
  3566. }
  3567. if (extension.offset) {
  3568. babylonTexture.uOffset = extension.offset[0];
  3569. babylonTexture.vOffset = extension.offset[1];
  3570. }
  3571. // Always rotate around the origin.
  3572. babylonTexture.uRotationCenter = 0;
  3573. babylonTexture.vRotationCenter = 0;
  3574. if (extension.rotation) {
  3575. babylonTexture.wAng = -extension.rotation;
  3576. }
  3577. if (extension.scale) {
  3578. babylonTexture.uScale = extension.scale[0];
  3579. babylonTexture.vScale = extension.scale[1];
  3580. }
  3581. if (extension.texCoord != undefined) {
  3582. babylonTexture.coordinatesIndex = extension.texCoord;
  3583. }
  3584. assign(babylonTexture);
  3585. });
  3586. });
  3587. };
  3588. return KHR_texture_transform;
  3589. }());
  3590. Extensions.KHR_texture_transform = KHR_texture_transform;
  3591. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3592. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3593. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3594. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3595. })(BABYLON || (BABYLON = {}));
  3596. //# sourceMappingURL=KHR_texture_transform.js.map
  3597. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3598. var BABYLON;
  3599. (function (BABYLON) {
  3600. var GLTF2;
  3601. (function (GLTF2) {
  3602. var Loader;
  3603. (function (Loader) {
  3604. var Extensions;
  3605. (function (Extensions) {
  3606. var NAME = "EXT_lights_image_based";
  3607. /**
  3608. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  3609. */
  3610. var EXT_lights_image_based = /** @class */ (function () {
  3611. /** @hidden */
  3612. function EXT_lights_image_based(loader) {
  3613. /** The name of this extension. */
  3614. this.name = NAME;
  3615. /** Defines whether this extension is enabled. */
  3616. this.enabled = true;
  3617. this._loader = loader;
  3618. }
  3619. /** @hidden */
  3620. EXT_lights_image_based.prototype.dispose = function () {
  3621. delete this._loader;
  3622. delete this._lights;
  3623. };
  3624. /** @hidden */
  3625. EXT_lights_image_based.prototype.onLoading = function () {
  3626. var extensions = this._loader.gltf.extensions;
  3627. if (extensions && extensions[this.name]) {
  3628. var extension = extensions[this.name];
  3629. this._lights = extension.lights;
  3630. }
  3631. };
  3632. /** @hidden */
  3633. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  3634. var _this = this;
  3635. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3636. var promises = new Array();
  3637. promises.push(_this._loader.loadSceneAsync(context, scene));
  3638. _this._loader.logOpen("" + extensionContext);
  3639. var light = GLTF2.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  3640. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3641. _this._loader.babylonScene.environmentTexture = texture;
  3642. }));
  3643. _this._loader.logClose();
  3644. return Promise.all(promises).then(function () { });
  3645. });
  3646. };
  3647. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  3648. var _this = this;
  3649. if (!light._loaded) {
  3650. var promises = new Array();
  3651. this._loader.logOpen("" + context);
  3652. var imageData_1 = new Array(light.specularImages.length);
  3653. var _loop_1 = function (mipmap) {
  3654. var faces = light.specularImages[mipmap];
  3655. imageData_1[mipmap] = new Array(faces.length);
  3656. var _loop_2 = function (face) {
  3657. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3658. this_1._loader.logOpen("" + specularImageContext);
  3659. var index = faces[face];
  3660. var image = GLTF2.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  3661. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  3662. imageData_1[mipmap][face] = data;
  3663. }));
  3664. this_1._loader.logClose();
  3665. };
  3666. for (var face = 0; face < faces.length; face++) {
  3667. _loop_2(face);
  3668. }
  3669. };
  3670. var this_1 = this;
  3671. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3672. _loop_1(mipmap);
  3673. }
  3674. this._loader.logClose();
  3675. light._loaded = Promise.all(promises).then(function () {
  3676. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  3677. light._babylonTexture = babylonTexture;
  3678. if (light.intensity != undefined) {
  3679. babylonTexture.level = light.intensity;
  3680. }
  3681. if (light.rotation) {
  3682. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  3683. // Invert the rotation so that positive rotation is counter-clockwise.
  3684. if (!_this._loader.babylonScene.useRightHandedSystem) {
  3685. rotation = BABYLON.Quaternion.Inverse(rotation);
  3686. }
  3687. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3688. }
  3689. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3690. sphericalHarmonics.scale(light.intensity);
  3691. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3692. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3693. // Compute the lod generation scale to fit exactly to the number of levels available.
  3694. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  3695. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3696. });
  3697. }
  3698. return light._loaded.then(function () {
  3699. return light._babylonTexture;
  3700. });
  3701. };
  3702. return EXT_lights_image_based;
  3703. }());
  3704. Extensions.EXT_lights_image_based = EXT_lights_image_based;
  3705. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  3706. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  3707. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  3708. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3709. })(BABYLON || (BABYLON = {}));
  3710. //# sourceMappingURL=EXT_lights_image_based.js.map