babylonjs.loaders.js 263 KB

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