babylonjs.loaders.js 238 KB

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