babylonjs.loaders.js 277 KB

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