babylonjs.loaders.js 249 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944
  1. var babylonDependency; try { babylonDependency = BABYLON || (typeof require !== 'undefined' && require("../babylon.max")); } catch (e) { babylonDependency = BABYLON || (typeof require !== 'undefined' && require("babylonjs")); }
  2. var BABYLON = babylonDependency;
  3. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  5. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  6. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8. };
  9. var __extends = (this && this.__extends) || (function () {
  10. var extendStatics = Object.setPrototypeOf ||
  11. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  12. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  13. return function (d, b) {
  14. extendStatics(d, b);
  15. function __() { this.constructor = d; }
  16. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17. };
  18. })();
  19. var BABYLON;
  20. (function (BABYLON) {
  21. var STLFileLoader = /** @class */ (function () {
  22. function STLFileLoader() {
  23. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  24. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  25. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  26. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  27. this.name = "stl";
  28. // force data to come in as an ArrayBuffer
  29. // we'll convert to string if it looks like it's an ASCII .stl
  30. this.extensions = {
  31. ".stl": { isBinary: true },
  32. };
  33. }
  34. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  35. var matches;
  36. if (this.isBinary(data)) {
  37. // binary .stl
  38. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  39. this.parseBinary(babylonMesh, data);
  40. if (meshes) {
  41. meshes.push(babylonMesh);
  42. }
  43. return true;
  44. }
  45. // ASCII .stl
  46. // convert to string
  47. var array_buffer = new Uint8Array(data);
  48. var str = '';
  49. for (var i = 0; i < data.byteLength; i++) {
  50. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  51. }
  52. data = str;
  53. while (matches = this.solidPattern.exec(data)) {
  54. var meshName = matches[1];
  55. var meshNameFromEnd = matches[3];
  56. if (meshName != meshNameFromEnd) {
  57. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  58. return false;
  59. }
  60. // check meshesNames
  61. if (meshesNames && meshName) {
  62. if (meshesNames instanceof Array) {
  63. if (!meshesNames.indexOf(meshName)) {
  64. continue;
  65. }
  66. }
  67. else {
  68. if (meshName !== meshesNames) {
  69. continue;
  70. }
  71. }
  72. }
  73. // stl mesh name can be empty as well
  74. meshName = meshName || "stlmesh";
  75. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  76. this.parseASCII(babylonMesh, matches[2]);
  77. if (meshes) {
  78. meshes.push(babylonMesh);
  79. }
  80. }
  81. return true;
  82. };
  83. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  84. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  85. if (result) {
  86. scene.createDefaultCameraOrLight();
  87. }
  88. return result;
  89. };
  90. STLFileLoader.prototype.isBinary = function (data) {
  91. // check if file size is correct for binary stl
  92. var faceSize, nFaces, reader;
  93. reader = new DataView(data);
  94. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  95. nFaces = reader.getUint32(80, true);
  96. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  97. return true;
  98. }
  99. // check characters higher than ASCII to confirm binary
  100. var fileLength = reader.byteLength;
  101. for (var index = 0; index < fileLength; index++) {
  102. if (reader.getUint8(index) > 127) {
  103. return true;
  104. }
  105. }
  106. return false;
  107. };
  108. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  109. var reader = new DataView(data);
  110. var faces = reader.getUint32(80, true);
  111. var dataOffset = 84;
  112. var faceLength = 12 * 4 + 2;
  113. var offset = 0;
  114. var positions = new Float32Array(faces * 3 * 3);
  115. var normals = new Float32Array(faces * 3 * 3);
  116. var indices = new Uint32Array(faces * 3);
  117. var indicesCount = 0;
  118. for (var face = 0; face < faces; face++) {
  119. var start = dataOffset + face * faceLength;
  120. var normalX = reader.getFloat32(start, true);
  121. var normalY = reader.getFloat32(start + 4, true);
  122. var normalZ = reader.getFloat32(start + 8, true);
  123. for (var i = 1; i <= 3; i++) {
  124. var vertexstart = start + i * 12;
  125. // ordering is intentional to match ascii import
  126. positions[offset] = reader.getFloat32(vertexstart, true);
  127. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  128. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  129. normals[offset] = normalX;
  130. normals[offset + 2] = normalY;
  131. normals[offset + 1] = normalZ;
  132. offset += 3;
  133. }
  134. indices[indicesCount] = indicesCount++;
  135. indices[indicesCount] = indicesCount++;
  136. indices[indicesCount] = indicesCount++;
  137. }
  138. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  139. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  140. mesh.setIndices(indices);
  141. mesh.computeWorldMatrix(true);
  142. };
  143. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  144. var positions = [];
  145. var normals = [];
  146. var indices = [];
  147. var indicesCount = 0;
  148. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  149. var matches;
  150. while (matches = this.facetsPattern.exec(solidData)) {
  151. var facet = matches[1];
  152. //one normal per face
  153. var normalMatches = this.normalPattern.exec(facet);
  154. this.normalPattern.lastIndex = 0;
  155. if (!normalMatches) {
  156. continue;
  157. }
  158. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  159. var vertexMatch;
  160. while (vertexMatch = this.vertexPattern.exec(facet)) {
  161. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  162. normals.push(normal[0], normal[1], normal[2]);
  163. }
  164. indices.push(indicesCount++, indicesCount++, indicesCount++);
  165. this.vertexPattern.lastIndex = 0;
  166. }
  167. this.facetsPattern.lastIndex = 0;
  168. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  169. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  170. mesh.setIndices(indices);
  171. mesh.computeWorldMatrix(true);
  172. };
  173. return STLFileLoader;
  174. }());
  175. BABYLON.STLFileLoader = STLFileLoader;
  176. if (BABYLON.SceneLoader) {
  177. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  178. }
  179. })(BABYLON || (BABYLON = {}));
  180. //# sourceMappingURL=babylon.stlFileLoader.js.map
  181. var BABYLON;
  182. (function (BABYLON) {
  183. /**
  184. * Class reading and parsing the MTL file bundled with the obj file.
  185. */
  186. var MTLFileLoader = /** @class */ (function () {
  187. function MTLFileLoader() {
  188. // All material loaded from the mtl will be set here
  189. this.materials = [];
  190. }
  191. /**
  192. * This function will read the mtl file and create each material described inside
  193. * This function could be improve by adding :
  194. * -some component missing (Ni, Tf...)
  195. * -including the specific options available
  196. *
  197. * @param scene
  198. * @param data
  199. * @param rootUrl
  200. */
  201. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  202. //Split the lines from the file
  203. var lines = data.split('\n');
  204. //Space char
  205. var delimiter_pattern = /\s+/;
  206. //Array with RGB colors
  207. var color;
  208. //New material
  209. var material;
  210. //Look at each line
  211. for (var i = 0; i < lines.length; i++) {
  212. var line = lines[i].trim();
  213. // Blank line or comment
  214. if (line.length === 0 || line.charAt(0) === '#') {
  215. continue;
  216. }
  217. //Get the first parameter (keyword)
  218. var pos = line.indexOf(' ');
  219. var key = (pos >= 0) ? line.substring(0, pos) : line;
  220. key = key.toLowerCase();
  221. //Get the data following the key
  222. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  223. //This mtl keyword will create the new material
  224. if (key === "newmtl") {
  225. //Check if it is the first material.
  226. // Materials specifications are described after this keyword.
  227. if (material) {
  228. //Add the previous material in the material array.
  229. this.materials.push(material);
  230. }
  231. //Create a new material.
  232. // value is the name of the material read in the mtl file
  233. material = new BABYLON.StandardMaterial(value, scene);
  234. }
  235. else if (key === "kd") {
  236. // Diffuse color (color under white light) using RGB values
  237. //value = "r g b"
  238. color = value.split(delimiter_pattern, 3).map(parseFloat);
  239. //color = [r,g,b]
  240. //Set tghe color into the material
  241. material.diffuseColor = BABYLON.Color3.FromArray(color);
  242. }
  243. else if (key === "ka") {
  244. // Ambient color (color under shadow) using RGB values
  245. //value = "r g b"
  246. color = value.split(delimiter_pattern, 3).map(parseFloat);
  247. //color = [r,g,b]
  248. //Set tghe color into the material
  249. material.ambientColor = BABYLON.Color3.FromArray(color);
  250. }
  251. else if (key === "ks") {
  252. // Specular color (color when light is reflected from shiny surface) using RGB values
  253. //value = "r g b"
  254. color = value.split(delimiter_pattern, 3).map(parseFloat);
  255. //color = [r,g,b]
  256. //Set the color into the material
  257. material.specularColor = BABYLON.Color3.FromArray(color);
  258. }
  259. else if (key === "ke") {
  260. // Emissive color using RGB values
  261. color = value.split(delimiter_pattern, 3).map(parseFloat);
  262. material.emissiveColor = BABYLON.Color3.FromArray(color);
  263. }
  264. else if (key === "ns") {
  265. //value = "Integer"
  266. material.specularPower = parseFloat(value);
  267. }
  268. else if (key === "d") {
  269. //d is dissolve for current material. It mean alpha for BABYLON
  270. material.alpha = parseFloat(value);
  271. //Texture
  272. //This part can be improved by adding the possible options of texture
  273. }
  274. else if (key === "map_ka") {
  275. // ambient texture map with a loaded image
  276. //We must first get the folder of the image
  277. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  278. }
  279. else if (key === "map_kd") {
  280. // Diffuse texture map with a loaded image
  281. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  282. }
  283. else if (key === "map_ks") {
  284. // Specular texture map with a loaded image
  285. //We must first get the folder of the image
  286. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  287. }
  288. else if (key === "map_ns") {
  289. //Specular
  290. //Specular highlight component
  291. //We must first get the folder of the image
  292. //
  293. //Not supported by BABYLON
  294. //
  295. // continue;
  296. }
  297. else if (key === "map_bump") {
  298. //The bump texture
  299. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  300. }
  301. else if (key === "map_d") {
  302. // The dissolve of the material
  303. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  304. //Options for illumination
  305. }
  306. else if (key === "illum") {
  307. //Illumination
  308. if (value === "0") {
  309. //That mean Kd == Kd
  310. }
  311. else if (value === "1") {
  312. //Color on and Ambient on
  313. }
  314. else if (value === "2") {
  315. //Highlight on
  316. }
  317. else if (value === "3") {
  318. //Reflection on and Ray trace on
  319. }
  320. else if (value === "4") {
  321. //Transparency: Glass on, Reflection: Ray trace on
  322. }
  323. else if (value === "5") {
  324. //Reflection: Fresnel on and Ray trace on
  325. }
  326. else if (value === "6") {
  327. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  328. }
  329. else if (value === "7") {
  330. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  331. }
  332. else if (value === "8") {
  333. //Reflection on and Ray trace off
  334. }
  335. else if (value === "9") {
  336. //Transparency: Glass on, Reflection: Ray trace off
  337. }
  338. else if (value === "10") {
  339. //Casts shadows onto invisible surfaces
  340. }
  341. }
  342. else {
  343. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  344. }
  345. }
  346. //At the end of the file, add the last material
  347. this.materials.push(material);
  348. };
  349. /**
  350. * Gets the texture for the material.
  351. *
  352. * If the material is imported from input file,
  353. * We sanitize the url to ensure it takes the textre from aside the material.
  354. *
  355. * @param rootUrl The root url to load from
  356. * @param value The value stored in the mtl
  357. * @return The Texture
  358. */
  359. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  360. if (!value) {
  361. return null;
  362. }
  363. var url = rootUrl;
  364. // Load from input file.
  365. if (rootUrl === "file:") {
  366. var lastDelimiter = value.lastIndexOf("\\");
  367. if (lastDelimiter === -1) {
  368. lastDelimiter = value.lastIndexOf("/");
  369. }
  370. if (lastDelimiter > -1) {
  371. url += value.substr(lastDelimiter + 1);
  372. }
  373. else {
  374. url += value;
  375. }
  376. }
  377. else {
  378. url += value;
  379. }
  380. return new BABYLON.Texture(url, scene);
  381. };
  382. return MTLFileLoader;
  383. }());
  384. BABYLON.MTLFileLoader = MTLFileLoader;
  385. var OBJFileLoader = /** @class */ (function () {
  386. function OBJFileLoader() {
  387. this.name = "obj";
  388. this.extensions = ".obj";
  389. this.obj = /^o/;
  390. this.group = /^g/;
  391. this.mtllib = /^mtllib /;
  392. this.usemtl = /^usemtl /;
  393. this.smooth = /^s /;
  394. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  395. // vn float float float
  396. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  397. // vt float float
  398. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  399. // f vertex vertex vertex ...
  400. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  401. // f vertex/uvs vertex/uvs vertex/uvs ...
  402. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  403. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  404. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  405. // f vertex//normal vertex//normal vertex//normal ...
  406. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  407. }
  408. /**
  409. * Calls synchronously the MTL file attached to this obj.
  410. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  411. * Without this function materials are not displayed in the first frame (but displayed after).
  412. * In consequence it is impossible to get material information in your HTML file
  413. *
  414. * @param url The URL of the MTL file
  415. * @param rootUrl
  416. * @param onSuccess Callback function to be called when the MTL file is loaded
  417. * @private
  418. */
  419. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  420. //The complete path to the mtl file
  421. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  422. // Loads through the babylon tools to allow fileInput search.
  423. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, null, null, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  424. };
  425. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  426. //get the meshes from OBJ file
  427. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  428. //Push meshes from OBJ file into the variable mesh of this function
  429. if (meshes) {
  430. loadedMeshes.forEach(function (mesh) {
  431. meshes.push(mesh);
  432. });
  433. }
  434. return true;
  435. };
  436. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  437. //Get the 3D model
  438. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  439. };
  440. /**
  441. * Read the OBJ file and create an Array of meshes.
  442. * Each mesh contains all information given by the OBJ and the MTL file.
  443. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  444. *
  445. * @param meshesNames
  446. * @param scene BABYLON.Scene The scene where are displayed the data
  447. * @param data String The content of the obj file
  448. * @param rootUrl String The path to the folder
  449. * @returns Array<AbstractMesh>
  450. * @private
  451. */
  452. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  453. var positions = []; //values for the positions of vertices
  454. var normals = []; //Values for the normals
  455. var uvs = []; //Values for the textures
  456. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  457. var handledMesh; //The current mesh of meshes array
  458. var indicesForBabylon = []; //The list of indices for VertexData
  459. var wrappedPositionForBabylon = []; //The list of position in vectors
  460. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  461. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  462. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  463. var curPositionInIndices = 0;
  464. var hasMeshes = false; //Meshes are defined in the file
  465. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  466. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  467. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  468. var triangles = []; //Indices from new triangles coming from polygons
  469. var materialNameFromObj = ""; //The name of the current material
  470. var fileToLoad = ""; //The name of the mtlFile to load
  471. var materialsFromMTLFile = new MTLFileLoader();
  472. var objMeshName = ""; //The name of the current obj mesh
  473. var increment = 1; //Id for meshes created by the multimaterial
  474. var isFirstMaterial = true;
  475. /**
  476. * Search for obj in the given array.
  477. * This function is called to check if a couple of data already exists in an array.
  478. *
  479. * If found, returns the index of the founded tuple index. Returns -1 if not found
  480. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  481. * @param obj Array<number>
  482. * @returns {boolean}
  483. */
  484. var isInArray = function (arr, obj) {
  485. if (!arr[obj[0]])
  486. arr[obj[0]] = { normals: [], idx: [] };
  487. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  488. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  489. };
  490. var isInArrayUV = function (arr, obj) {
  491. if (!arr[obj[0]])
  492. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  493. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  494. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  495. return arr[obj[0]].idx[idx];
  496. }
  497. return -1;
  498. };
  499. /**
  500. * This function set the data for each triangle.
  501. * Data are position, normals and uvs
  502. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  503. * If the tuple already exist, add only their indice
  504. *
  505. * @param indicePositionFromObj Integer The index in positions array
  506. * @param indiceUvsFromObj Integer The index in uvs array
  507. * @param indiceNormalFromObj Integer The index in normals array
  508. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  509. * @param textureVectorFromOBJ Vector3 The value of uvs
  510. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  511. */
  512. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  513. //Check if this tuple already exists in the list of tuples
  514. var _index;
  515. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  516. _index = isInArrayUV(tuplePosNorm, [
  517. indicePositionFromObj,
  518. indiceNormalFromObj,
  519. indiceUvsFromObj
  520. ]);
  521. }
  522. else {
  523. _index = isInArray(tuplePosNorm, [
  524. indicePositionFromObj,
  525. indiceNormalFromObj
  526. ]);
  527. }
  528. //If it not exists
  529. if (_index == -1) {
  530. //Add an new indice.
  531. //The array of indices is only an array with his length equal to the number of triangles - 1.
  532. //We add vertices data in this order
  533. indicesForBabylon.push(wrappedPositionForBabylon.length);
  534. //Push the position of vertice for Babylon
  535. //Each element is a BABYLON.Vector3(x,y,z)
  536. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  537. //Push the uvs for Babylon
  538. //Each element is a BABYLON.Vector3(u,v)
  539. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  540. //Push the normals for Babylon
  541. //Each element is a BABYLON.Vector3(x,y,z)
  542. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  543. //Add the tuple in the comparison list
  544. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  545. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  546. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  547. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  548. }
  549. else {
  550. //The tuple already exists
  551. //Add the index of the already existing tuple
  552. //At this index we can get the value of position, normal and uvs of vertex
  553. indicesForBabylon.push(_index);
  554. }
  555. };
  556. /**
  557. * Transform BABYLON.Vector() object onto 3 digits in an array
  558. */
  559. var unwrapData = function () {
  560. //Every array has the same length
  561. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  562. //Push the x, y, z values of each element in the unwrapped array
  563. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  564. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  565. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  566. }
  567. // Reset arrays for the next new meshes
  568. wrappedPositionForBabylon = [];
  569. wrappedNormalsForBabylon = [];
  570. wrappedUvsForBabylon = [];
  571. tuplePosNorm = [];
  572. curPositionInIndices = 0;
  573. };
  574. /**
  575. * Create triangles from polygons by recursion
  576. * The best to understand how it works is to draw it in the same time you get the recursion.
  577. * It is important to notice that a triangle is a polygon
  578. * We get 4 patterns of face defined in OBJ File :
  579. * facePattern1 = ["1","2","3","4","5","6"]
  580. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  581. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  582. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  583. * Each pattern is divided by the same method
  584. * @param face Array[String] The indices of elements
  585. * @param v Integer The variable to increment
  586. */
  587. var getTriangles = function (face, v) {
  588. //Work for each element of the array
  589. if (v + 1 < face.length) {
  590. //Add on the triangle variable the indexes to obtain triangles
  591. triangles.push(face[0], face[v], face[v + 1]);
  592. //Incrementation for recursion
  593. v += 1;
  594. //Recursion
  595. getTriangles(face, v);
  596. }
  597. //Result obtained after 2 iterations:
  598. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  599. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  600. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  601. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  602. };
  603. /**
  604. * Create triangles and push the data for each polygon for the pattern 1
  605. * In this pattern we get vertice positions
  606. * @param face
  607. * @param v
  608. */
  609. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  610. //Get the indices of triangles for each polygon
  611. getTriangles(face, v);
  612. //For each element in the triangles array.
  613. //This var could contains 1 to an infinity of triangles
  614. for (var k = 0; k < triangles.length; k++) {
  615. // Set position indice
  616. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  617. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  618. positions[indicePositionFromObj], //Get the vectors data
  619. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  620. );
  621. }
  622. //Reset variable for the next line
  623. triangles = [];
  624. };
  625. /**
  626. * Create triangles and push the data for each polygon for the pattern 2
  627. * In this pattern we get vertice positions and uvsu
  628. * @param face
  629. * @param v
  630. */
  631. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  632. //Get the indices of triangles for each polygon
  633. getTriangles(face, v);
  634. for (var k = 0; k < triangles.length; k++) {
  635. //triangle[k] = "1/1"
  636. //Split the data for getting position and uv
  637. var point = triangles[k].split("/"); // ["1", "1"]
  638. //Set position indice
  639. var indicePositionFromObj = parseInt(point[0]) - 1;
  640. //Set uv indice
  641. var indiceUvsFromObj = parseInt(point[1]) - 1;
  642. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  643. positions[indicePositionFromObj], //Get the values for each element
  644. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  645. );
  646. }
  647. //Reset variable for the next line
  648. triangles = [];
  649. };
  650. /**
  651. * Create triangles and push the data for each polygon for the pattern 3
  652. * In this pattern we get vertice positions, uvs and normals
  653. * @param face
  654. * @param v
  655. */
  656. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  657. //Get the indices of triangles for each polygon
  658. getTriangles(face, v);
  659. for (var k = 0; k < triangles.length; k++) {
  660. //triangle[k] = "1/1/1"
  661. //Split the data for getting position, uv, and normals
  662. var point = triangles[k].split("/"); // ["1", "1", "1"]
  663. // Set position indice
  664. var indicePositionFromObj = parseInt(point[0]) - 1;
  665. // Set uv indice
  666. var indiceUvsFromObj = parseInt(point[1]) - 1;
  667. // Set normal indice
  668. var indiceNormalFromObj = parseInt(point[2]) - 1;
  669. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  670. );
  671. }
  672. //Reset variable for the next line
  673. triangles = [];
  674. };
  675. /**
  676. * Create triangles and push the data for each polygon for the pattern 4
  677. * In this pattern we get vertice positions and normals
  678. * @param face
  679. * @param v
  680. */
  681. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  682. getTriangles(face, v);
  683. for (var k = 0; k < triangles.length; k++) {
  684. //triangle[k] = "1//1"
  685. //Split the data for getting position and normals
  686. var point = triangles[k].split("//"); // ["1", "1"]
  687. // We check indices, and normals
  688. var indicePositionFromObj = parseInt(point[0]) - 1;
  689. var indiceNormalFromObj = parseInt(point[1]) - 1;
  690. setData(indicePositionFromObj, 1, //Default value for uv
  691. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  692. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  693. }
  694. //Reset variable for the next line
  695. triangles = [];
  696. };
  697. var addPreviousObjMesh = function () {
  698. //Check if it is not the first mesh. Otherwise we don't have data.
  699. if (meshesFromObj.length > 0) {
  700. //Get the previous mesh for applying the data about the faces
  701. //=> in obj file, faces definition append after the name of the mesh
  702. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  703. //Set the data into Array for the mesh
  704. unwrapData();
  705. // Reverse tab. Otherwise face are displayed in the wrong sens
  706. indicesForBabylon.reverse();
  707. //Set the information for the mesh
  708. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  709. handledMesh.indices = indicesForBabylon.slice();
  710. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  711. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  712. handledMesh.uvs = unwrappedUVForBabylon.slice();
  713. //Reset the array for the next mesh
  714. indicesForBabylon = [];
  715. unwrappedPositionsForBabylon = [];
  716. unwrappedNormalsForBabylon = [];
  717. unwrappedUVForBabylon = [];
  718. }
  719. };
  720. //Main function
  721. //Split the file into lines
  722. var lines = data.split('\n');
  723. //Look at each line
  724. for (var i = 0; i < lines.length; i++) {
  725. var line = lines[i].trim();
  726. var result;
  727. //Comment or newLine
  728. if (line.length === 0 || line.charAt(0) === '#') {
  729. continue;
  730. //Get information about one position possible for the vertices
  731. }
  732. else if ((result = this.vertexPattern.exec(line)) !== null) {
  733. //Create a Vector3 with the position x, y, z
  734. //Value of result:
  735. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  736. //Add the Vector in the list of positions
  737. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  738. }
  739. else if ((result = this.normalPattern.exec(line)) !== null) {
  740. //Create a Vector3 with the normals x, y, z
  741. //Value of result
  742. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  743. //Add the Vector in the list of normals
  744. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  745. }
  746. else if ((result = this.uvPattern.exec(line)) !== null) {
  747. //Create a Vector2 with the normals u, v
  748. //Value of result
  749. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  750. //Add the Vector in the list of uvs
  751. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  752. //Identify patterns of faces
  753. //Face could be defined in different type of pattern
  754. }
  755. else if ((result = this.facePattern3.exec(line)) !== null) {
  756. //Value of result:
  757. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  758. //Set the data for this face
  759. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  760. 1);
  761. }
  762. else if ((result = this.facePattern4.exec(line)) !== null) {
  763. //Value of result:
  764. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  765. //Set the data for this face
  766. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  767. 1);
  768. }
  769. else if ((result = this.facePattern2.exec(line)) !== null) {
  770. //Value of result:
  771. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  772. //Set the data for this face
  773. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  774. 1);
  775. }
  776. else if ((result = this.facePattern1.exec(line)) !== null) {
  777. //Value of result
  778. //["f 1 2 3", "1 2 3"...]
  779. //Set the data for this face
  780. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  781. 1);
  782. //Define a mesh or an object
  783. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  784. }
  785. else if (this.group.test(line) || this.obj.test(line)) {
  786. //Create a new mesh corresponding to the name of the group.
  787. //Definition of the mesh
  788. var objMesh =
  789. //Set the name of the current obj mesh
  790. {
  791. name: line.substring(2).trim(),
  792. indices: undefined,
  793. positions: undefined,
  794. normals: undefined,
  795. uvs: undefined,
  796. materialName: ""
  797. };
  798. addPreviousObjMesh();
  799. //Push the last mesh created with only the name
  800. meshesFromObj.push(objMesh);
  801. //Set this variable to indicate that now meshesFromObj has objects defined inside
  802. hasMeshes = true;
  803. isFirstMaterial = true;
  804. increment = 1;
  805. //Keyword for applying a material
  806. }
  807. else if (this.usemtl.test(line)) {
  808. //Get the name of the material
  809. materialNameFromObj = line.substring(7).trim();
  810. //If this new material is in the same mesh
  811. if (!isFirstMaterial) {
  812. //Set the data for the previous mesh
  813. addPreviousObjMesh();
  814. //Create a new mesh
  815. var objMesh =
  816. //Set the name of the current obj mesh
  817. {
  818. name: objMeshName + "_mm" + increment.toString(),
  819. indices: undefined,
  820. positions: undefined,
  821. normals: undefined,
  822. uvs: undefined,
  823. materialName: materialNameFromObj
  824. };
  825. increment++;
  826. //If meshes are already defined
  827. meshesFromObj.push(objMesh);
  828. }
  829. //Set the material name if the previous line define a mesh
  830. if (hasMeshes && isFirstMaterial) {
  831. //Set the material name to the previous mesh (1 material per mesh)
  832. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  833. isFirstMaterial = false;
  834. }
  835. //Keyword for loading the mtl file
  836. }
  837. else if (this.mtllib.test(line)) {
  838. //Get the name of mtl file
  839. fileToLoad = line.substring(7).trim();
  840. //Apply smoothing
  841. }
  842. else if (this.smooth.test(line)) {
  843. // smooth shading => apply smoothing
  844. //Toda y I don't know it work with babylon and with obj.
  845. //With the obj file an integer is set
  846. }
  847. else {
  848. //If there is another possibility
  849. console.log("Unhandled expression at line : " + line);
  850. }
  851. }
  852. //At the end of the file, add the last mesh into the meshesFromObj array
  853. if (hasMeshes) {
  854. //Set the data for the last mesh
  855. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  856. //Reverse indices for displaying faces in the good sens
  857. indicesForBabylon.reverse();
  858. //Get the good array
  859. unwrapData();
  860. //Set array
  861. handledMesh.indices = indicesForBabylon;
  862. handledMesh.positions = unwrappedPositionsForBabylon;
  863. handledMesh.normals = unwrappedNormalsForBabylon;
  864. handledMesh.uvs = unwrappedUVForBabylon;
  865. }
  866. //If any o or g keyword found, create a mesj with a random id
  867. if (!hasMeshes) {
  868. // reverse tab of indices
  869. indicesForBabylon.reverse();
  870. //Get positions normals uvs
  871. unwrapData();
  872. //Set data for one mesh
  873. meshesFromObj.push({
  874. name: BABYLON.Geometry.RandomId(),
  875. indices: indicesForBabylon,
  876. positions: unwrappedPositionsForBabylon,
  877. normals: unwrappedNormalsForBabylon,
  878. uvs: unwrappedUVForBabylon,
  879. materialName: materialNameFromObj
  880. });
  881. }
  882. //Create a BABYLON.Mesh list
  883. var babylonMeshesArray = []; //The mesh for babylon
  884. var materialToUse = new Array();
  885. //Set data for each mesh
  886. for (var j = 0; j < meshesFromObj.length; j++) {
  887. //check meshesNames (stlFileLoader)
  888. if (meshesNames && meshesFromObj[j].name) {
  889. if (meshesNames instanceof Array) {
  890. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  891. continue;
  892. }
  893. }
  894. else {
  895. if (meshesFromObj[j].name !== meshesNames) {
  896. continue;
  897. }
  898. }
  899. }
  900. //Get the current mesh
  901. //Set the data with VertexBuffer for each mesh
  902. handledMesh = meshesFromObj[j];
  903. //Create a BABYLON.Mesh with the name of the obj mesh
  904. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  905. //Push the name of the material to an array
  906. //This is indispensable for the importMesh function
  907. materialToUse.push(meshesFromObj[j].materialName);
  908. var vertexData = new BABYLON.VertexData(); //The container for the values
  909. //Set the data for the babylonMesh
  910. vertexData.positions = handledMesh.positions;
  911. vertexData.normals = handledMesh.normals;
  912. vertexData.uvs = handledMesh.uvs;
  913. vertexData.indices = handledMesh.indices;
  914. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  915. vertexData.applyToMesh(babylonMesh);
  916. //Push the mesh into an array
  917. babylonMeshesArray.push(babylonMesh);
  918. }
  919. //load the materials
  920. //Check if we have a file to load
  921. if (fileToLoad !== "") {
  922. //Load the file synchronously
  923. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  924. //Create materials thanks MTLLoader function
  925. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  926. //Look at each material loaded in the mtl file
  927. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  928. //Three variables to get all meshes with the same material
  929. var startIndex = 0;
  930. var _indices = [];
  931. var _index;
  932. //The material from MTL file is used in the meshes loaded
  933. //Push the indice in an array
  934. //Check if the material is not used for another mesh
  935. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  936. _indices.push(_index);
  937. startIndex = _index + 1;
  938. }
  939. //If the material is not used dispose it
  940. if (_index == -1 && _indices.length == 0) {
  941. //If the material is not needed, remove it
  942. materialsFromMTLFile.materials[n].dispose();
  943. }
  944. else {
  945. for (var o = 0; o < _indices.length; o++) {
  946. //Apply the material to the BABYLON.Mesh for each mesh with the material
  947. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  948. }
  949. }
  950. }
  951. });
  952. }
  953. //Return an array with all BABYLON.Mesh
  954. return babylonMeshesArray;
  955. };
  956. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  957. return OBJFileLoader;
  958. }());
  959. BABYLON.OBJFileLoader = OBJFileLoader;
  960. if (BABYLON.SceneLoader) {
  961. //Add this loader into the register plugin
  962. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  963. }
  964. })(BABYLON || (BABYLON = {}));
  965. //# sourceMappingURL=babylon.objFileLoader.js.map
  966. var BABYLON;
  967. (function (BABYLON) {
  968. var GLTFLoaderCoordinateSystemMode;
  969. (function (GLTFLoaderCoordinateSystemMode) {
  970. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  971. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  972. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  973. // The glTF right-handed data is not transformed in any form and is loaded directly.
  974. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  975. // Sets the useRightHandedSystem flag on the scene.
  976. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  977. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  978. var GLTFFileLoader = /** @class */ (function () {
  979. function GLTFFileLoader() {
  980. // V2 options
  981. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  982. this.name = "gltf";
  983. this.extensions = {
  984. ".gltf": { isBinary: false },
  985. ".glb": { isBinary: true }
  986. };
  987. }
  988. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  989. var loaderData = GLTFFileLoader._parse(data, onError);
  990. if (!loaderData) {
  991. return;
  992. }
  993. if (this.onParsed) {
  994. this.onParsed(loaderData);
  995. }
  996. var loader = this._getLoader(loaderData, onError);
  997. if (!loader) {
  998. return;
  999. }
  1000. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  1001. };
  1002. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1003. var loaderData = GLTFFileLoader._parse(data, onError);
  1004. if (!loaderData) {
  1005. return;
  1006. }
  1007. if (this.onParsed) {
  1008. this.onParsed(loaderData);
  1009. }
  1010. var loader = this._getLoader(loaderData, onError);
  1011. if (!loader) {
  1012. return;
  1013. }
  1014. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  1015. };
  1016. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  1017. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  1018. };
  1019. GLTFFileLoader._parse = function (data, onError) {
  1020. try {
  1021. if (data instanceof ArrayBuffer) {
  1022. return GLTFFileLoader._parseBinary(data, onError);
  1023. }
  1024. return {
  1025. json: JSON.parse(data),
  1026. bin: null
  1027. };
  1028. }
  1029. catch (e) {
  1030. onError(e.message);
  1031. return null;
  1032. }
  1033. };
  1034. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  1035. var loaderVersion = { major: 2, minor: 0 };
  1036. var asset = loaderData.json.asset || {};
  1037. var version = GLTFFileLoader._parseVersion(asset.version);
  1038. if (!version) {
  1039. onError("Invalid version: " + asset.version);
  1040. return null;
  1041. }
  1042. if (asset.minVersion !== undefined) {
  1043. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  1044. if (!minVersion) {
  1045. onError("Invalid minimum version: " + asset.minVersion);
  1046. return null;
  1047. }
  1048. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  1049. onError("Incompatible minimum version: " + asset.minVersion);
  1050. return null;
  1051. }
  1052. }
  1053. var createLoaders = {
  1054. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  1055. 2: GLTFFileLoader.CreateGLTFLoaderV2
  1056. };
  1057. var createLoader = createLoaders[version.major];
  1058. if (!createLoader) {
  1059. onError("Unsupported version: " + asset.version);
  1060. return null;
  1061. }
  1062. return createLoader(this);
  1063. };
  1064. GLTFFileLoader._parseBinary = function (data, onError) {
  1065. var Binary = {
  1066. Magic: 0x46546C67
  1067. };
  1068. var binaryReader = new BinaryReader(data);
  1069. var magic = binaryReader.readUint32();
  1070. if (magic !== Binary.Magic) {
  1071. onError("Unexpected magic: " + magic);
  1072. return null;
  1073. }
  1074. var version = binaryReader.readUint32();
  1075. switch (version) {
  1076. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  1077. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  1078. }
  1079. onError("Unsupported version: " + version);
  1080. return null;
  1081. };
  1082. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  1083. var ContentFormat = {
  1084. JSON: 0
  1085. };
  1086. var length = binaryReader.readUint32();
  1087. if (length != binaryReader.getLength()) {
  1088. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1089. return null;
  1090. }
  1091. var contentLength = binaryReader.readUint32();
  1092. var contentFormat = binaryReader.readUint32();
  1093. var content;
  1094. switch (contentFormat) {
  1095. case ContentFormat.JSON:
  1096. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  1097. break;
  1098. default:
  1099. onError("Unexpected content format: " + contentFormat);
  1100. return null;
  1101. }
  1102. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  1103. var body = binaryReader.readUint8Array(bytesRemaining);
  1104. return {
  1105. json: content,
  1106. bin: body
  1107. };
  1108. };
  1109. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  1110. var ChunkFormat = {
  1111. JSON: 0x4E4F534A,
  1112. BIN: 0x004E4942
  1113. };
  1114. var length = binaryReader.readUint32();
  1115. if (length !== binaryReader.getLength()) {
  1116. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1117. return null;
  1118. }
  1119. // JSON chunk
  1120. var chunkLength = binaryReader.readUint32();
  1121. var chunkFormat = binaryReader.readUint32();
  1122. if (chunkFormat !== ChunkFormat.JSON) {
  1123. onError("First chunk format is not JSON");
  1124. return null;
  1125. }
  1126. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  1127. // Look for BIN chunk
  1128. var bin = null;
  1129. while (binaryReader.getPosition() < binaryReader.getLength()) {
  1130. chunkLength = binaryReader.readUint32();
  1131. chunkFormat = binaryReader.readUint32();
  1132. switch (chunkFormat) {
  1133. case ChunkFormat.JSON:
  1134. onError("Unexpected JSON chunk");
  1135. return null;
  1136. case ChunkFormat.BIN:
  1137. bin = binaryReader.readUint8Array(chunkLength);
  1138. break;
  1139. default:
  1140. // ignore unrecognized chunkFormat
  1141. binaryReader.skipBytes(chunkLength);
  1142. break;
  1143. }
  1144. }
  1145. return {
  1146. json: json,
  1147. bin: bin
  1148. };
  1149. };
  1150. GLTFFileLoader._parseVersion = function (version) {
  1151. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  1152. if (!match) {
  1153. return null;
  1154. }
  1155. return {
  1156. major: parseInt(match[1]),
  1157. minor: parseInt(match[2])
  1158. };
  1159. };
  1160. GLTFFileLoader._compareVersion = function (a, b) {
  1161. if (a.major > b.major)
  1162. return 1;
  1163. if (a.major < b.major)
  1164. return -1;
  1165. if (a.minor > b.minor)
  1166. return 1;
  1167. if (a.minor < b.minor)
  1168. return -1;
  1169. return 0;
  1170. };
  1171. GLTFFileLoader._decodeBufferToText = function (buffer) {
  1172. var result = "";
  1173. var length = buffer.byteLength;
  1174. for (var i = 0; i < length; ++i) {
  1175. result += String.fromCharCode(buffer[i]);
  1176. }
  1177. return result;
  1178. };
  1179. // V1 options
  1180. GLTFFileLoader.HomogeneousCoordinates = false;
  1181. GLTFFileLoader.IncrementalLoading = true;
  1182. return GLTFFileLoader;
  1183. }());
  1184. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1185. var BinaryReader = /** @class */ (function () {
  1186. function BinaryReader(arrayBuffer) {
  1187. this._arrayBuffer = arrayBuffer;
  1188. this._dataView = new DataView(arrayBuffer);
  1189. this._byteOffset = 0;
  1190. }
  1191. BinaryReader.prototype.getPosition = function () {
  1192. return this._byteOffset;
  1193. };
  1194. BinaryReader.prototype.getLength = function () {
  1195. return this._arrayBuffer.byteLength;
  1196. };
  1197. BinaryReader.prototype.readUint32 = function () {
  1198. var value = this._dataView.getUint32(this._byteOffset, true);
  1199. this._byteOffset += 4;
  1200. return value;
  1201. };
  1202. BinaryReader.prototype.readUint8Array = function (length) {
  1203. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1204. this._byteOffset += length;
  1205. return value;
  1206. };
  1207. BinaryReader.prototype.skipBytes = function (length) {
  1208. this._byteOffset += length;
  1209. };
  1210. return BinaryReader;
  1211. }());
  1212. if (BABYLON.SceneLoader) {
  1213. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1214. }
  1215. })(BABYLON || (BABYLON = {}));
  1216. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1217. var BABYLON;
  1218. (function (BABYLON) {
  1219. var GLTF1;
  1220. (function (GLTF1) {
  1221. /**
  1222. * Enums
  1223. */
  1224. var EComponentType;
  1225. (function (EComponentType) {
  1226. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1227. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1228. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1229. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1230. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1231. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1232. var EShaderType;
  1233. (function (EShaderType) {
  1234. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1235. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1236. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1237. var EParameterType;
  1238. (function (EParameterType) {
  1239. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1240. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1241. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1242. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1243. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1244. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1245. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1246. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1247. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1248. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1249. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1250. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1251. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1252. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1253. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1254. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1255. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1256. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1257. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1258. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1259. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1260. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1261. var ETextureWrapMode;
  1262. (function (ETextureWrapMode) {
  1263. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1264. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1265. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1266. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1267. var ETextureFilterType;
  1268. (function (ETextureFilterType) {
  1269. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1270. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1271. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1272. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1273. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1274. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1275. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1276. var ETextureFormat;
  1277. (function (ETextureFormat) {
  1278. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1279. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1280. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1281. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1282. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1283. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1284. var ECullingType;
  1285. (function (ECullingType) {
  1286. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1287. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1288. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1289. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1290. var EBlendingFunction;
  1291. (function (EBlendingFunction) {
  1292. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1293. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1294. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1295. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1296. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1297. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1298. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1299. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1300. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1301. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1302. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1303. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1304. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1305. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1306. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1307. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1308. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1309. })(BABYLON || (BABYLON = {}));
  1310. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1311. var BABYLON;
  1312. (function (BABYLON) {
  1313. var GLTF1;
  1314. (function (GLTF1) {
  1315. /**
  1316. * Tokenizer. Used for shaders compatibility
  1317. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1318. */
  1319. var ETokenType;
  1320. (function (ETokenType) {
  1321. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1322. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1323. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1324. })(ETokenType || (ETokenType = {}));
  1325. var Tokenizer = /** @class */ (function () {
  1326. function Tokenizer(toParse) {
  1327. this._pos = 0;
  1328. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1329. this._toParse = toParse;
  1330. this._maxPos = toParse.length;
  1331. }
  1332. Tokenizer.prototype.getNextToken = function () {
  1333. if (this.isEnd())
  1334. return ETokenType.END_OF_INPUT;
  1335. this.currentString = this.read();
  1336. this.currentToken = ETokenType.UNKNOWN;
  1337. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1338. this.currentToken = ETokenType.IDENTIFIER;
  1339. this.currentIdentifier = this.currentString;
  1340. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1341. this.currentIdentifier += this.currentString;
  1342. this.forward();
  1343. }
  1344. }
  1345. return this.currentToken;
  1346. };
  1347. Tokenizer.prototype.peek = function () {
  1348. return this._toParse[this._pos];
  1349. };
  1350. Tokenizer.prototype.read = function () {
  1351. return this._toParse[this._pos++];
  1352. };
  1353. Tokenizer.prototype.forward = function () {
  1354. this._pos++;
  1355. };
  1356. Tokenizer.prototype.isEnd = function () {
  1357. return this._pos >= this._maxPos;
  1358. };
  1359. return Tokenizer;
  1360. }());
  1361. /**
  1362. * Values
  1363. */
  1364. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1365. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1366. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1367. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1368. /**
  1369. * Parse
  1370. */
  1371. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1372. for (var buf in parsedBuffers) {
  1373. var parsedBuffer = parsedBuffers[buf];
  1374. gltfRuntime.buffers[buf] = parsedBuffer;
  1375. gltfRuntime.buffersCount++;
  1376. }
  1377. };
  1378. var parseShaders = function (parsedShaders, gltfRuntime) {
  1379. for (var sha in parsedShaders) {
  1380. var parsedShader = parsedShaders[sha];
  1381. gltfRuntime.shaders[sha] = parsedShader;
  1382. gltfRuntime.shaderscount++;
  1383. }
  1384. };
  1385. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1386. for (var object in parsedObjects) {
  1387. var parsedObject = parsedObjects[object];
  1388. gltfRuntime[runtimeProperty][object] = parsedObject;
  1389. }
  1390. };
  1391. /**
  1392. * Utils
  1393. */
  1394. var normalizeUVs = function (buffer) {
  1395. if (!buffer) {
  1396. return;
  1397. }
  1398. for (var i = 0; i < buffer.length / 2; i++) {
  1399. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1400. }
  1401. };
  1402. var getAttribute = function (attributeParameter) {
  1403. if (attributeParameter.semantic === "NORMAL") {
  1404. return "normal";
  1405. }
  1406. else if (attributeParameter.semantic === "POSITION") {
  1407. return "position";
  1408. }
  1409. else if (attributeParameter.semantic === "JOINT") {
  1410. return "matricesIndices";
  1411. }
  1412. else if (attributeParameter.semantic === "WEIGHT") {
  1413. return "matricesWeights";
  1414. }
  1415. else if (attributeParameter.semantic === "COLOR") {
  1416. return "color";
  1417. }
  1418. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1419. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1420. return "uv" + (channel === 0 ? "" : channel + 1);
  1421. }
  1422. return null;
  1423. };
  1424. /**
  1425. * Loads and creates animations
  1426. */
  1427. var loadAnimations = function (gltfRuntime) {
  1428. for (var anim in gltfRuntime.animations) {
  1429. var animation = gltfRuntime.animations[anim];
  1430. var lastAnimation = null;
  1431. for (var i = 0; i < animation.channels.length; i++) {
  1432. // Get parameters and load buffers
  1433. var channel = animation.channels[i];
  1434. var sampler = animation.samplers[channel.sampler];
  1435. if (!sampler) {
  1436. continue;
  1437. }
  1438. var inputData = null;
  1439. var outputData = null;
  1440. if (animation.parameters) {
  1441. inputData = animation.parameters[sampler.input];
  1442. outputData = animation.parameters[sampler.output];
  1443. }
  1444. else {
  1445. inputData = sampler.input;
  1446. outputData = sampler.output;
  1447. }
  1448. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1449. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1450. var targetID = channel.target.id;
  1451. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1452. if (targetNode === null) {
  1453. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1454. }
  1455. if (targetNode === null) {
  1456. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1457. continue;
  1458. }
  1459. var isBone = targetNode instanceof BABYLON.Bone;
  1460. // Get target path (position, rotation or scaling)
  1461. var targetPath = channel.target.path;
  1462. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1463. if (targetPathIndex !== -1) {
  1464. targetPath = babylonAnimationPaths[targetPathIndex];
  1465. }
  1466. // Determine animation type
  1467. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1468. if (!isBone) {
  1469. if (targetPath === "rotationQuaternion") {
  1470. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1471. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1472. }
  1473. else {
  1474. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1475. }
  1476. }
  1477. // Create animation and key frames
  1478. var babylonAnimation = null;
  1479. var keys = [];
  1480. var arrayOffset = 0;
  1481. var modifyKey = false;
  1482. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1483. babylonAnimation = lastAnimation;
  1484. modifyKey = true;
  1485. }
  1486. if (!modifyKey) {
  1487. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1488. }
  1489. // For each frame
  1490. for (var j = 0; j < bufferInput.length; j++) {
  1491. var value = null;
  1492. if (targetPath === "rotationQuaternion") {
  1493. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1494. arrayOffset += 4;
  1495. }
  1496. else {
  1497. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1498. arrayOffset += 3;
  1499. }
  1500. if (isBone) {
  1501. var bone = targetNode;
  1502. var translation = BABYLON.Vector3.Zero();
  1503. var rotationQuaternion = new BABYLON.Quaternion();
  1504. var scaling = BABYLON.Vector3.Zero();
  1505. // Warning on decompose
  1506. var mat = bone.getBaseMatrix();
  1507. if (modifyKey) {
  1508. mat = lastAnimation.getKeys()[j].value;
  1509. }
  1510. mat.decompose(scaling, rotationQuaternion, translation);
  1511. if (targetPath === "position") {
  1512. translation = value;
  1513. }
  1514. else if (targetPath === "rotationQuaternion") {
  1515. rotationQuaternion = value;
  1516. }
  1517. else {
  1518. scaling = value;
  1519. }
  1520. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1521. }
  1522. if (!modifyKey) {
  1523. keys.push({
  1524. frame: bufferInput[j],
  1525. value: value
  1526. });
  1527. }
  1528. else {
  1529. lastAnimation.getKeys()[j].value = value;
  1530. }
  1531. }
  1532. // Finish
  1533. if (!modifyKey) {
  1534. babylonAnimation.setKeys(keys);
  1535. targetNode.animations.push(babylonAnimation);
  1536. }
  1537. lastAnimation = babylonAnimation;
  1538. gltfRuntime.scene.stopAnimation(targetNode);
  1539. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1540. }
  1541. }
  1542. };
  1543. /**
  1544. * Returns the bones transformation matrix
  1545. */
  1546. var configureBoneTransformation = function (node) {
  1547. var mat = null;
  1548. if (node.translation || node.rotation || node.scale) {
  1549. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1550. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1551. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1552. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1553. }
  1554. else {
  1555. mat = BABYLON.Matrix.FromArray(node.matrix);
  1556. }
  1557. return mat;
  1558. };
  1559. /**
  1560. * Returns the parent bone
  1561. */
  1562. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1563. // Try to find
  1564. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1565. if (newSkeleton.bones[i].name === jointName) {
  1566. return newSkeleton.bones[i];
  1567. }
  1568. }
  1569. // Not found, search in gltf nodes
  1570. var nodes = gltfRuntime.nodes;
  1571. for (var nde in nodes) {
  1572. var node = nodes[nde];
  1573. if (!node.jointName) {
  1574. continue;
  1575. }
  1576. var children = node.children;
  1577. for (var i = 0; i < children.length; i++) {
  1578. var child = gltfRuntime.nodes[children[i]];
  1579. if (!child.jointName) {
  1580. continue;
  1581. }
  1582. if (child.jointName === jointName) {
  1583. var mat = configureBoneTransformation(node);
  1584. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1585. bone.id = nde;
  1586. return bone;
  1587. }
  1588. }
  1589. }
  1590. return null;
  1591. };
  1592. /**
  1593. * Returns the appropriate root node
  1594. */
  1595. var getNodeToRoot = function (nodesToRoot, id) {
  1596. for (var i = 0; i < nodesToRoot.length; i++) {
  1597. var nodeToRoot = nodesToRoot[i];
  1598. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1599. var child = nodeToRoot.node.children[j];
  1600. if (child === id) {
  1601. return nodeToRoot.bone;
  1602. }
  1603. }
  1604. }
  1605. return null;
  1606. };
  1607. /**
  1608. * Returns the node with the joint name
  1609. */
  1610. var getJointNode = function (gltfRuntime, jointName) {
  1611. var nodes = gltfRuntime.nodes;
  1612. var node = nodes[jointName];
  1613. if (node) {
  1614. return {
  1615. node: node,
  1616. id: jointName
  1617. };
  1618. }
  1619. for (var nde in nodes) {
  1620. node = nodes[nde];
  1621. if (node.jointName === jointName) {
  1622. return {
  1623. node: node,
  1624. id: nde
  1625. };
  1626. }
  1627. }
  1628. return null;
  1629. };
  1630. /**
  1631. * Checks if a nodes is in joints
  1632. */
  1633. var nodeIsInJoints = function (skins, id) {
  1634. for (var i = 0; i < skins.jointNames.length; i++) {
  1635. if (skins.jointNames[i] === id) {
  1636. return true;
  1637. }
  1638. }
  1639. return false;
  1640. };
  1641. /**
  1642. * Fills the nodes to root for bones and builds hierarchy
  1643. */
  1644. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1645. // Creates nodes for root
  1646. for (var nde in gltfRuntime.nodes) {
  1647. var node = gltfRuntime.nodes[nde];
  1648. var id = nde;
  1649. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1650. continue;
  1651. }
  1652. // Create node to root bone
  1653. var mat = configureBoneTransformation(node);
  1654. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  1655. bone.id = id;
  1656. nodesToRoot.push({ bone: bone, node: node, id: id });
  1657. }
  1658. // Parenting
  1659. for (var i = 0; i < nodesToRoot.length; i++) {
  1660. var nodeToRoot = nodesToRoot[i];
  1661. var children = nodeToRoot.node.children;
  1662. for (var j = 0; j < children.length; j++) {
  1663. var child = null;
  1664. for (var k = 0; k < nodesToRoot.length; k++) {
  1665. if (nodesToRoot[k].id === children[j]) {
  1666. child = nodesToRoot[k];
  1667. break;
  1668. }
  1669. }
  1670. if (child) {
  1671. child.bone._parent = nodeToRoot.bone;
  1672. nodeToRoot.bone.children.push(child.bone);
  1673. }
  1674. }
  1675. }
  1676. };
  1677. /**
  1678. * Imports a skeleton
  1679. */
  1680. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1681. if (!newSkeleton) {
  1682. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  1683. }
  1684. if (!skins.babylonSkeleton) {
  1685. return newSkeleton;
  1686. }
  1687. // Find the root bones
  1688. var nodesToRoot = [];
  1689. var nodesToRootToAdd = [];
  1690. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1691. newSkeleton.bones = [];
  1692. // Joints
  1693. for (var i = 0; i < skins.jointNames.length; i++) {
  1694. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1695. var node = jointNode.node;
  1696. if (!node) {
  1697. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1698. continue;
  1699. }
  1700. var id = jointNode.id;
  1701. // Optimize, if the bone already exists...
  1702. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1703. if (existingBone) {
  1704. newSkeleton.bones.push(existingBone);
  1705. continue;
  1706. }
  1707. // Search for parent bone
  1708. var foundBone = false;
  1709. var parentBone = null;
  1710. for (var j = 0; j < i; j++) {
  1711. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  1712. if (!joint) {
  1713. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1714. continue;
  1715. }
  1716. var children = joint.children;
  1717. if (!children) {
  1718. continue;
  1719. }
  1720. foundBone = false;
  1721. for (var k = 0; k < children.length; k++) {
  1722. if (children[k] === id) {
  1723. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1724. foundBone = true;
  1725. break;
  1726. }
  1727. }
  1728. if (foundBone) {
  1729. break;
  1730. }
  1731. }
  1732. // Create bone
  1733. var mat = configureBoneTransformation(node);
  1734. if (!parentBone && nodesToRoot.length > 0) {
  1735. parentBone = getNodeToRoot(nodesToRoot, id);
  1736. if (parentBone) {
  1737. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1738. nodesToRootToAdd.push(parentBone);
  1739. }
  1740. }
  1741. }
  1742. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  1743. bone.id = id;
  1744. }
  1745. // Polish
  1746. var bones = newSkeleton.bones;
  1747. newSkeleton.bones = [];
  1748. for (var i = 0; i < skins.jointNames.length; i++) {
  1749. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1750. if (!jointNode) {
  1751. continue;
  1752. }
  1753. for (var j = 0; j < bones.length; j++) {
  1754. if (bones[j].id === jointNode.id) {
  1755. newSkeleton.bones.push(bones[j]);
  1756. break;
  1757. }
  1758. }
  1759. }
  1760. newSkeleton.prepare();
  1761. // Finish
  1762. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1763. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1764. }
  1765. return newSkeleton;
  1766. };
  1767. /**
  1768. * Imports a mesh and its geometries
  1769. */
  1770. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1771. if (!newMesh) {
  1772. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1773. newMesh.id = id;
  1774. }
  1775. if (!node.babylonNode) {
  1776. return newMesh;
  1777. }
  1778. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1779. if (!newMesh.material) {
  1780. newMesh.material = multiMat;
  1781. }
  1782. var vertexData = new BABYLON.VertexData();
  1783. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1784. var verticesStarts = new Array();
  1785. var verticesCounts = new Array();
  1786. var indexStarts = new Array();
  1787. var indexCounts = new Array();
  1788. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1789. var meshID = meshes[meshIndex];
  1790. var mesh = gltfRuntime.meshes[meshID];
  1791. if (!mesh) {
  1792. continue;
  1793. }
  1794. // Positions, normals and UVs
  1795. for (var i = 0; i < mesh.primitives.length; i++) {
  1796. // Temporary vertex data
  1797. var tempVertexData = new BABYLON.VertexData();
  1798. var primitive = mesh.primitives[i];
  1799. if (primitive.mode !== 4) {
  1800. // continue;
  1801. }
  1802. var attributes = primitive.attributes;
  1803. var accessor = null;
  1804. var buffer = null;
  1805. // Set positions, normal and uvs
  1806. for (var semantic in attributes) {
  1807. // Link accessor and buffer view
  1808. accessor = gltfRuntime.accessors[attributes[semantic]];
  1809. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1810. if (semantic === "NORMAL") {
  1811. tempVertexData.normals = new Float32Array(buffer.length);
  1812. tempVertexData.normals.set(buffer);
  1813. }
  1814. else if (semantic === "POSITION") {
  1815. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1816. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1817. for (var j = 0; j < buffer.length; j += 4) {
  1818. tempVertexData.positions[j] = buffer[j];
  1819. tempVertexData.positions[j + 1] = buffer[j + 1];
  1820. tempVertexData.positions[j + 2] = buffer[j + 2];
  1821. }
  1822. }
  1823. else {
  1824. tempVertexData.positions = new Float32Array(buffer.length);
  1825. tempVertexData.positions.set(buffer);
  1826. }
  1827. verticesCounts.push(tempVertexData.positions.length);
  1828. }
  1829. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1830. var channel = Number(semantic.split("_")[1]);
  1831. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1832. var uvs = new Float32Array(buffer.length);
  1833. uvs.set(buffer);
  1834. normalizeUVs(uvs);
  1835. tempVertexData.set(uvs, uvKind);
  1836. }
  1837. else if (semantic === "JOINT") {
  1838. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1839. tempVertexData.matricesIndices.set(buffer);
  1840. }
  1841. else if (semantic === "WEIGHT") {
  1842. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1843. tempVertexData.matricesWeights.set(buffer);
  1844. }
  1845. else if (semantic === "COLOR") {
  1846. tempVertexData.colors = new Float32Array(buffer.length);
  1847. tempVertexData.colors.set(buffer);
  1848. }
  1849. }
  1850. // Indices
  1851. accessor = gltfRuntime.accessors[primitive.indices];
  1852. if (accessor) {
  1853. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1854. tempVertexData.indices = new Int32Array(buffer.length);
  1855. tempVertexData.indices.set(buffer);
  1856. indexCounts.push(tempVertexData.indices.length);
  1857. }
  1858. else {
  1859. // Set indices on the fly
  1860. var indices = [];
  1861. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1862. indices.push(j);
  1863. }
  1864. tempVertexData.indices = new Int32Array(indices);
  1865. indexCounts.push(tempVertexData.indices.length);
  1866. }
  1867. vertexData.merge(tempVertexData);
  1868. tempVertexData = undefined;
  1869. // Sub material
  1870. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  1871. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  1872. // Update vertices start and index start
  1873. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1874. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1875. }
  1876. }
  1877. // Apply geometry
  1878. geometry.setAllVerticesData(vertexData, false);
  1879. newMesh.computeWorldMatrix(true);
  1880. // Apply submeshes
  1881. newMesh.subMeshes = [];
  1882. var index = 0;
  1883. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1884. var meshID = meshes[meshIndex];
  1885. var mesh = gltfRuntime.meshes[meshID];
  1886. if (!mesh) {
  1887. continue;
  1888. }
  1889. for (var i = 0; i < mesh.primitives.length; i++) {
  1890. if (mesh.primitives[i].mode !== 4) {
  1891. //continue;
  1892. }
  1893. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1894. index++;
  1895. }
  1896. }
  1897. // Finish
  1898. return newMesh;
  1899. };
  1900. /**
  1901. * Configure node transformation from position, rotation and scaling
  1902. */
  1903. var configureNode = function (newNode, position, rotation, scaling) {
  1904. if (newNode.position) {
  1905. newNode.position = position;
  1906. }
  1907. if (newNode.rotationQuaternion || newNode.rotation) {
  1908. newNode.rotationQuaternion = rotation;
  1909. }
  1910. if (newNode.scaling) {
  1911. newNode.scaling = scaling;
  1912. }
  1913. };
  1914. /**
  1915. * Configures node from transformation matrix
  1916. */
  1917. var configureNodeFromMatrix = function (newNode, node, parent) {
  1918. if (node.matrix) {
  1919. var position = new BABYLON.Vector3(0, 0, 0);
  1920. var rotation = new BABYLON.Quaternion();
  1921. var scaling = new BABYLON.Vector3(0, 0, 0);
  1922. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1923. mat.decompose(scaling, rotation, position);
  1924. configureNode(newNode, position, rotation, scaling);
  1925. }
  1926. else {
  1927. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1928. }
  1929. newNode.computeWorldMatrix(true);
  1930. };
  1931. /**
  1932. * Imports a node
  1933. */
  1934. var importNode = function (gltfRuntime, node, id, parent) {
  1935. var lastNode = null;
  1936. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1937. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  1938. return null;
  1939. }
  1940. }
  1941. // Meshes
  1942. if (node.skin) {
  1943. if (node.meshes) {
  1944. var skin = gltfRuntime.skins[node.skin];
  1945. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1946. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1947. if (newMesh.skeleton === null) {
  1948. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1949. if (!skin.babylonSkeleton) {
  1950. skin.babylonSkeleton = newMesh.skeleton;
  1951. }
  1952. }
  1953. lastNode = newMesh;
  1954. }
  1955. }
  1956. else if (node.meshes) {
  1957. /**
  1958. * Improve meshes property
  1959. */
  1960. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1961. lastNode = newMesh;
  1962. }
  1963. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1964. var light = gltfRuntime.lights[node.light];
  1965. if (light) {
  1966. if (light.type === "ambient") {
  1967. var ambienLight = light[light.type];
  1968. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1969. hemiLight.name = node.name;
  1970. if (ambienLight.color) {
  1971. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1972. }
  1973. lastNode = hemiLight;
  1974. }
  1975. else if (light.type === "directional") {
  1976. var directionalLight = light[light.type];
  1977. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1978. dirLight.name = node.name;
  1979. if (directionalLight.color) {
  1980. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1981. }
  1982. lastNode = dirLight;
  1983. }
  1984. else if (light.type === "point") {
  1985. var pointLight = light[light.type];
  1986. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1987. ptLight.name = node.name;
  1988. if (pointLight.color) {
  1989. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1990. }
  1991. lastNode = ptLight;
  1992. }
  1993. else if (light.type === "spot") {
  1994. var spotLight = light[light.type];
  1995. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1996. spLight.name = node.name;
  1997. if (spotLight.color) {
  1998. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1999. }
  2000. if (spotLight.fallOfAngle) {
  2001. spLight.angle = spotLight.fallOfAngle;
  2002. }
  2003. if (spotLight.fallOffExponent) {
  2004. spLight.exponent = spotLight.fallOffExponent;
  2005. }
  2006. lastNode = spLight;
  2007. }
  2008. }
  2009. }
  2010. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2011. var camera = gltfRuntime.cameras[node.camera];
  2012. if (camera) {
  2013. if (camera.type === "orthographic") {
  2014. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2015. orthoCamera.name = node.name;
  2016. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2017. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2018. lastNode = orthoCamera;
  2019. }
  2020. else if (camera.type === "perspective") {
  2021. var perspectiveCamera = camera[camera.type];
  2022. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2023. persCamera.name = node.name;
  2024. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2025. if (!perspectiveCamera.aspectRatio) {
  2026. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2027. }
  2028. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2029. persCamera.maxZ = perspectiveCamera.zfar;
  2030. persCamera.minZ = perspectiveCamera.znear;
  2031. }
  2032. lastNode = persCamera;
  2033. }
  2034. }
  2035. }
  2036. // Empty node
  2037. if (!node.jointName) {
  2038. if (node.babylonNode) {
  2039. return node.babylonNode;
  2040. }
  2041. else if (lastNode === null) {
  2042. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  2043. node.babylonNode = dummy;
  2044. lastNode = dummy;
  2045. }
  2046. }
  2047. if (lastNode !== null) {
  2048. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2049. configureNodeFromMatrix(lastNode, node, parent);
  2050. }
  2051. else {
  2052. var translation = node.translation || [0, 0, 0];
  2053. var rotation = node.rotation || [0, 0, 0, 1];
  2054. var scale = node.scale || [1, 1, 1];
  2055. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2056. }
  2057. lastNode.updateCache(true);
  2058. node.babylonNode = lastNode;
  2059. }
  2060. return lastNode;
  2061. };
  2062. /**
  2063. * Traverses nodes and creates them
  2064. */
  2065. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2066. var node = gltfRuntime.nodes[id];
  2067. var newNode = null;
  2068. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  2069. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2070. meshIncluded = true;
  2071. }
  2072. else {
  2073. meshIncluded = false;
  2074. }
  2075. }
  2076. else {
  2077. meshIncluded = true;
  2078. }
  2079. if (!node.jointName && meshIncluded) {
  2080. newNode = importNode(gltfRuntime, node, id, parent);
  2081. if (newNode !== null) {
  2082. newNode.id = id;
  2083. newNode.parent = parent;
  2084. }
  2085. }
  2086. if (node.children) {
  2087. for (var i = 0; i < node.children.length; i++) {
  2088. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2089. }
  2090. }
  2091. };
  2092. /**
  2093. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2094. */
  2095. var postLoad = function (gltfRuntime) {
  2096. // Nodes
  2097. var currentScene = gltfRuntime.currentScene;
  2098. if (currentScene) {
  2099. for (var i = 0; i < currentScene.nodes.length; i++) {
  2100. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2101. }
  2102. }
  2103. else {
  2104. for (var thing in gltfRuntime.scenes) {
  2105. currentScene = gltfRuntime.scenes[thing];
  2106. for (var i = 0; i < currentScene.nodes.length; i++) {
  2107. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2108. }
  2109. }
  2110. }
  2111. // Set animations
  2112. loadAnimations(gltfRuntime);
  2113. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2114. var skeleton = gltfRuntime.scene.skeletons[i];
  2115. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2116. }
  2117. };
  2118. /**
  2119. * onBind shaderrs callback to set uniforms and matrices
  2120. */
  2121. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2122. var materialValues = material.values || technique.parameters;
  2123. for (var unif in unTreatedUniforms) {
  2124. var uniform = unTreatedUniforms[unif];
  2125. var type = uniform.type;
  2126. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2127. if (uniform.semantic && !uniform.source && !uniform.node) {
  2128. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2129. }
  2130. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2131. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  2132. if (source === null) {
  2133. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  2134. }
  2135. if (source === null) {
  2136. continue;
  2137. }
  2138. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2139. }
  2140. }
  2141. else {
  2142. var value = materialValues[technique.uniforms[unif]];
  2143. if (!value) {
  2144. continue;
  2145. }
  2146. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2147. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2148. if (texture === null || texture === undefined) {
  2149. continue;
  2150. }
  2151. shaderMaterial.getEffect().setTexture(unif, texture);
  2152. }
  2153. else {
  2154. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  2155. }
  2156. }
  2157. }
  2158. onSuccess(shaderMaterial);
  2159. };
  2160. /**
  2161. * Prepare uniforms to send the only one time
  2162. * Loads the appropriate textures
  2163. */
  2164. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2165. var materialValues = material.values || technique.parameters;
  2166. var techniqueUniforms = technique.uniforms;
  2167. /**
  2168. * Prepare values here (not matrices)
  2169. */
  2170. for (var unif in unTreatedUniforms) {
  2171. var uniform = unTreatedUniforms[unif];
  2172. var type = uniform.type;
  2173. var value = materialValues[techniqueUniforms[unif]];
  2174. if (value === undefined) {
  2175. // In case the value is the same for all materials
  2176. value = uniform.value;
  2177. }
  2178. if (!value) {
  2179. continue;
  2180. }
  2181. var onLoadTexture = function (uniformName) {
  2182. return function (texture) {
  2183. if (uniform.value) {
  2184. // Static uniform
  2185. shaderMaterial.setTexture(uniformName, texture);
  2186. delete unTreatedUniforms[uniformName];
  2187. }
  2188. };
  2189. };
  2190. // Texture (sampler2D)
  2191. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2192. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2193. }
  2194. else {
  2195. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2196. // Static uniform
  2197. delete unTreatedUniforms[unif];
  2198. }
  2199. }
  2200. }
  2201. };
  2202. /**
  2203. * Shader compilation failed
  2204. */
  2205. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2206. return function (effect, error) {
  2207. shaderMaterial.dispose(true);
  2208. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2209. };
  2210. };
  2211. /**
  2212. * Shader compilation success
  2213. */
  2214. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2215. return function (_) {
  2216. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2217. shaderMaterial.onBind = function (mesh) {
  2218. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2219. };
  2220. };
  2221. };
  2222. /**
  2223. * Returns the appropriate uniform if already handled by babylon
  2224. */
  2225. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2226. for (var unif in technique.uniforms) {
  2227. var uniform = technique.uniforms[unif];
  2228. var uniformParameter = technique.parameters[uniform];
  2229. if (tokenizer.currentIdentifier === unif) {
  2230. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2231. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2232. if (transformIndex !== -1) {
  2233. delete unTreatedUniforms[unif];
  2234. return babylonTransforms[transformIndex];
  2235. }
  2236. }
  2237. }
  2238. }
  2239. return tokenizer.currentIdentifier;
  2240. };
  2241. /**
  2242. * All shaders loaded. Create materials one by one
  2243. */
  2244. var importMaterials = function (gltfRuntime) {
  2245. // Create materials
  2246. for (var mat in gltfRuntime.materials) {
  2247. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2248. }
  2249. };
  2250. /**
  2251. * Implementation of the base glTF spec
  2252. */
  2253. var GLTFLoaderBase = /** @class */ (function () {
  2254. function GLTFLoaderBase() {
  2255. }
  2256. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2257. var gltfRuntime = {
  2258. extensions: {},
  2259. accessors: {},
  2260. buffers: {},
  2261. bufferViews: {},
  2262. meshes: {},
  2263. lights: {},
  2264. cameras: {},
  2265. nodes: {},
  2266. images: {},
  2267. textures: {},
  2268. shaders: {},
  2269. programs: {},
  2270. samplers: {},
  2271. techniques: {},
  2272. materials: {},
  2273. animations: {},
  2274. skins: {},
  2275. extensionsUsed: [],
  2276. scenes: {},
  2277. buffersCount: 0,
  2278. shaderscount: 0,
  2279. scene: scene,
  2280. rootUrl: rootUrl,
  2281. loadedBufferCount: 0,
  2282. loadedBufferViews: {},
  2283. loadedShaderCount: 0,
  2284. importOnlyMeshes: false,
  2285. dummyNodes: []
  2286. };
  2287. // Parse
  2288. if (parsedData.extensions) {
  2289. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2290. }
  2291. if (parsedData.extensionsUsed) {
  2292. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2293. }
  2294. if (parsedData.buffers) {
  2295. parseBuffers(parsedData.buffers, gltfRuntime);
  2296. }
  2297. if (parsedData.bufferViews) {
  2298. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2299. }
  2300. if (parsedData.accessors) {
  2301. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2302. }
  2303. if (parsedData.meshes) {
  2304. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2305. }
  2306. if (parsedData.lights) {
  2307. parseObject(parsedData.lights, "lights", gltfRuntime);
  2308. }
  2309. if (parsedData.cameras) {
  2310. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2311. }
  2312. if (parsedData.nodes) {
  2313. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2314. }
  2315. if (parsedData.images) {
  2316. parseObject(parsedData.images, "images", gltfRuntime);
  2317. }
  2318. if (parsedData.textures) {
  2319. parseObject(parsedData.textures, "textures", gltfRuntime);
  2320. }
  2321. if (parsedData.shaders) {
  2322. parseShaders(parsedData.shaders, gltfRuntime);
  2323. }
  2324. if (parsedData.programs) {
  2325. parseObject(parsedData.programs, "programs", gltfRuntime);
  2326. }
  2327. if (parsedData.samplers) {
  2328. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2329. }
  2330. if (parsedData.techniques) {
  2331. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2332. }
  2333. if (parsedData.materials) {
  2334. parseObject(parsedData.materials, "materials", gltfRuntime);
  2335. }
  2336. if (parsedData.animations) {
  2337. parseObject(parsedData.animations, "animations", gltfRuntime);
  2338. }
  2339. if (parsedData.skins) {
  2340. parseObject(parsedData.skins, "skins", gltfRuntime);
  2341. }
  2342. if (parsedData.scenes) {
  2343. gltfRuntime.scenes = parsedData.scenes;
  2344. }
  2345. if (parsedData.scene && parsedData.scenes) {
  2346. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2347. }
  2348. return gltfRuntime;
  2349. };
  2350. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2351. var buffer = gltfRuntime.buffers[id];
  2352. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  2353. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  2354. }
  2355. else {
  2356. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  2357. onError(request.status + " " + request.statusText);
  2358. });
  2359. }
  2360. };
  2361. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2362. var texture = gltfRuntime.textures[id];
  2363. if (!texture || !texture.source) {
  2364. onError(null);
  2365. return;
  2366. }
  2367. if (texture.babylonTexture) {
  2368. onSuccess(null);
  2369. return;
  2370. }
  2371. var source = gltfRuntime.images[texture.source];
  2372. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  2373. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  2374. }
  2375. else {
  2376. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  2377. onError(request.status + " " + request.statusText);
  2378. });
  2379. }
  2380. };
  2381. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2382. var texture = gltfRuntime.textures[id];
  2383. if (texture.babylonTexture) {
  2384. onSuccess(texture.babylonTexture);
  2385. return;
  2386. }
  2387. var sampler = gltfRuntime.samplers[texture.sampler];
  2388. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2389. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2390. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2391. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2392. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2393. var blob = new Blob([buffer]);
  2394. var blobURL = URL.createObjectURL(blob);
  2395. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2396. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2397. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2398. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2399. newTexture.name = id;
  2400. texture.babylonTexture = newTexture;
  2401. onSuccess(newTexture);
  2402. };
  2403. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2404. var shader = gltfRuntime.shaders[id];
  2405. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  2406. var shaderString = atob(shader.uri.split(",")[1]);
  2407. onSuccess(shaderString);
  2408. }
  2409. else {
  2410. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  2411. onError(request.status + " " + request.statusText);
  2412. });
  2413. }
  2414. };
  2415. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2416. var material = gltfRuntime.materials[id];
  2417. var technique = gltfRuntime.techniques[material.technique];
  2418. if (!technique) {
  2419. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2420. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2421. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2422. onSuccess(defaultMaterial);
  2423. return;
  2424. }
  2425. var program = gltfRuntime.programs[technique.program];
  2426. var states = technique.states;
  2427. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2428. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2429. var newVertexShader = "";
  2430. var newPixelShader = "";
  2431. var vertexTokenizer = new Tokenizer(vertexShader);
  2432. var pixelTokenizer = new Tokenizer(pixelShader);
  2433. var unTreatedUniforms = {};
  2434. var uniforms = [];
  2435. var attributes = [];
  2436. var samplers = [];
  2437. // Fill uniform, sampler2D and attributes
  2438. for (var unif in technique.uniforms) {
  2439. var uniform = technique.uniforms[unif];
  2440. var uniformParameter = technique.parameters[uniform];
  2441. unTreatedUniforms[unif] = uniformParameter;
  2442. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2443. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2444. if (transformIndex !== -1) {
  2445. uniforms.push(babylonTransforms[transformIndex]);
  2446. delete unTreatedUniforms[unif];
  2447. }
  2448. else {
  2449. uniforms.push(unif);
  2450. }
  2451. }
  2452. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2453. samplers.push(unif);
  2454. }
  2455. else {
  2456. uniforms.push(unif);
  2457. }
  2458. }
  2459. for (var attr in technique.attributes) {
  2460. var attribute = technique.attributes[attr];
  2461. var attributeParameter = technique.parameters[attribute];
  2462. if (attributeParameter.semantic) {
  2463. attributes.push(getAttribute(attributeParameter));
  2464. }
  2465. }
  2466. // Configure vertex shader
  2467. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2468. var tokenType = vertexTokenizer.currentToken;
  2469. if (tokenType !== ETokenType.IDENTIFIER) {
  2470. newVertexShader += vertexTokenizer.currentString;
  2471. continue;
  2472. }
  2473. var foundAttribute = false;
  2474. for (var attr in technique.attributes) {
  2475. var attribute = technique.attributes[attr];
  2476. var attributeParameter = technique.parameters[attribute];
  2477. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2478. newVertexShader += getAttribute(attributeParameter);
  2479. foundAttribute = true;
  2480. break;
  2481. }
  2482. }
  2483. if (foundAttribute) {
  2484. continue;
  2485. }
  2486. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2487. }
  2488. // Configure pixel shader
  2489. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2490. var tokenType = pixelTokenizer.currentToken;
  2491. if (tokenType !== ETokenType.IDENTIFIER) {
  2492. newPixelShader += pixelTokenizer.currentString;
  2493. continue;
  2494. }
  2495. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2496. }
  2497. // Create shader material
  2498. var shaderPath = {
  2499. vertex: program.vertexShader + id,
  2500. fragment: program.fragmentShader + id
  2501. };
  2502. var options = {
  2503. attributes: attributes,
  2504. uniforms: uniforms,
  2505. samplers: samplers,
  2506. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2507. };
  2508. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2509. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2510. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2511. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2512. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2513. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2514. if (states && states.functions) {
  2515. var functions = states.functions;
  2516. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2517. shaderMaterial.backFaceCulling = false;
  2518. }
  2519. var blendFunc = functions.blendFuncSeparate;
  2520. if (blendFunc) {
  2521. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2522. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2523. }
  2524. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2525. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2526. }
  2527. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2528. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2529. }
  2530. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2531. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2532. }
  2533. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2534. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2535. }
  2536. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2537. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2538. }
  2539. }
  2540. }
  2541. };
  2542. return GLTFLoaderBase;
  2543. }());
  2544. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2545. /**
  2546. * glTF V1 Loader
  2547. */
  2548. var GLTFLoader = /** @class */ (function () {
  2549. function GLTFLoader() {
  2550. }
  2551. GLTFLoader.RegisterExtension = function (extension) {
  2552. if (GLTFLoader.Extensions[extension.name]) {
  2553. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2554. return;
  2555. }
  2556. GLTFLoader.Extensions[extension.name] = extension;
  2557. };
  2558. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2559. var _this = this;
  2560. scene.useRightHandedSystem = true;
  2561. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2562. gltfRuntime.importOnlyMeshes = true;
  2563. if (meshesNames === "") {
  2564. gltfRuntime.importMeshesNames = [];
  2565. }
  2566. else if (typeof meshesNames === "string") {
  2567. gltfRuntime.importMeshesNames = [meshesNames];
  2568. }
  2569. else if (meshesNames && !(meshesNames instanceof Array)) {
  2570. gltfRuntime.importMeshesNames = [meshesNames];
  2571. }
  2572. else {
  2573. gltfRuntime.importMeshesNames = [];
  2574. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2575. }
  2576. // Create nodes
  2577. _this._createNodes(gltfRuntime);
  2578. var meshes = new Array();
  2579. var skeletons = new Array();
  2580. // Fill arrays of meshes and skeletons
  2581. for (var nde in gltfRuntime.nodes) {
  2582. var node = gltfRuntime.nodes[nde];
  2583. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2584. meshes.push(node.babylonNode);
  2585. }
  2586. }
  2587. for (var skl in gltfRuntime.skins) {
  2588. var skin = gltfRuntime.skins[skl];
  2589. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2590. skeletons.push(skin.babylonSkeleton);
  2591. }
  2592. }
  2593. // Load buffers, shaders, materials, etc.
  2594. _this._loadBuffersAsync(gltfRuntime, function () {
  2595. _this._loadShadersAsync(gltfRuntime, function () {
  2596. importMaterials(gltfRuntime);
  2597. postLoad(gltfRuntime);
  2598. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2599. onSuccess(meshes, null, skeletons);
  2600. }
  2601. });
  2602. }, onProgress);
  2603. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2604. onSuccess(meshes, null, skeletons);
  2605. }
  2606. }, onError);
  2607. return true;
  2608. };
  2609. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2610. var _this = this;
  2611. scene.useRightHandedSystem = true;
  2612. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2613. // Load runtime extensios
  2614. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2615. // Create nodes
  2616. _this._createNodes(gltfRuntime);
  2617. // Load buffers, shaders, materials, etc.
  2618. _this._loadBuffersAsync(gltfRuntime, function () {
  2619. _this._loadShadersAsync(gltfRuntime, function () {
  2620. importMaterials(gltfRuntime);
  2621. postLoad(gltfRuntime);
  2622. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2623. onSuccess();
  2624. }
  2625. });
  2626. });
  2627. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2628. onSuccess();
  2629. }
  2630. }, onError);
  2631. }, onError);
  2632. };
  2633. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2634. var hasShaders = false;
  2635. var processShader = function (sha, shader) {
  2636. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2637. gltfRuntime.loadedShaderCount++;
  2638. if (shaderString) {
  2639. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2640. }
  2641. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2642. onload();
  2643. }
  2644. }, function () {
  2645. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2646. });
  2647. };
  2648. for (var sha in gltfRuntime.shaders) {
  2649. hasShaders = true;
  2650. var shader = gltfRuntime.shaders[sha];
  2651. if (shader) {
  2652. processShader.bind(this, sha, shader)();
  2653. }
  2654. else {
  2655. BABYLON.Tools.Error("No shader named: " + sha);
  2656. }
  2657. }
  2658. if (!hasShaders) {
  2659. onload();
  2660. }
  2661. };
  2662. ;
  2663. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2664. var hasBuffers = false;
  2665. var processBuffer = function (buf, buffer) {
  2666. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2667. gltfRuntime.loadedBufferCount++;
  2668. if (bufferView) {
  2669. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2670. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2671. }
  2672. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2673. }
  2674. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2675. onLoad();
  2676. }
  2677. }, function () {
  2678. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2679. });
  2680. };
  2681. for (var buf in gltfRuntime.buffers) {
  2682. hasBuffers = true;
  2683. var buffer = gltfRuntime.buffers[buf];
  2684. if (buffer) {
  2685. processBuffer.bind(this, buf, buffer)();
  2686. }
  2687. else {
  2688. BABYLON.Tools.Error("No buffer named: " + buf);
  2689. }
  2690. }
  2691. if (!hasBuffers) {
  2692. onLoad();
  2693. }
  2694. };
  2695. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2696. var currentScene = gltfRuntime.currentScene;
  2697. if (currentScene) {
  2698. // Only one scene even if multiple scenes are defined
  2699. for (var i = 0; i < currentScene.nodes.length; i++) {
  2700. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2701. }
  2702. }
  2703. else {
  2704. // Load all scenes
  2705. for (var thing in gltfRuntime.scenes) {
  2706. currentScene = gltfRuntime.scenes[thing];
  2707. for (var i = 0; i < currentScene.nodes.length; i++) {
  2708. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2709. }
  2710. }
  2711. }
  2712. };
  2713. GLTFLoader.Extensions = {};
  2714. return GLTFLoader;
  2715. }());
  2716. GLTF1.GLTFLoader = GLTFLoader;
  2717. ;
  2718. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2719. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2720. })(BABYLON || (BABYLON = {}));
  2721. //# sourceMappingURL=babylon.glTFLoader.js.map
  2722. var BABYLON;
  2723. (function (BABYLON) {
  2724. var GLTF1;
  2725. (function (GLTF1) {
  2726. /**
  2727. * Utils functions for GLTF
  2728. */
  2729. var GLTFUtils = /** @class */ (function () {
  2730. function GLTFUtils() {
  2731. }
  2732. /**
  2733. * Sets the given "parameter" matrix
  2734. * @param scene: the {BABYLON.Scene} object
  2735. * @param source: the source node where to pick the matrix
  2736. * @param parameter: the GLTF technique parameter
  2737. * @param uniformName: the name of the shader's uniform
  2738. * @param shaderMaterial: the shader material
  2739. */
  2740. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2741. var mat = null;
  2742. if (parameter.semantic === "MODEL") {
  2743. mat = source.getWorldMatrix();
  2744. }
  2745. else if (parameter.semantic === "PROJECTION") {
  2746. mat = scene.getProjectionMatrix();
  2747. }
  2748. else if (parameter.semantic === "VIEW") {
  2749. mat = scene.getViewMatrix();
  2750. }
  2751. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2752. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2753. }
  2754. else if (parameter.semantic === "MODELVIEW") {
  2755. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2756. }
  2757. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2758. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2759. }
  2760. else if (parameter.semantic === "MODELINVERSE") {
  2761. mat = source.getWorldMatrix().invert();
  2762. }
  2763. else if (parameter.semantic === "VIEWINVERSE") {
  2764. mat = scene.getViewMatrix().invert();
  2765. }
  2766. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2767. mat = scene.getProjectionMatrix().invert();
  2768. }
  2769. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2770. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2771. }
  2772. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2773. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2774. }
  2775. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2776. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2777. }
  2778. else {
  2779. debugger;
  2780. }
  2781. switch (parameter.type) {
  2782. case GLTF1.EParameterType.FLOAT_MAT2:
  2783. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2784. break;
  2785. case GLTF1.EParameterType.FLOAT_MAT3:
  2786. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2787. break;
  2788. case GLTF1.EParameterType.FLOAT_MAT4:
  2789. shaderMaterial.setMatrix(uniformName, mat);
  2790. break;
  2791. default: break;
  2792. }
  2793. };
  2794. /**
  2795. * Sets the given "parameter" matrix
  2796. * @param shaderMaterial: the shader material
  2797. * @param uniform: the name of the shader's uniform
  2798. * @param value: the value of the uniform
  2799. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2800. */
  2801. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2802. switch (type) {
  2803. case GLTF1.EParameterType.FLOAT:
  2804. shaderMaterial.setFloat(uniform, value);
  2805. return true;
  2806. case GLTF1.EParameterType.FLOAT_VEC2:
  2807. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2808. return true;
  2809. case GLTF1.EParameterType.FLOAT_VEC3:
  2810. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2811. return true;
  2812. case GLTF1.EParameterType.FLOAT_VEC4:
  2813. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2814. return true;
  2815. default: return false;
  2816. }
  2817. };
  2818. /**
  2819. * If the uri is a base64 string
  2820. * @param uri: the uri to test
  2821. */
  2822. GLTFUtils.IsBase64 = function (uri) {
  2823. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2824. };
  2825. /**
  2826. * Decode the base64 uri
  2827. * @param uri: the uri to decode
  2828. */
  2829. GLTFUtils.DecodeBase64 = function (uri) {
  2830. var decodedString = atob(uri.split(",")[1]);
  2831. var bufferLength = decodedString.length;
  2832. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2833. for (var i = 0; i < bufferLength; i++) {
  2834. bufferView[i] = decodedString.charCodeAt(i);
  2835. }
  2836. return bufferView.buffer;
  2837. };
  2838. /**
  2839. * Returns the wrap mode of the texture
  2840. * @param mode: the mode value
  2841. */
  2842. GLTFUtils.GetWrapMode = function (mode) {
  2843. switch (mode) {
  2844. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2845. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2846. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2847. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2848. }
  2849. };
  2850. /**
  2851. * Returns the byte stride giving an accessor
  2852. * @param accessor: the GLTF accessor objet
  2853. */
  2854. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2855. // Needs this function since "byteStride" isn't requiered in glTF format
  2856. var type = accessor.type;
  2857. switch (type) {
  2858. case "VEC2": return 2;
  2859. case "VEC3": return 3;
  2860. case "VEC4": return 4;
  2861. case "MAT2": return 4;
  2862. case "MAT3": return 9;
  2863. case "MAT4": return 16;
  2864. default: return 1;
  2865. }
  2866. };
  2867. /**
  2868. * Returns the texture filter mode giving a mode value
  2869. * @param mode: the filter mode value
  2870. */
  2871. GLTFUtils.GetTextureFilterMode = function (mode) {
  2872. switch (mode) {
  2873. case GLTF1.ETextureFilterType.LINEAR:
  2874. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2875. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2876. case GLTF1.ETextureFilterType.NEAREST:
  2877. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2878. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2879. }
  2880. };
  2881. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2882. var byteOffset = bufferView.byteOffset + byteOffset;
  2883. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2884. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2885. throw new Error("Buffer access is out of range");
  2886. }
  2887. var buffer = loadedBufferView.buffer;
  2888. byteOffset += loadedBufferView.byteOffset;
  2889. switch (componentType) {
  2890. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2891. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2892. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2893. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2894. default: return new Float32Array(buffer, byteOffset, byteLength);
  2895. }
  2896. };
  2897. /**
  2898. * Returns a buffer from its accessor
  2899. * @param gltfRuntime: the GLTF runtime
  2900. * @param accessor: the GLTF accessor
  2901. */
  2902. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2903. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2904. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2905. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2906. };
  2907. /**
  2908. * Decodes a buffer view into a string
  2909. * @param view: the buffer view
  2910. */
  2911. GLTFUtils.DecodeBufferToText = function (view) {
  2912. var result = "";
  2913. var length = view.byteLength;
  2914. for (var i = 0; i < length; ++i) {
  2915. result += String.fromCharCode(view[i]);
  2916. }
  2917. return result;
  2918. };
  2919. /**
  2920. * Returns the default material of gltf. Related to
  2921. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2922. * @param scene: the Babylon.js scene
  2923. */
  2924. GLTFUtils.GetDefaultMaterial = function (scene) {
  2925. if (!GLTFUtils._DefaultMaterial) {
  2926. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2927. "precision highp float;",
  2928. "",
  2929. "uniform mat4 worldView;",
  2930. "uniform mat4 projection;",
  2931. "",
  2932. "attribute vec3 position;",
  2933. "",
  2934. "void main(void)",
  2935. "{",
  2936. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2937. "}"
  2938. ].join("\n");
  2939. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2940. "precision highp float;",
  2941. "",
  2942. "uniform vec4 u_emission;",
  2943. "",
  2944. "void main(void)",
  2945. "{",
  2946. " gl_FragColor = u_emission;",
  2947. "}"
  2948. ].join("\n");
  2949. var shaderPath = {
  2950. vertex: "GLTFDefaultMaterial",
  2951. fragment: "GLTFDefaultMaterial"
  2952. };
  2953. var options = {
  2954. attributes: ["position"],
  2955. uniforms: ["worldView", "projection", "u_emission"],
  2956. samplers: new Array(),
  2957. needAlphaBlending: false
  2958. };
  2959. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2960. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2961. }
  2962. return GLTFUtils._DefaultMaterial;
  2963. };
  2964. // The GLTF default material
  2965. GLTFUtils._DefaultMaterial = null;
  2966. return GLTFUtils;
  2967. }());
  2968. GLTF1.GLTFUtils = GLTFUtils;
  2969. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2970. })(BABYLON || (BABYLON = {}));
  2971. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2972. var BABYLON;
  2973. (function (BABYLON) {
  2974. var GLTF1;
  2975. (function (GLTF1) {
  2976. var GLTFLoaderExtension = /** @class */ (function () {
  2977. function GLTFLoaderExtension(name) {
  2978. this._name = name;
  2979. }
  2980. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2981. get: function () {
  2982. return this._name;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. /**
  2988. * Defines an override for loading the runtime
  2989. * Return true to stop further extensions from loading the runtime
  2990. */
  2991. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2992. return false;
  2993. };
  2994. /**
  2995. * Defines an onverride for creating gltf runtime
  2996. * Return true to stop further extensions from creating the runtime
  2997. */
  2998. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2999. return false;
  3000. };
  3001. /**
  3002. * Defines an override for loading buffers
  3003. * Return true to stop further extensions from loading this buffer
  3004. */
  3005. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3006. return false;
  3007. };
  3008. /**
  3009. * Defines an override for loading texture buffers
  3010. * Return true to stop further extensions from loading this texture data
  3011. */
  3012. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3013. return false;
  3014. };
  3015. /**
  3016. * Defines an override for creating textures
  3017. * Return true to stop further extensions from loading this texture
  3018. */
  3019. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3020. return false;
  3021. };
  3022. /**
  3023. * Defines an override for loading shader strings
  3024. * Return true to stop further extensions from loading this shader data
  3025. */
  3026. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3027. return false;
  3028. };
  3029. /**
  3030. * Defines an override for loading materials
  3031. * Return true to stop further extensions from loading this material
  3032. */
  3033. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3034. return false;
  3035. };
  3036. // ---------
  3037. // Utilities
  3038. // ---------
  3039. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3040. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3041. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3042. }, function () {
  3043. setTimeout(function () {
  3044. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3045. });
  3046. });
  3047. };
  3048. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3049. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3050. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3051. }, function () {
  3052. setTimeout(function () {
  3053. onSuccess();
  3054. });
  3055. });
  3056. };
  3057. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3058. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3059. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3060. }, function () {
  3061. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3062. });
  3063. };
  3064. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3065. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  3066. };
  3067. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3068. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3069. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3070. }, function () {
  3071. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3072. });
  3073. };
  3074. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3075. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3076. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3077. }, function () {
  3078. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3079. });
  3080. };
  3081. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3082. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3083. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3084. }, function () {
  3085. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3086. });
  3087. };
  3088. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3089. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3090. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3091. }, function () {
  3092. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3093. });
  3094. };
  3095. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3096. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3097. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3098. if (func(loaderExtension)) {
  3099. return;
  3100. }
  3101. }
  3102. defaultFunc();
  3103. };
  3104. return GLTFLoaderExtension;
  3105. }());
  3106. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3107. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3108. })(BABYLON || (BABYLON = {}));
  3109. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3110. var BABYLON;
  3111. (function (BABYLON) {
  3112. var GLTF1;
  3113. (function (GLTF1) {
  3114. var BinaryExtensionBufferName = "binary_glTF";
  3115. ;
  3116. ;
  3117. var GLTFBinaryExtension = /** @class */ (function (_super) {
  3118. __extends(GLTFBinaryExtension, _super);
  3119. function GLTFBinaryExtension() {
  3120. return _super.call(this, "KHR_binary_glTF") || this;
  3121. }
  3122. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3123. var extensionsUsed = data.json.extensionsUsed;
  3124. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  3125. return false;
  3126. }
  3127. this._bin = data.bin;
  3128. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3129. return true;
  3130. };
  3131. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3132. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3133. return false;
  3134. }
  3135. if (id !== BinaryExtensionBufferName) {
  3136. return false;
  3137. }
  3138. onSuccess(this._bin);
  3139. return true;
  3140. };
  3141. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3142. var texture = gltfRuntime.textures[id];
  3143. var source = gltfRuntime.images[texture.source];
  3144. if (!source.extensions || !(this.name in source.extensions)) {
  3145. return false;
  3146. }
  3147. var sourceExt = source.extensions[this.name];
  3148. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3149. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3150. onSuccess(buffer);
  3151. return true;
  3152. };
  3153. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3154. var shader = gltfRuntime.shaders[id];
  3155. if (!shader.extensions || !(this.name in shader.extensions)) {
  3156. return false;
  3157. }
  3158. var binaryExtensionShader = shader.extensions[this.name];
  3159. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3160. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3161. setTimeout(function () {
  3162. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3163. onSuccess(shaderString);
  3164. });
  3165. return true;
  3166. };
  3167. return GLTFBinaryExtension;
  3168. }(GLTF1.GLTFLoaderExtension));
  3169. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3170. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3171. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3172. })(BABYLON || (BABYLON = {}));
  3173. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3174. var BABYLON;
  3175. (function (BABYLON) {
  3176. var GLTF1;
  3177. (function (GLTF1) {
  3178. ;
  3179. ;
  3180. ;
  3181. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3182. __extends(GLTFMaterialsCommonExtension, _super);
  3183. function GLTFMaterialsCommonExtension() {
  3184. return _super.call(this, "KHR_materials_common") || this;
  3185. }
  3186. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3187. if (!gltfRuntime.extensions)
  3188. return false;
  3189. var extension = gltfRuntime.extensions[this.name];
  3190. if (!extension)
  3191. return false;
  3192. // Create lights
  3193. var lights = extension.lights;
  3194. if (lights) {
  3195. for (var thing in lights) {
  3196. var light = lights[thing];
  3197. switch (light.type) {
  3198. case "ambient":
  3199. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3200. var ambient = light.ambient;
  3201. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3202. break;
  3203. case "point":
  3204. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3205. var point = light.point;
  3206. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3207. break;
  3208. case "directional":
  3209. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3210. var directional = light.directional;
  3211. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3212. break;
  3213. case "spot":
  3214. var spot = light.spot;
  3215. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  3216. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3217. break;
  3218. default:
  3219. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3220. break;
  3221. }
  3222. }
  3223. }
  3224. return false;
  3225. };
  3226. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3227. var material = gltfRuntime.materials[id];
  3228. if (!material || !material.extensions)
  3229. return false;
  3230. var extension = material.extensions[this.name];
  3231. if (!extension)
  3232. return false;
  3233. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3234. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3235. if (extension.technique === "CONSTANT") {
  3236. standardMaterial.disableLighting = true;
  3237. }
  3238. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3239. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3240. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3241. // Ambient
  3242. if (typeof extension.values.ambient === "string") {
  3243. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3244. }
  3245. else {
  3246. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3247. }
  3248. // Diffuse
  3249. if (typeof extension.values.diffuse === "string") {
  3250. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3251. }
  3252. else {
  3253. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3254. }
  3255. // Emission
  3256. if (typeof extension.values.emission === "string") {
  3257. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3258. }
  3259. else {
  3260. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3261. }
  3262. // Specular
  3263. if (typeof extension.values.specular === "string") {
  3264. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3265. }
  3266. else {
  3267. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3268. }
  3269. return true;
  3270. };
  3271. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3272. // Create buffer from texture url
  3273. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3274. // Create texture from buffer
  3275. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3276. }, onError);
  3277. };
  3278. return GLTFMaterialsCommonExtension;
  3279. }(GLTF1.GLTFLoaderExtension));
  3280. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3281. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3282. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3283. })(BABYLON || (BABYLON = {}));
  3284. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3285. var BABYLON;
  3286. (function (BABYLON) {
  3287. var GLTF2;
  3288. (function (GLTF2) {
  3289. /**
  3290. * Enums
  3291. */
  3292. var EComponentType;
  3293. (function (EComponentType) {
  3294. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  3295. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  3296. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  3297. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  3298. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  3299. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  3300. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  3301. var EMeshPrimitiveMode;
  3302. (function (EMeshPrimitiveMode) {
  3303. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  3304. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  3305. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  3306. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  3307. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  3308. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  3309. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  3310. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  3311. var ETextureMagFilter;
  3312. (function (ETextureMagFilter) {
  3313. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  3314. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  3315. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  3316. var ETextureMinFilter;
  3317. (function (ETextureMinFilter) {
  3318. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  3319. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  3320. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  3321. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  3322. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  3323. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  3324. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  3325. var ETextureWrapMode;
  3326. (function (ETextureWrapMode) {
  3327. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  3328. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  3329. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  3330. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  3331. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3332. })(BABYLON || (BABYLON = {}));
  3333. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3334. var BABYLON;
  3335. (function (BABYLON) {
  3336. var GLTF2;
  3337. (function (GLTF2) {
  3338. var GLTFLoaderTracker = /** @class */ (function () {
  3339. function GLTFLoaderTracker(onComplete) {
  3340. this._pendingCount = 0;
  3341. this._callback = onComplete;
  3342. }
  3343. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  3344. this._pendingCount++;
  3345. };
  3346. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  3347. if (--this._pendingCount === 0) {
  3348. this._callback();
  3349. }
  3350. };
  3351. return GLTFLoaderTracker;
  3352. }());
  3353. var GLTFLoader = /** @class */ (function () {
  3354. function GLTFLoader(parent) {
  3355. this._renderReady = false;
  3356. this._disposed = false;
  3357. this._renderReadyObservable = new BABYLON.Observable();
  3358. // Count of pending work that needs to complete before the asset is rendered.
  3359. this._renderPendingCount = 0;
  3360. // Count of pending work that needs to complete before the loader is disposed.
  3361. this._loaderPendingCount = 0;
  3362. this._loaderTrackers = new Array();
  3363. this._parent = parent;
  3364. }
  3365. GLTFLoader.RegisterExtension = function (extension) {
  3366. if (GLTFLoader.Extensions[extension.name]) {
  3367. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  3368. return;
  3369. }
  3370. GLTFLoader.Extensions[extension.name] = extension;
  3371. // Keep the order of registration so that extensions registered first are called first.
  3372. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  3373. };
  3374. GLTFLoader.prototype.dispose = function () {
  3375. if (this._disposed) {
  3376. return;
  3377. }
  3378. this._disposed = true;
  3379. // Revoke object urls created during load
  3380. if (this._gltf.textures) {
  3381. this._gltf.textures.forEach(function (texture) {
  3382. if (texture.url) {
  3383. URL.revokeObjectURL(texture.url);
  3384. }
  3385. });
  3386. }
  3387. this._gltf = undefined;
  3388. this._babylonScene = undefined;
  3389. this._rootUrl = undefined;
  3390. this._defaultMaterial = undefined;
  3391. this._successCallback = undefined;
  3392. this._errorCallback = undefined;
  3393. this._renderReady = false;
  3394. this._renderReadyObservable.clear();
  3395. this._renderPendingCount = 0;
  3396. this._loaderPendingCount = 0;
  3397. };
  3398. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3399. var _this = this;
  3400. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  3401. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  3402. }, onProgress, onError);
  3403. };
  3404. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  3405. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  3406. };
  3407. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3408. var _this = this;
  3409. this._tryCatchOnError(function () {
  3410. _this._loadData(data);
  3411. _this._babylonScene = scene;
  3412. _this._rootUrl = rootUrl;
  3413. _this._successCallback = onSuccess;
  3414. _this._progressCallback = onProgress;
  3415. _this._errorCallback = onError;
  3416. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  3417. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  3418. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  3419. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  3420. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  3421. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  3422. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  3423. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  3424. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  3425. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  3426. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  3427. _this._addPendingData(_this);
  3428. _this._loadDefaultScene(nodeNames);
  3429. _this._loadAnimations();
  3430. _this._removePendingData(_this);
  3431. });
  3432. };
  3433. GLTFLoader.prototype._onError = function (message) {
  3434. if (this._disposed) {
  3435. return;
  3436. }
  3437. BABYLON.Tools.Error("glTF Loader: " + message);
  3438. if (this._errorCallback) {
  3439. this._errorCallback(message);
  3440. }
  3441. this.dispose();
  3442. };
  3443. GLTFLoader.prototype._onProgress = function (event) {
  3444. if (this._disposed) {
  3445. return;
  3446. }
  3447. if (this._progressCallback) {
  3448. this._progressCallback(event);
  3449. }
  3450. };
  3451. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  3452. if (this._renderReady) {
  3453. func();
  3454. }
  3455. else {
  3456. this._renderReadyObservable.add(func);
  3457. }
  3458. };
  3459. GLTFLoader.prototype._onRenderReady = function () {
  3460. this._rootNode.babylonMesh.setEnabled(true);
  3461. this._startAnimations();
  3462. this._successCallback();
  3463. this._renderReadyObservable.notifyObservers(this);
  3464. if (this._parent.onReady) {
  3465. this._parent.onReady();
  3466. }
  3467. };
  3468. GLTFLoader.prototype._onComplete = function () {
  3469. if (this._parent.onComplete) {
  3470. this._parent.onComplete();
  3471. }
  3472. this.dispose();
  3473. };
  3474. GLTFLoader.prototype._loadData = function (data) {
  3475. this._gltf = data.json;
  3476. if (data.bin) {
  3477. var buffers = this._gltf.buffers;
  3478. if (buffers && buffers[0] && !buffers[0].uri) {
  3479. var binaryBuffer = buffers[0];
  3480. if (binaryBuffer.byteLength != data.bin.byteLength) {
  3481. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3482. }
  3483. binaryBuffer.loadedData = data.bin;
  3484. }
  3485. else {
  3486. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3487. }
  3488. }
  3489. };
  3490. GLTFLoader.prototype._getMeshes = function () {
  3491. var meshes = [this._rootNode.babylonMesh];
  3492. var nodes = this._gltf.nodes;
  3493. if (nodes) {
  3494. nodes.forEach(function (node) {
  3495. if (node.babylonMesh) {
  3496. meshes.push(node.babylonMesh);
  3497. }
  3498. });
  3499. }
  3500. return meshes;
  3501. };
  3502. GLTFLoader.prototype._getSkeletons = function () {
  3503. var skeletons = new Array();
  3504. var skins = this._gltf.skins;
  3505. if (skins) {
  3506. skins.forEach(function (skin) {
  3507. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3508. skeletons.push(skin.babylonSkeleton);
  3509. }
  3510. });
  3511. }
  3512. return skeletons;
  3513. };
  3514. GLTFLoader.prototype._getAnimationTargets = function () {
  3515. var targets = new Array();
  3516. var animations = this._gltf.animations;
  3517. if (animations) {
  3518. animations.forEach(function (animation) {
  3519. targets.push.apply(targets, animation.targets);
  3520. });
  3521. }
  3522. return targets;
  3523. };
  3524. GLTFLoader.prototype._startAnimations = function () {
  3525. var _this = this;
  3526. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  3527. };
  3528. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  3529. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  3530. if (!scene) {
  3531. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  3532. }
  3533. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  3534. };
  3535. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  3536. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  3537. switch (this._parent.coordinateSystemMode) {
  3538. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  3539. if (!this._babylonScene.useRightHandedSystem) {
  3540. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  3541. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  3542. }
  3543. break;
  3544. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  3545. // do nothing
  3546. break;
  3547. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  3548. this._babylonScene.useRightHandedSystem = true;
  3549. break;
  3550. default:
  3551. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  3552. return;
  3553. }
  3554. var nodeIndices = scene.nodes;
  3555. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  3556. node.parent = parentNode;
  3557. return true;
  3558. }, this._rootNode);
  3559. if (nodeNames) {
  3560. if (!(nodeNames instanceof Array)) {
  3561. nodeNames = [nodeNames];
  3562. }
  3563. var filteredNodeIndices = new Array();
  3564. this._traverseNodes(context, nodeIndices, function (node) {
  3565. if (nodeNames.indexOf(node.name) !== -1) {
  3566. filteredNodeIndices.push(node.index);
  3567. return false;
  3568. }
  3569. return true;
  3570. }, this._rootNode);
  3571. nodeIndices = filteredNodeIndices;
  3572. }
  3573. for (var i = 0; i < nodeIndices.length; i++) {
  3574. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  3575. if (!node) {
  3576. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  3577. }
  3578. this._loadNode("#/nodes/" + nodeIndices[i], node);
  3579. }
  3580. // Disable the root mesh until the asset is ready to render.
  3581. this._rootNode.babylonMesh.setEnabled(false);
  3582. };
  3583. GLTFLoader.prototype._loadNode = function (context, node) {
  3584. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  3585. return;
  3586. }
  3587. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  3588. this._loadTransform(node);
  3589. if (node.mesh != null) {
  3590. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  3591. if (!mesh) {
  3592. throw new Error(context + ": Failed to find mesh " + node.mesh);
  3593. }
  3594. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  3595. }
  3596. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  3597. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  3598. node.babylonAnimationTargets.push(node.babylonMesh);
  3599. if (node.skin != null) {
  3600. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  3601. if (!skin) {
  3602. throw new Error(context + ": Failed to find skin " + node.skin);
  3603. }
  3604. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  3605. }
  3606. if (node.camera != null) {
  3607. // TODO: handle cameras
  3608. }
  3609. if (node.children) {
  3610. for (var i = 0; i < node.children.length; i++) {
  3611. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  3612. if (!childNode) {
  3613. throw new Error(context + ": Failed to find child node " + node.children[i]);
  3614. }
  3615. this._loadNode("#/nodes/" + node.children[i], childNode);
  3616. }
  3617. }
  3618. };
  3619. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  3620. var _this = this;
  3621. node.babylonMesh.name = node.babylonMesh.name || mesh.name;
  3622. if (!mesh.primitives || mesh.primitives.length === 0) {
  3623. throw new Error(context + ": Primitives are missing");
  3624. }
  3625. this._createMorphTargets(context, node, mesh);
  3626. this._loadAllVertexDataAsync(context, mesh, function () {
  3627. _this._loadMorphTargets(context, node, mesh);
  3628. var primitives = mesh.primitives;
  3629. var vertexData = new BABYLON.VertexData();
  3630. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3631. var primitive = primitives_1[_i];
  3632. vertexData.merge(primitive.vertexData);
  3633. }
  3634. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  3635. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  3636. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  3637. node.babylonMesh.subMeshes = [];
  3638. var verticesStart = 0;
  3639. var indicesStart = 0;
  3640. for (var index = 0; index < primitives.length; index++) {
  3641. var vertexData = primitives[index].vertexData;
  3642. var verticesCount = vertexData.positions.length;
  3643. var indicesCount = vertexData.indices.length;
  3644. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  3645. verticesStart += verticesCount;
  3646. indicesStart += indicesCount;
  3647. }
  3648. ;
  3649. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, _this._babylonScene);
  3650. node.babylonMesh.material = multiMaterial;
  3651. var subMaterials = multiMaterial.subMaterials;
  3652. for (var index = 0; index < primitives.length; index++) {
  3653. var primitive = primitives[index];
  3654. if (primitive.material == null) {
  3655. subMaterials[index] = _this._getDefaultMaterial();
  3656. }
  3657. else {
  3658. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  3659. if (!material) {
  3660. throw new Error(context + ": Failed to find material " + primitive.material);
  3661. }
  3662. _this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  3663. if (isNew && _this._parent.onMaterialLoaded) {
  3664. _this._parent.onMaterialLoaded(babylonMaterial);
  3665. }
  3666. if (_this._parent.onBeforeMaterialReadyAsync) {
  3667. _this._addLoaderPendingData(material);
  3668. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  3669. subMaterials[index] = babylonMaterial;
  3670. _this._removeLoaderPendingData(material);
  3671. });
  3672. }
  3673. else {
  3674. subMaterials[index] = babylonMaterial;
  3675. }
  3676. });
  3677. }
  3678. }
  3679. ;
  3680. });
  3681. };
  3682. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  3683. var primitives = mesh.primitives;
  3684. var numRemainingPrimitives = primitives.length;
  3685. var _loop_1 = function () {
  3686. var primitive = primitives[index];
  3687. this_1._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  3688. primitive.vertexData = vertexData;
  3689. if (--numRemainingPrimitives === 0) {
  3690. onSuccess();
  3691. }
  3692. });
  3693. };
  3694. var this_1 = this;
  3695. for (var index = 0; index < primitives.length; index++) {
  3696. _loop_1();
  3697. }
  3698. };
  3699. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  3700. var _this = this;
  3701. var attributes = primitive.attributes;
  3702. if (!attributes) {
  3703. throw new Error(context + ": Attributes are missing");
  3704. }
  3705. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  3706. // TODO: handle other primitive modes
  3707. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3708. }
  3709. var vertexData = new BABYLON.VertexData();
  3710. var numRemainingAttributes = Object.keys(attributes).length;
  3711. var _loop_2 = function (attribute) {
  3712. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  3713. if (!accessor) {
  3714. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  3715. }
  3716. this_2._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  3717. switch (attribute) {
  3718. case "NORMAL":
  3719. vertexData.normals = data;
  3720. break;
  3721. case "POSITION":
  3722. vertexData.positions = data;
  3723. break;
  3724. case "TANGENT":
  3725. vertexData.tangents = data;
  3726. break;
  3727. case "TEXCOORD_0":
  3728. vertexData.uvs = data;
  3729. break;
  3730. case "TEXCOORD_1":
  3731. vertexData.uvs2 = data;
  3732. break;
  3733. case "JOINTS_0":
  3734. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  3735. break;
  3736. case "WEIGHTS_0":
  3737. vertexData.matricesWeights = data;
  3738. break;
  3739. case "COLOR_0":
  3740. vertexData.colors = data;
  3741. break;
  3742. default:
  3743. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  3744. break;
  3745. }
  3746. if (--numRemainingAttributes === 0) {
  3747. if (primitive.indices == null) {
  3748. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  3749. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  3750. onSuccess(vertexData);
  3751. }
  3752. else {
  3753. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  3754. if (!indicesAccessor) {
  3755. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  3756. }
  3757. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  3758. vertexData.indices = data;
  3759. onSuccess(vertexData);
  3760. });
  3761. }
  3762. }
  3763. });
  3764. };
  3765. var this_2 = this, accessor;
  3766. for (var attribute in attributes) {
  3767. _loop_2(attribute);
  3768. }
  3769. };
  3770. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  3771. var primitives = mesh.primitives;
  3772. var targets = primitives[0].targets;
  3773. if (!targets) {
  3774. return;
  3775. }
  3776. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  3777. var primitive = primitives_2[_i];
  3778. if (!primitive.targets || primitive.targets.length != targets.length) {
  3779. throw new Error(context + ": All primitives are required to list the same number of targets");
  3780. }
  3781. }
  3782. var morphTargetManager = new BABYLON.MorphTargetManager();
  3783. node.babylonMesh.morphTargetManager = morphTargetManager;
  3784. for (var index = 0; index < targets.length; index++) {
  3785. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3786. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3787. }
  3788. };
  3789. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  3790. var morphTargetManager = node.babylonMesh.morphTargetManager;
  3791. if (!morphTargetManager) {
  3792. return;
  3793. }
  3794. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  3795. var numTargets = morphTargetManager.numTargets;
  3796. for (var index = 0; index < numTargets; index++) {
  3797. var vertexData = new BABYLON.VertexData();
  3798. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  3799. var primitive = _a[_i];
  3800. vertexData.merge(primitive.targetsVertexData[index]);
  3801. }
  3802. var target = morphTargetManager.getTarget(index);
  3803. target.setNormals(vertexData.normals);
  3804. target.setPositions(vertexData.positions);
  3805. target.setTangents(vertexData.tangents);
  3806. }
  3807. });
  3808. };
  3809. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  3810. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  3811. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  3812. var primitive = _a[_i];
  3813. var targets = primitive.targets;
  3814. primitive.targetsVertexData = new Array(targets.length);
  3815. var _loop_3 = function (index) {
  3816. this_3._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  3817. primitive.targetsVertexData[index] = vertexData;
  3818. if (--numRemainingTargets === 0) {
  3819. onSuccess();
  3820. }
  3821. });
  3822. };
  3823. var this_3 = this;
  3824. for (var index = 0; index < targets.length; index++) {
  3825. _loop_3(index);
  3826. }
  3827. }
  3828. };
  3829. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  3830. var targetVertexData = new BABYLON.VertexData();
  3831. var numRemainingAttributes = Object.keys(attributes).length;
  3832. var _loop_4 = function (attribute) {
  3833. accessor = GLTF2.GLTFUtils.GetArrayItem(this_4._gltf.accessors, attributes[attribute]);
  3834. if (!accessor) {
  3835. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  3836. }
  3837. this_4._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  3838. // glTF stores morph target information as deltas while babylon.js expects the final data.
  3839. // As a result we have to add the original data to the delta to calculate the final data.
  3840. var values = data;
  3841. switch (attribute) {
  3842. case "NORMAL":
  3843. for (var i = 0; i < values.length; i++) {
  3844. values[i] += vertexData.normals[i];
  3845. }
  3846. targetVertexData.normals = values;
  3847. break;
  3848. case "POSITION":
  3849. for (var i = 0; i < values.length; i++) {
  3850. values[i] += vertexData.positions[i];
  3851. }
  3852. targetVertexData.positions = values;
  3853. break;
  3854. case "TANGENT":
  3855. // Tangent data for morph targets is stored as xyz delta.
  3856. // The vertexData.tangent is stored as xyzw.
  3857. // So we need to skip every fourth vertexData.tangent.
  3858. for (var i = 0, j = 0; i < values.length; i++, j++) {
  3859. values[i] += vertexData.tangents[j];
  3860. if ((i + 1) % 3 == 0) {
  3861. j++;
  3862. }
  3863. }
  3864. targetVertexData.tangents = values;
  3865. break;
  3866. default:
  3867. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  3868. break;
  3869. }
  3870. if (--numRemainingAttributes === 0) {
  3871. onSuccess(targetVertexData);
  3872. }
  3873. });
  3874. };
  3875. var this_4 = this, accessor;
  3876. for (var attribute in attributes) {
  3877. _loop_4(attribute);
  3878. }
  3879. };
  3880. GLTFLoader.prototype._loadTransform = function (node) {
  3881. var position = BABYLON.Vector3.Zero();
  3882. var rotation = BABYLON.Quaternion.Identity();
  3883. var scaling = BABYLON.Vector3.One();
  3884. if (node.matrix) {
  3885. var mat = BABYLON.Matrix.FromArray(node.matrix);
  3886. mat.decompose(scaling, rotation, position);
  3887. }
  3888. else {
  3889. if (node.translation)
  3890. position = BABYLON.Vector3.FromArray(node.translation);
  3891. if (node.rotation)
  3892. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3893. if (node.scale)
  3894. scaling = BABYLON.Vector3.FromArray(node.scale);
  3895. }
  3896. node.babylonMesh.position = position;
  3897. node.babylonMesh.rotationQuaternion = rotation;
  3898. node.babylonMesh.scaling = scaling;
  3899. };
  3900. GLTFLoader.prototype._loadSkin = function (context, skin) {
  3901. var _this = this;
  3902. var skeletonId = "skeleton" + skin.index;
  3903. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  3904. if (skin.inverseBindMatrices == null) {
  3905. this._loadBones(context, skin, null);
  3906. }
  3907. else {
  3908. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  3909. if (!accessor) {
  3910. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  3911. }
  3912. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  3913. _this._loadBones(context, skin, data);
  3914. });
  3915. }
  3916. return skin.babylonSkeleton;
  3917. };
  3918. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3919. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3920. node.babylonBones = node.babylonBones || {};
  3921. node.babylonBones[skin.index] = babylonBone;
  3922. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  3923. node.babylonAnimationTargets.push(babylonBone);
  3924. return babylonBone;
  3925. };
  3926. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  3927. var babylonBones = {};
  3928. for (var i = 0; i < skin.joints.length; i++) {
  3929. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  3930. if (!node) {
  3931. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  3932. }
  3933. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  3934. }
  3935. };
  3936. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  3937. var babylonBone = babylonBones[node.index];
  3938. if (babylonBone) {
  3939. return babylonBone;
  3940. }
  3941. var boneIndex = skin.joints.indexOf(node.index);
  3942. var baseMatrix = BABYLON.Matrix.Identity();
  3943. if (inverseBindMatrixData && boneIndex !== -1) {
  3944. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  3945. baseMatrix.invertToRef(baseMatrix);
  3946. }
  3947. var babylonParentBone;
  3948. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  3949. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  3950. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3951. }
  3952. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3953. babylonBones[node.index] = babylonBone;
  3954. return babylonBone;
  3955. };
  3956. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3957. return node.matrix ?
  3958. BABYLON.Matrix.FromArray(node.matrix) :
  3959. 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());
  3960. };
  3961. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  3962. if (parentNode === void 0) { parentNode = null; }
  3963. for (var i = 0; i < indices.length; i++) {
  3964. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  3965. if (!node) {
  3966. throw new Error(context + ": Failed to find node " + indices[i]);
  3967. }
  3968. this._traverseNode(context, node, action, parentNode);
  3969. }
  3970. };
  3971. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  3972. if (parentNode === void 0) { parentNode = null; }
  3973. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  3974. return;
  3975. }
  3976. if (!action(node, parentNode)) {
  3977. return;
  3978. }
  3979. if (node.children) {
  3980. this._traverseNodes(context, node.children, action, node);
  3981. }
  3982. };
  3983. GLTFLoader.prototype._loadAnimations = function () {
  3984. var animations = this._gltf.animations;
  3985. if (!animations) {
  3986. return;
  3987. }
  3988. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  3989. var animation = animations[animationIndex];
  3990. var context = "#/animations/" + animationIndex;
  3991. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  3992. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  3993. if (!channel) {
  3994. throw new Error(context + ": Failed to find channel " + channelIndex);
  3995. }
  3996. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  3997. if (!sampler) {
  3998. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  3999. }
  4000. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  4001. }
  4002. }
  4003. };
  4004. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  4005. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  4006. if (!targetNode) {
  4007. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  4008. }
  4009. var targetPath;
  4010. var animationType;
  4011. switch (channel.target.path) {
  4012. case "translation":
  4013. targetPath = "position";
  4014. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4015. break;
  4016. case "rotation":
  4017. targetPath = "rotationQuaternion";
  4018. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  4019. break;
  4020. case "scale":
  4021. targetPath = "scaling";
  4022. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4023. break;
  4024. case "weights":
  4025. targetPath = "influence";
  4026. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  4027. break;
  4028. default:
  4029. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  4030. }
  4031. var inputData;
  4032. var outputData;
  4033. var checkSuccess = function () {
  4034. if (!inputData || !outputData) {
  4035. return;
  4036. }
  4037. var outputBufferOffset = 0;
  4038. var getNextOutputValue;
  4039. switch (targetPath) {
  4040. case "position":
  4041. getNextOutputValue = function () {
  4042. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  4043. outputBufferOffset += 3;
  4044. return value;
  4045. };
  4046. break;
  4047. case "rotationQuaternion":
  4048. getNextOutputValue = function () {
  4049. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  4050. outputBufferOffset += 4;
  4051. return value;
  4052. };
  4053. break;
  4054. case "scaling":
  4055. getNextOutputValue = function () {
  4056. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  4057. outputBufferOffset += 3;
  4058. return value;
  4059. };
  4060. break;
  4061. case "influence":
  4062. getNextOutputValue = function () {
  4063. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  4064. var value = new Array(numTargets);
  4065. for (var i = 0; i < numTargets; i++) {
  4066. value[i] = outputData[outputBufferOffset++];
  4067. }
  4068. return value;
  4069. };
  4070. break;
  4071. }
  4072. var getNextKey;
  4073. switch (sampler.interpolation) {
  4074. case "LINEAR":
  4075. getNextKey = function (frameIndex) { return ({
  4076. frame: inputData[frameIndex],
  4077. value: getNextOutputValue()
  4078. }); };
  4079. break;
  4080. case "CUBICSPLINE":
  4081. getNextKey = function (frameIndex) { return ({
  4082. frame: inputData[frameIndex],
  4083. inTangent: getNextOutputValue(),
  4084. value: getNextOutputValue(),
  4085. outTangent: getNextOutputValue()
  4086. }); };
  4087. break;
  4088. default:
  4089. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  4090. }
  4091. ;
  4092. var keys = new Array(inputData.length);
  4093. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  4094. keys[frameIndex] = getNextKey(frameIndex);
  4095. }
  4096. animation.targets = animation.targets || [];
  4097. if (targetPath === "influence") {
  4098. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  4099. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  4100. var morphTarget = morphTargetManager.getTarget(targetIndex);
  4101. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  4102. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4103. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4104. frame: key.frame,
  4105. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4106. value: key.value[targetIndex],
  4107. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4108. }); }));
  4109. morphTarget.animations.push(babylonAnimation);
  4110. animation.targets.push(morphTarget);
  4111. }
  4112. }
  4113. else {
  4114. var animationName = animation.name || "anim" + animation.index;
  4115. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4116. babylonAnimation.setKeys(keys);
  4117. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  4118. var target = targetNode.babylonAnimationTargets[i];
  4119. target.animations.push(babylonAnimation.clone());
  4120. animation.targets.push(target);
  4121. }
  4122. }
  4123. };
  4124. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  4125. if (!inputAccessor) {
  4126. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  4127. }
  4128. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  4129. inputData = data;
  4130. checkSuccess();
  4131. });
  4132. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  4133. if (!outputAccessor) {
  4134. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  4135. }
  4136. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  4137. outputData = data;
  4138. checkSuccess();
  4139. });
  4140. };
  4141. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  4142. var _this = this;
  4143. this._addPendingData(buffer);
  4144. if (buffer.loadedData) {
  4145. onSuccess(buffer.loadedData);
  4146. this._removePendingData(buffer);
  4147. }
  4148. else if (buffer.loadedObservable) {
  4149. buffer.loadedObservable.add(function (buffer) {
  4150. onSuccess(buffer.loadedData);
  4151. _this._removePendingData(buffer);
  4152. });
  4153. }
  4154. else {
  4155. if (!buffer.uri) {
  4156. throw new Error(context + ": Uri is missing");
  4157. }
  4158. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  4159. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  4160. buffer.loadedData = new Uint8Array(data);
  4161. onSuccess(buffer.loadedData);
  4162. this._removePendingData(buffer);
  4163. }
  4164. else {
  4165. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  4166. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  4167. }
  4168. buffer.loadedObservable = new BABYLON.Observable();
  4169. buffer.loadedObservable.add(function (buffer) {
  4170. onSuccess(buffer.loadedData);
  4171. _this._removePendingData(buffer);
  4172. });
  4173. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  4174. _this._tryCatchOnError(function () {
  4175. buffer.loadedData = new Uint8Array(data);
  4176. buffer.loadedObservable.notifyObservers(buffer);
  4177. buffer.loadedObservable = null;
  4178. });
  4179. }, function (event) {
  4180. _this._tryCatchOnError(function () {
  4181. _this._onProgress(event);
  4182. });
  4183. }, this._babylonScene.database, true, function (request) {
  4184. _this._tryCatchOnError(function () {
  4185. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  4186. });
  4187. });
  4188. }
  4189. }
  4190. };
  4191. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  4192. var _this = this;
  4193. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  4194. if (!buffer) {
  4195. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  4196. }
  4197. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  4198. if (_this._disposed) {
  4199. return;
  4200. }
  4201. try {
  4202. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4203. }
  4204. catch (e) {
  4205. throw new Error(context + ": " + e.message);
  4206. }
  4207. onSuccess(data);
  4208. });
  4209. };
  4210. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  4211. var _this = this;
  4212. if (accessor.sparse) {
  4213. throw new Error(context + ": Sparse accessors are not currently supported");
  4214. }
  4215. if (accessor.normalized) {
  4216. throw new Error(context + ": Normalized accessors are not currently supported");
  4217. }
  4218. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  4219. if (!bufferView) {
  4220. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  4221. }
  4222. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  4223. var numComponents = _this._getNumComponentsOfType(accessor.type);
  4224. if (numComponents === 0) {
  4225. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  4226. }
  4227. var data;
  4228. switch (accessor.componentType) {
  4229. case GLTF2.EComponentType.BYTE:
  4230. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4231. break;
  4232. case GLTF2.EComponentType.UNSIGNED_BYTE:
  4233. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4234. break;
  4235. case GLTF2.EComponentType.SHORT:
  4236. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4237. break;
  4238. case GLTF2.EComponentType.UNSIGNED_SHORT:
  4239. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4240. break;
  4241. case GLTF2.EComponentType.UNSIGNED_INT:
  4242. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4243. break;
  4244. case GLTF2.EComponentType.FLOAT:
  4245. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  4246. break;
  4247. default:
  4248. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  4249. }
  4250. onSuccess(data);
  4251. });
  4252. };
  4253. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  4254. switch (type) {
  4255. case "SCALAR": return 1;
  4256. case "VEC2": return 2;
  4257. case "VEC3": return 3;
  4258. case "VEC4": return 4;
  4259. case "MAT2": return 4;
  4260. case "MAT3": return 9;
  4261. case "MAT4": return 16;
  4262. }
  4263. return 0;
  4264. };
  4265. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  4266. try {
  4267. var byteOffset = data.byteOffset + (byteOffset || 0);
  4268. var targetLength = count * numComponents;
  4269. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  4270. return new typedArray(data.buffer, byteOffset, targetLength);
  4271. }
  4272. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  4273. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  4274. var targetBuffer = new typedArray(targetLength);
  4275. var sourceIndex = 0;
  4276. var targetIndex = 0;
  4277. while (targetIndex < targetLength) {
  4278. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4279. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  4280. targetIndex++;
  4281. }
  4282. sourceIndex += elementStride;
  4283. }
  4284. return targetBuffer;
  4285. }
  4286. catch (e) {
  4287. throw new Error(context + ": " + e);
  4288. }
  4289. };
  4290. GLTFLoader.prototype._addPendingData = function (data) {
  4291. if (!this._renderReady) {
  4292. this._renderPendingCount++;
  4293. }
  4294. this._addLoaderPendingData(data);
  4295. };
  4296. GLTFLoader.prototype._removePendingData = function (data) {
  4297. if (!this._renderReady) {
  4298. if (--this._renderPendingCount === 0) {
  4299. this._renderReady = true;
  4300. this._onRenderReady();
  4301. }
  4302. }
  4303. this._removeLoaderPendingData(data);
  4304. };
  4305. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  4306. this._loaderPendingCount++;
  4307. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  4308. };
  4309. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  4310. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  4311. if (--this._loaderPendingCount === 0) {
  4312. this._onComplete();
  4313. }
  4314. };
  4315. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  4316. var _this = this;
  4317. var tracker = new GLTFLoaderTracker(function () {
  4318. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  4319. onComplete();
  4320. });
  4321. this._loaderTrackers.push(tracker);
  4322. this._addLoaderPendingData(tracker);
  4323. action();
  4324. this._removeLoaderPendingData(tracker);
  4325. };
  4326. GLTFLoader.prototype._getDefaultMaterial = function () {
  4327. if (!this._defaultMaterial) {
  4328. var id = "__gltf_default";
  4329. var material = this._babylonScene.getMaterialByName(id);
  4330. if (!material) {
  4331. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  4332. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  4333. material.metallic = 1;
  4334. material.roughness = 1;
  4335. }
  4336. this._defaultMaterial = material;
  4337. }
  4338. return this._defaultMaterial;
  4339. };
  4340. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  4341. var babylonMaterial = material.babylonMaterial;
  4342. // Ensure metallic workflow
  4343. babylonMaterial.metallic = 1;
  4344. babylonMaterial.roughness = 1;
  4345. var properties = material.pbrMetallicRoughness;
  4346. if (!properties) {
  4347. return;
  4348. }
  4349. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  4350. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  4351. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  4352. if (properties.baseColorTexture) {
  4353. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  4354. if (!texture) {
  4355. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  4356. }
  4357. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  4358. }
  4359. if (properties.metallicRoughnessTexture) {
  4360. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  4361. if (!texture) {
  4362. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  4363. }
  4364. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  4365. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4366. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4367. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4368. }
  4369. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  4370. };
  4371. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  4372. if (material.babylonMaterial) {
  4373. assign(material.babylonMaterial, false);
  4374. return;
  4375. }
  4376. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  4377. return;
  4378. }
  4379. this._createPbrMaterial(material);
  4380. this._loadMaterialBaseProperties(context, material);
  4381. this._loadMaterialMetallicRoughnessProperties(context, material);
  4382. assign(material.babylonMaterial, true);
  4383. };
  4384. GLTFLoader.prototype._createPbrMaterial = function (material) {
  4385. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  4386. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  4387. material.babylonMaterial = babylonMaterial;
  4388. };
  4389. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  4390. var babylonMaterial = material.babylonMaterial;
  4391. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4392. if (material.doubleSided) {
  4393. babylonMaterial.backFaceCulling = false;
  4394. babylonMaterial.twoSidedLighting = true;
  4395. }
  4396. if (material.normalTexture) {
  4397. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  4398. if (!texture) {
  4399. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  4400. }
  4401. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  4402. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  4403. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  4404. if (material.normalTexture.scale != null) {
  4405. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4406. }
  4407. }
  4408. if (material.occlusionTexture) {
  4409. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  4410. if (!texture) {
  4411. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  4412. }
  4413. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  4414. babylonMaterial.useAmbientInGrayScale = true;
  4415. if (material.occlusionTexture.strength != null) {
  4416. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4417. }
  4418. }
  4419. if (material.emissiveTexture) {
  4420. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  4421. if (!texture) {
  4422. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  4423. }
  4424. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  4425. }
  4426. };
  4427. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  4428. var babylonMaterial = material.babylonMaterial;
  4429. var alphaMode = material.alphaMode || "OPAQUE";
  4430. switch (alphaMode) {
  4431. case "OPAQUE":
  4432. // default is opaque
  4433. break;
  4434. case "MASK":
  4435. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  4436. if (colorFactor) {
  4437. if (colorFactor[3] == 0) {
  4438. babylonMaterial.alphaCutOff = 1;
  4439. }
  4440. else {
  4441. babylonMaterial.alphaCutOff /= colorFactor[3];
  4442. }
  4443. }
  4444. if (babylonMaterial.albedoTexture) {
  4445. babylonMaterial.albedoTexture.hasAlpha = true;
  4446. }
  4447. break;
  4448. case "BLEND":
  4449. if (colorFactor) {
  4450. babylonMaterial.alpha = colorFactor[3];
  4451. }
  4452. if (babylonMaterial.albedoTexture) {
  4453. babylonMaterial.albedoTexture.hasAlpha = true;
  4454. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4455. }
  4456. break;
  4457. default:
  4458. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  4459. }
  4460. };
  4461. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  4462. var _this = this;
  4463. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  4464. if (!sampler) {
  4465. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  4466. }
  4467. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  4468. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  4469. this._addPendingData(texture);
  4470. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  4471. _this._tryCatchOnError(function () {
  4472. _this._removePendingData(texture);
  4473. });
  4474. }, function (message) {
  4475. _this._tryCatchOnError(function () {
  4476. throw new Error(context + ": " + message);
  4477. });
  4478. });
  4479. if (texture.url) {
  4480. babylonTexture.updateURL(texture.url);
  4481. }
  4482. else if (texture.dataReadyObservable) {
  4483. texture.dataReadyObservable.add(function (texture) {
  4484. babylonTexture.updateURL(texture.url);
  4485. });
  4486. }
  4487. else {
  4488. texture.dataReadyObservable = new BABYLON.Observable();
  4489. texture.dataReadyObservable.add(function (texture) {
  4490. babylonTexture.updateURL(texture.url);
  4491. });
  4492. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  4493. if (!image) {
  4494. throw new Error(context + ": Failed to find source " + texture.source);
  4495. }
  4496. this._loadImage("#/images/" + image.index, image, function (data) {
  4497. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  4498. texture.dataReadyObservable.notifyObservers(texture);
  4499. });
  4500. }
  4501. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  4502. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  4503. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  4504. babylonTexture.name = texture.name || "texture" + texture.index;
  4505. if (this._parent.onTextureLoaded) {
  4506. this._parent.onTextureLoaded(babylonTexture);
  4507. }
  4508. return babylonTexture;
  4509. };
  4510. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  4511. var _this = this;
  4512. if (image.uri) {
  4513. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  4514. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  4515. }
  4516. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  4517. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  4518. }
  4519. else {
  4520. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  4521. _this._tryCatchOnError(function () {
  4522. onSuccess(data);
  4523. });
  4524. }, function (event) {
  4525. _this._tryCatchOnError(function () {
  4526. _this._onProgress(event);
  4527. });
  4528. }, this._babylonScene.database, true, function (request) {
  4529. _this._tryCatchOnError(function () {
  4530. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  4531. });
  4532. });
  4533. }
  4534. }
  4535. else {
  4536. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  4537. if (!bufferView) {
  4538. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  4539. }
  4540. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  4541. }
  4542. };
  4543. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  4544. try {
  4545. handler();
  4546. }
  4547. catch (e) {
  4548. this._onError(e.message);
  4549. }
  4550. };
  4551. GLTFLoader.Extensions = {};
  4552. return GLTFLoader;
  4553. }());
  4554. GLTF2.GLTFLoader = GLTFLoader;
  4555. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  4556. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4557. })(BABYLON || (BABYLON = {}));
  4558. //# sourceMappingURL=babylon.glTFLoader.js.map
  4559. var BABYLON;
  4560. (function (BABYLON) {
  4561. var GLTF2;
  4562. (function (GLTF2) {
  4563. /**
  4564. * Utils functions for GLTF
  4565. */
  4566. var GLTFUtils = /** @class */ (function () {
  4567. function GLTFUtils() {
  4568. }
  4569. /**
  4570. * If the uri is a base64 string
  4571. * @param uri: the uri to test
  4572. */
  4573. GLTFUtils.IsBase64 = function (uri) {
  4574. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  4575. };
  4576. /**
  4577. * Decode the base64 uri
  4578. * @param uri: the uri to decode
  4579. */
  4580. GLTFUtils.DecodeBase64 = function (uri) {
  4581. var decodedString = atob(uri.split(",")[1]);
  4582. var bufferLength = decodedString.length;
  4583. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  4584. for (var i = 0; i < bufferLength; i++) {
  4585. bufferView[i] = decodedString.charCodeAt(i);
  4586. }
  4587. return bufferView.buffer;
  4588. };
  4589. GLTFUtils.ValidateUri = function (uri) {
  4590. return (uri.indexOf("..") === -1);
  4591. };
  4592. GLTFUtils.AssignIndices = function (array) {
  4593. if (array) {
  4594. for (var index = 0; index < array.length; index++) {
  4595. array[index].index = index;
  4596. }
  4597. }
  4598. };
  4599. GLTFUtils.GetArrayItem = function (array, index) {
  4600. if (!array || !array[index]) {
  4601. return null;
  4602. }
  4603. return array[index];
  4604. };
  4605. GLTFUtils.GetTextureWrapMode = function (mode) {
  4606. // Set defaults if undefined
  4607. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  4608. switch (mode) {
  4609. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4610. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4611. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4612. default:
  4613. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  4614. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4615. }
  4616. };
  4617. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  4618. // Set defaults if undefined
  4619. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  4620. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  4621. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  4622. switch (minFilter) {
  4623. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  4624. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  4625. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4626. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4627. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4628. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4629. default:
  4630. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  4631. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4632. }
  4633. }
  4634. else {
  4635. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  4636. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  4637. }
  4638. switch (minFilter) {
  4639. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  4640. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  4641. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4642. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4643. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4644. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4645. default:
  4646. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  4647. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4648. }
  4649. }
  4650. };
  4651. return GLTFUtils;
  4652. }());
  4653. GLTF2.GLTFUtils = GLTFUtils;
  4654. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4655. })(BABYLON || (BABYLON = {}));
  4656. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  4657. var BABYLON;
  4658. (function (BABYLON) {
  4659. var GLTF2;
  4660. (function (GLTF2) {
  4661. var GLTFLoaderExtension = /** @class */ (function () {
  4662. function GLTFLoaderExtension() {
  4663. this.enabled = true;
  4664. }
  4665. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  4666. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  4667. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  4668. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  4669. var _this = this;
  4670. if (!property.extensions) {
  4671. return false;
  4672. }
  4673. var extension = property.extensions[this.name];
  4674. if (!extension) {
  4675. return false;
  4676. }
  4677. // Clear out the extension before executing the action to avoid recursing into the same property.
  4678. property.extensions[this.name] = undefined;
  4679. action(extension, function () {
  4680. // Restore the extension after completing the action.
  4681. property.extensions[_this.name] = extension;
  4682. });
  4683. return true;
  4684. };
  4685. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  4686. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  4687. };
  4688. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  4689. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  4690. };
  4691. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  4692. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  4693. };
  4694. GLTFLoaderExtension._ApplyExtensions = function (action) {
  4695. var extensions = GLTFLoaderExtension._Extensions;
  4696. if (!extensions) {
  4697. return false;
  4698. }
  4699. for (var i = 0; i < extensions.length; i++) {
  4700. var extension = extensions[i];
  4701. if (extension.enabled && action(extension)) {
  4702. return true;
  4703. }
  4704. }
  4705. return false;
  4706. };
  4707. //
  4708. // Utilities
  4709. //
  4710. GLTFLoaderExtension._Extensions = [];
  4711. return GLTFLoaderExtension;
  4712. }());
  4713. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4714. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4715. })(BABYLON || (BABYLON = {}));
  4716. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4717. var BABYLON;
  4718. (function (BABYLON) {
  4719. var GLTF2;
  4720. (function (GLTF2) {
  4721. var Extensions;
  4722. (function (Extensions) {
  4723. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  4724. var MSFTLOD = /** @class */ (function (_super) {
  4725. __extends(MSFTLOD, _super);
  4726. function MSFTLOD() {
  4727. return _super !== null && _super.apply(this, arguments) || this;
  4728. }
  4729. Object.defineProperty(MSFTLOD.prototype, "name", {
  4730. get: function () {
  4731. return "MSFT_lod";
  4732. },
  4733. enumerable: true,
  4734. configurable: true
  4735. });
  4736. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  4737. return this._loadExtension(node, function (extension, onComplete) {
  4738. for (var i = extension.ids.length - 1; i >= 0; i--) {
  4739. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  4740. if (!lodNode) {
  4741. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  4742. }
  4743. loader._traverseNode(context, lodNode, action, parentNode);
  4744. }
  4745. loader._traverseNode(context, node, action, parentNode);
  4746. onComplete();
  4747. });
  4748. };
  4749. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  4750. var _this = this;
  4751. return this._loadExtension(node, function (extension, onComplete) {
  4752. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  4753. loader._addLoaderPendingData(node);
  4754. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  4755. loader._removeLoaderPendingData(node);
  4756. onComplete();
  4757. });
  4758. });
  4759. };
  4760. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  4761. var _this = this;
  4762. loader._whenAction(function () {
  4763. loader._loadNode(context, nodes[index]);
  4764. }, function () {
  4765. if (index !== nodes.length - 1) {
  4766. var previousNode = nodes[index + 1];
  4767. previousNode.babylonMesh.setEnabled(false);
  4768. }
  4769. if (index === 0) {
  4770. onComplete();
  4771. return;
  4772. }
  4773. setTimeout(function () {
  4774. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  4775. }, MSFTLOD.MinimalLODDelay);
  4776. });
  4777. };
  4778. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  4779. var _this = this;
  4780. return this._loadExtension(material, function (extension, onComplete) {
  4781. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  4782. loader._addLoaderPendingData(material);
  4783. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  4784. material.extensions[_this.name] = extension;
  4785. loader._removeLoaderPendingData(material);
  4786. onComplete();
  4787. });
  4788. });
  4789. };
  4790. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  4791. var _this = this;
  4792. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  4793. assign(babylonMaterial, isNew);
  4794. if (index === 0) {
  4795. onComplete();
  4796. return;
  4797. }
  4798. // Load the next LOD when the loader is ready to render and
  4799. // all active material textures of the current LOD are loaded.
  4800. loader._executeWhenRenderReady(function () {
  4801. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  4802. setTimeout(function () {
  4803. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  4804. }, MSFTLOD.MinimalLODDelay);
  4805. });
  4806. });
  4807. });
  4808. };
  4809. /**
  4810. * Specify the minimal delay between LODs in ms (default = 250)
  4811. */
  4812. MSFTLOD.MinimalLODDelay = 250;
  4813. return MSFTLOD;
  4814. }(GLTF2.GLTFLoaderExtension));
  4815. Extensions.MSFTLOD = MSFTLOD;
  4816. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  4817. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4818. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4819. })(BABYLON || (BABYLON = {}));
  4820. //# sourceMappingURL=MSFT_lod.js.map
  4821. var BABYLON;
  4822. (function (BABYLON) {
  4823. var GLTF2;
  4824. (function (GLTF2) {
  4825. var Extensions;
  4826. (function (Extensions) {
  4827. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  4828. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  4829. function KHRMaterialsPbrSpecularGlossiness() {
  4830. return _super !== null && _super.apply(this, arguments) || this;
  4831. }
  4832. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  4833. get: function () {
  4834. return "KHR_materials_pbrSpecularGlossiness";
  4835. },
  4836. enumerable: true,
  4837. configurable: true
  4838. });
  4839. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  4840. var _this = this;
  4841. return this._loadExtension(material, function (extension, onComplete) {
  4842. loader._createPbrMaterial(material);
  4843. loader._loadMaterialBaseProperties(context, material);
  4844. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  4845. assign(material.babylonMaterial, true);
  4846. });
  4847. };
  4848. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  4849. var babylonMaterial = material.babylonMaterial;
  4850. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  4851. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  4852. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  4853. if (properties.diffuseTexture) {
  4854. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  4855. if (!texture) {
  4856. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  4857. }
  4858. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  4859. }
  4860. if (properties.specularGlossinessTexture) {
  4861. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  4862. if (!texture) {
  4863. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  4864. }
  4865. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  4866. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4867. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4868. }
  4869. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  4870. };
  4871. return KHRMaterialsPbrSpecularGlossiness;
  4872. }(GLTF2.GLTFLoaderExtension));
  4873. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  4874. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  4875. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4876. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4877. })(BABYLON || (BABYLON = {}));
  4878. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4879. (function universalModuleDefinition(root, factory) {
  4880. if (root && root["BABYLON"]) {
  4881. return;
  4882. }
  4883. if(typeof exports === 'object' && typeof module === 'object')
  4884. module.exports = factory();
  4885. else if(typeof define === 'function' && define.amd)
  4886. define([], factory);
  4887. else if(typeof exports === 'object')
  4888. exports["BJSLoaders"] = factory();
  4889. else {
  4890. root["BABYLON"] = factory();
  4891. }
  4892. })(this, function() {
  4893. return BABYLON;
  4894. });