babylonjs.loaders.js 276 KB

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